code
stringlengths
2.5k
150k
kind
stringclasses
1 value
kotlin decodeToString decodeToString ============== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [decodeToString](decode-to-string) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` fun ByteArray.decodeToString(): String ``` Decodes a string from the bytes in UTF-8 encoding in this array. Malformed byte sequences are replaced by the replacement char `\uFFFD`. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` fun ByteArray.decodeToString(     startIndex: Int = 0,     endIndex: Int = this.size,     throwOnInvalidSequence: Boolean = false ): String ``` Decodes a string from the bytes in UTF-8 encoding in this array or its subrange. Parameters ---------- `startIndex` - the beginning (inclusive) of the subrange to decode, 0 by default. `endIndex` - the end (exclusive) of the subrange to decode, size of this array by default. `throwOnInvalidSequence` - specifies whether to throw an exception on malformed byte sequence or replace it by the replacement char `\uFFFD`. Exceptions ---------- `IndexOutOfBoundsException` - if [startIndex](decode-to-string#kotlin.text%24decodeToString(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/startIndex) is less than zero or [endIndex](decode-to-string#kotlin.text%24decodeToString(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/endIndex) is greater than the size of this array. `IllegalArgumentException` - if [startIndex](decode-to-string#kotlin.text%24decodeToString(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/startIndex) is greater than [endIndex](decode-to-string#kotlin.text%24decodeToString(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/endIndex). `CharacterCodingException` - if the byte array contains malformed UTF-8 byte sequence and [throwOnInvalidSequence](decode-to-string#kotlin.text%24decodeToString(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/throwOnInvalidSequence) is true. kotlin isDigit isDigit ======= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [isDigit](is-digit) **Platform and version requirements:** JVM (1.0), JS (1.5) ``` fun Char.isDigit(): Boolean ``` Returns `true` if this character is a digit. A character is considered to be a digit if its category is [CharCategory.DECIMAL\_DIGIT\_NUMBER](-char-category/-d-e-c-i-m-a-l_-d-i-g-i-t_-n-u-m-b-e-r#kotlin.text.CharCategory.DECIMAL_DIGIT_NUMBER). ``` import java.util.* import kotlin.test.* fun main(args: Array<String>) { //sampleStart val chars = listOf('a', '+', '1') val (digits, notDigits) = chars.partition { it.isDigit() } println(digits) // [1] println(notDigits) // [a, +] //sampleEnd } ``` kotlin associateBy associateBy =========== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [associateBy](associate-by) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <K> CharSequence.associateBy(     keySelector: (Char) -> K ): Map<K, Char> ``` Returns a [Map](../kotlin.collections/-map/index#kotlin.collections.Map) containing the characters from the given char sequence indexed by the key returned from [keySelector](associate-by#kotlin.text%24associateBy(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateBy.K)))/keySelector) function applied to each character. If any two characters would have the same key returned by [keySelector](associate-by#kotlin.text%24associateBy(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateBy.K)))/keySelector) the last one gets added to the map. The returned map preserves the entry iteration order of the original char sequence. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val string = "bonne journée" // associate each character by its code val result = string.associateBy { char -> char.code } // notice each char code occurs only once println(result) // {98=b, 111=o, 110=n, 101=e, 32= , 106=j, 117=u, 114=r, 233=é} //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <K, V> CharSequence.associateBy(     keySelector: (Char) -> K,     valueTransform: (Char) -> V ): Map<K, V> ``` Returns a [Map](../kotlin.collections/-map/index#kotlin.collections.Map) containing the values provided by [valueTransform](associate-by#kotlin.text%24associateBy(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateBy.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateBy.V)))/valueTransform) and indexed by [keySelector](associate-by#kotlin.text%24associateBy(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateBy.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateBy.V)))/keySelector) functions applied to characters of the given char sequence. If any two characters would have the same key returned by [keySelector](associate-by#kotlin.text%24associateBy(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateBy.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateBy.V)))/keySelector) the last one gets added to the map. The returned map preserves the entry iteration order of the original char sequence. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val string = "bonne journée" // associate each character by the code of its upper case equivalent and transform the character to upper case val result = string.associateBy({ char -> char.uppercaseChar().code }, { char -> char.uppercaseChar() }) // notice each char code occurs only once println(result) // {66=B, 79=O, 78=N, 69=E, 32= , 74=J, 85=U, 82=R, 201=É} //sampleEnd } ``` kotlin filterNotTo filterNotTo =========== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [filterNotTo](filter-not-to) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <C : Appendable> CharSequence.filterNotTo(     destination: C,     predicate: (Char) -> Boolean ): C ``` Appends all characters not matching the given [predicate](filter-not-to#kotlin.text%24filterNotTo(kotlin.CharSequence,%20kotlin.text.filterNotTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate) to the given [destination](filter-not-to#kotlin.text%24filterNotTo(kotlin.CharSequence,%20kotlin.text.filterNotTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/destination). ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val numbers: List<Int> = listOf(1, 2, 3, 4, 5, 6, 7) val evenNumbers = mutableListOf<Int>() val notMultiplesOf3 = mutableListOf<Int>() println(evenNumbers) // [] numbers.filterTo(evenNumbers) { it % 2 == 0 } numbers.filterNotTo(notMultiplesOf3) { number -> number % 3 == 0 } println(evenNumbers) // [2, 4, 6] println(notMultiplesOf3) // [1, 2, 4, 5, 7] //sampleEnd } ``` kotlin reversed reversed ======== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <reversed> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.reversed(): CharSequence ``` Returns a char sequence with characters in reversed order. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.reversed(): String ``` Returns a string with characters in reversed order. kotlin subSequence subSequence =========== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [subSequence](sub-sequence) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.subSequence(range: IntRange): CharSequence ``` Returns a subsequence of this char sequence specified by the given [range](sub-sequence#kotlin.text%24subSequence(kotlin.CharSequence,%20kotlin.ranges.IntRange)/range) of indices. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.subSequence(start: Int, end: Int): CharSequence ``` **Deprecated:** Use parameters named startIndex and endIndex. Returns a subsequence of this char sequence. This extension is chosen only for invocation with old-named parameters. Replace parameter names with the same as those of [CharSequence.subSequence](../kotlin/-char-sequence/sub-sequence#kotlin.CharSequence%24subSequence(kotlin.Int,%20kotlin.Int)). kotlin equals equals ====== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <equals> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String?.equals(     other: String?,     ignoreCase: Boolean = false ): Boolean ``` Returns `true` if this string is equal to [other](equals#kotlin.text%24equals(kotlin.String?,%20kotlin.String?,%20kotlin.Boolean)/other), optionally ignoring character case. Two strings are considered to be equal if they have the same length and the same character at the same index. If [ignoreCase](equals#kotlin.text%24equals(kotlin.String?,%20kotlin.String?,%20kotlin.Boolean)/ignoreCase) is true, the result of `Char.uppercaseChar().lowercaseChar()` on each character is compared. Parameters ---------- `ignoreCase` - `true` to ignore character case when comparing strings. By default `false`. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun Char.equals(     other: Char,     ignoreCase: Boolean = false ): Boolean ``` Returns `true` if this character is equal to the [other](equals#kotlin.text%24equals(kotlin.Char,%20kotlin.Char,%20kotlin.Boolean)/other) character, optionally ignoring character case. Two characters are considered equal ignoring case if `Char.uppercaseChar().lowercaseChar()` on each character produces the same result. ``` import java.util.* import kotlin.test.* fun main(args: Array<String>) { //sampleStart println("'a'.equals('a', false) is ${'a'.equals('a', false)}") // true println("'a'.equals('A', false) is ${'a'.equals('A', false)}") // false println("'a'.equals('A', true) is ${'a'.equals('A', true)}") // true //sampleEnd } ``` Parameters ---------- `ignoreCase` - `true` to ignore character case when comparing characters. By default `false`. kotlin toBooleanStrictOrNull toBooleanStrictOrNull ===================== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [toBooleanStrictOrNull](to-boolean-strict-or-null) **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun String.toBooleanStrictOrNull(): Boolean? ``` Returns `true` if the content of this string is equal to the word "true", `false` if it is equal to "false", and `null` otherwise. There is also a lenient version of the function available on nullable String, String?.toBoolean. Note that this function is case-sensitive. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart println("true".toBooleanStrictOrNull()) // true println("True".toBooleanStrictOrNull()) // null println("TRUE".toBooleanStrictOrNull()) // null println("false".toBooleanStrictOrNull()) // false println("False".toBooleanStrictOrNull()) // null println("FALSE".toBooleanStrictOrNull()) // null println("abc".toBooleanStrictOrNull()) // null //sampleEnd } ``` kotlin isIdentifierIgnorable isIdentifierIgnorable ===================== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [isIdentifierIgnorable](is-identifier-ignorable) **Platform and version requirements:** JVM (1.0), Native (1.3) ``` fun Char.isIdentifierIgnorable(): Boolean ``` Returns `true` if this character (Unicode code point) should be regarded as an ignorable character in a Java identifier or a Unicode identifier. kotlin replaceBefore replaceBefore ============= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [replaceBefore](replace-before) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.replaceBefore(     delimiter: Char,     replacement: String,     missingDelimiterValue: String = this ): String ``` ``` fun String.replaceBefore(     delimiter: String,     replacement: String,     missingDelimiterValue: String = this ): String ``` Replace part of string before the first occurrence of given delimiter with the [replacement](replace-before#kotlin.text%24replaceBefore(kotlin.String,%20kotlin.Char,%20kotlin.String,%20kotlin.String)/replacement) string. If the string does not contain the delimiter, returns [missingDelimiterValue](replace-before#kotlin.text%24replaceBefore(kotlin.String,%20kotlin.Char,%20kotlin.String,%20kotlin.String)/missingDelimiterValue) which defaults to the original string. kotlin flatMapIndexedTo flatMapIndexedTo ================ [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [flatMapIndexedTo](flat-map-indexed-to) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` @JvmName("flatMapIndexedIterableTo") inline fun <R, C : MutableCollection<in R>> CharSequence.flatMapIndexedTo(     destination: C,     transform: (index: Int, Char) -> Iterable<R> ): C ``` Appends all elements yielded from results of [transform](flat-map-indexed-to#kotlin.text%24flatMapIndexedTo(kotlin.CharSequence,%20kotlin.text.flatMapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.collections.Iterable((kotlin.text.flatMapIndexedTo.R)))))/transform) function being invoked on each character and its index in the original char sequence, to the given [destination](flat-map-indexed-to#kotlin.text%24flatMapIndexedTo(kotlin.CharSequence,%20kotlin.text.flatMapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.collections.Iterable((kotlin.text.flatMapIndexedTo.R)))))/destination). kotlin minOfWithOrNull minOfWithOrNull =============== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [minOfWithOrNull](min-of-with-or-null) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` inline fun <R> CharSequence.minOfWithOrNull(     comparator: Comparator<in R>,     selector: (Char) -> R ): R? ``` Returns the smallest value according to the provided [comparator](min-of-with-or-null#kotlin.text%24minOfWithOrNull(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.minOfWithOrNull.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.minOfWithOrNull.R)))/comparator) among all values produced by [selector](min-of-with-or-null#kotlin.text%24minOfWithOrNull(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.minOfWithOrNull.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.minOfWithOrNull.R)))/selector) function applied to each character in the char sequence or `null` if there are no characters. kotlin startsWith startsWith ========== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [startsWith](starts-with) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.startsWith(     prefix: String,     ignoreCase: Boolean = false ): Boolean ``` Returns `true` if this string starts with the specified prefix. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.startsWith(     prefix: String,     startIndex: Int,     ignoreCase: Boolean = false ): Boolean ``` Returns `true` if a substring of this string starting at the specified offset [startIndex](starts-with#kotlin.text%24startsWith(kotlin.String,%20kotlin.String,%20kotlin.Int,%20kotlin.Boolean)/startIndex) starts with the specified prefix. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.startsWith(     char: Char,     ignoreCase: Boolean = false ): Boolean ``` Returns `true` if this char sequence starts with the specified character. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.startsWith(     prefix: CharSequence,     ignoreCase: Boolean = false ): Boolean ``` Returns `true` if this char sequence starts with the specified prefix. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.startsWith(     prefix: CharSequence,     startIndex: Int,     ignoreCase: Boolean = false ): Boolean ``` Returns `true` if a substring of this char sequence starting at the specified offset [startIndex](starts-with#kotlin.text%24startsWith(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Boolean)/startIndex) starts with the specified prefix. kotlin clear clear ===== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <clear> **Platform and version requirements:** JS (1.3) ``` fun StringBuilder.clear(): StringBuilder ``` Clears the content of this string builder making it empty and returns this instance. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val builder = StringBuilder() builder.append("content").append(1) println(builder) // content1 builder.clear() println(builder) // //sampleEnd } ``` kotlin removePrefix removePrefix ============ [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [removePrefix](remove-prefix) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.removePrefix(     prefix: CharSequence ): CharSequence ``` If this char sequence starts with the given [prefix](remove-prefix#kotlin.text%24removePrefix(kotlin.CharSequence,%20kotlin.CharSequence)/prefix), returns a new char sequence with the prefix removed. Otherwise, returns a new char sequence with the same characters. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.removePrefix(prefix: CharSequence): String ``` If this string starts with the given [prefix](remove-prefix#kotlin.text%24removePrefix(kotlin.String,%20kotlin.CharSequence)/prefix), returns a copy of this string with the prefix removed. Otherwise, returns this string. kotlin partition partition ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <partition> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun CharSequence.partition(     predicate: (Char) -> Boolean ): Pair<CharSequence, CharSequence> ``` Splits the original char sequence into pair of char sequences, where *first* char sequence contains characters for which [predicate](partition#kotlin.text%24partition(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate) yielded `true`, while *second* char sequence contains characters for which [predicate](partition#kotlin.text%24partition(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate) yielded `false`. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart fun isVowel(c: Char) = "aeuio".contains(c, ignoreCase = true) val string = "Discussion" val result = string.partition(::isVowel) println(result) // (iuio, Dscssn) //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun String.partition(     predicate: (Char) -> Boolean ): Pair<String, String> ``` Splits the original string into pair of strings, where *first* string contains characters for which [predicate](partition#kotlin.text%24partition(kotlin.String,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate) yielded `true`, while *second* string contains characters for which [predicate](partition#kotlin.text%24partition(kotlin.String,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate) yielded `false`. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart fun isVowel(c: Char) = "aeuio".contains(c, ignoreCase = true) val string = "Discussion" val result = string.partition(::isVowel) println(result) // (iuio, Dscssn) //sampleEnd } ```
programming_docs
kotlin uppercase uppercase ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <uppercase> **Platform and version requirements:** JVM (1.5), JS (1.5) ``` fun Char.uppercase(): String ``` Converts this character to upper case using Unicode mapping rules of the invariant locale. This function supports one-to-many character mapping, thus the length of the returned string can be greater than one. For example, `'\uFB00'.uppercase()` returns `"\u0046\u0046"`, where `'\uFB00'` is the LATIN SMALL LIGATURE FF character (`ff`). If this character has no upper case mapping, the result of `toString()` of this char is returned. ``` import java.util.* import kotlin.test.* fun main(args: Array<String>) { //sampleStart val chars = listOf('a', 'ω', '1', 'ʼn', 'A', '+', 'ß') val uppercaseChar = chars.map { it.uppercaseChar() } val uppercase = chars.map { it.uppercase() } println(uppercaseChar) // [A, Ω, 1, ʼn, A, +, ß] println(uppercase) // [A, Ω, 1, ʼN, A, +, SS] //sampleEnd } ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun String.uppercase(): String ``` Returns a copy of this string converted to upper case using Unicode mapping rules of the invariant locale. This function supports one-to-many and many-to-one character mapping, thus the length of the returned string can be different from the length of the original string. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart println("Iced frappé!".uppercase()) // ICED FRAPPÉ! //sampleEnd } ``` **Platform and version requirements:** JVM (1.5) ``` fun Char.uppercase(locale: Locale): String ``` Converts this character to upper case using Unicode mapping rules of the specified [locale](uppercase#kotlin.text%24uppercase(kotlin.Char,%20java.util.Locale)/locale). This function supports one-to-many character mapping, thus the length of the returned string can be greater than one. For example, `'\uFB00'.uppercase(Locale.US)` returns `"\u0046\u0046"`, where `'\uFB00'` is the LATIN SMALL LIGATURE FF character (`ff`). If this character has no upper case mapping, the result of `toString()` of this char is returned. ``` import java.util.* import kotlin.test.* fun main(args: Array<String>) { //sampleStart val chars = listOf('a', '1', 'ʼn', 'A', '+', 'i') val uppercase = chars.map { it.uppercase() } val turkishLocale = Locale.forLanguageTag("tr") val uppercaseTurkish = chars.map { it.uppercase(turkishLocale) } println(uppercase) // [A, 1, ʼN, A, +, I] println(uppercaseTurkish) // [A, 1, ʼN, A, +, İ] //sampleEnd } ``` **Platform and version requirements:** JVM (1.5) ``` fun String.uppercase(locale: Locale): String ``` Returns a copy of this string converted to upper case using the rules of the specified [locale](uppercase#kotlin.text%24uppercase(kotlin.String,%20java.util.Locale)/locale). This function supports one-to-many and many-to-one character mapping, thus the length of the returned string can be different from the length of the original string. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart println("Kotlin".uppercase()) // KOTLIN val turkishLocale = Locale.forLanguageTag("tr") println("Kotlin".uppercase(turkishLocale)) // KOTLİN //sampleEnd } ``` kotlin deleteAt deleteAt ======== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [deleteAt](delete-at) **Platform and version requirements:** JS (1.4) ``` fun StringBuilder.deleteAt(index: Int): StringBuilder ``` Removes the character at the specified [index](delete-at#kotlin.text%24deleteAt(kotlin.text.StringBuilder,%20kotlin.Int)/index) from this string builder and returns this instance. If the `Char` at the specified [index](delete-at#kotlin.text%24deleteAt(kotlin.text.StringBuilder,%20kotlin.Int)/index) is part of a supplementary code point, this method does not remove the entire supplementary character. Parameters ---------- `index` - the index of `Char` to remove. Exceptions ---------- `IndexOutOfBoundsException` - if [index](delete-at#kotlin.text%24deleteAt(kotlin.text.StringBuilder,%20kotlin.Int)/index) is out of bounds of this string builder. kotlin toBooleanStrict toBooleanStrict =============== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [toBooleanStrict](to-boolean-strict) **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun String.toBooleanStrict(): Boolean ``` Returns `true` if the content of this string is equal to the word "true", `false` if it is equal to "false", and throws an exception otherwise. There is also a lenient version of the function available on nullable String, String?.toBoolean. Note that this function is case-sensitive. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart println("true".toBooleanStrict()) // true // "True".toBooleanStrict() // will fail // "TRUE".toBooleanStrict() // will fail println("false".toBooleanStrict()) // false // "False".toBooleanStrict() // will fail // "FALSE".toBooleanStrict() // will fail // "abc".toBooleanStrict() // will fail //sampleEnd } ``` kotlin toRegex toRegex ======= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [toRegex](to-regex) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.toRegex(): Regex ``` Converts the string into a regular expression [Regex](-regex/index#kotlin.text.Regex) with the default options. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.toRegex(option: RegexOption): Regex ``` Converts the string into a regular expression [Regex](-regex/index#kotlin.text.Regex) with the specified single [option](to-regex#kotlin.text%24toRegex(kotlin.String,%20kotlin.text.RegexOption)/option). **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.toRegex(options: Set<RegexOption>): Regex ``` Converts the string into a regular expression [Regex](-regex/index#kotlin.text.Regex) with the specified set of [options](to-regex#kotlin.text%24toRegex(kotlin.String,%20kotlin.collections.Set((kotlin.text.RegexOption)))/options). kotlin onEachIndexed onEachIndexed ============= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [onEachIndexed](on-each-indexed) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` inline fun <S : CharSequence> S.onEachIndexed(     action: (index: Int, Char) -> Unit ): S ``` Performs the given [action](on-each-indexed#kotlin.text%24onEachIndexed(kotlin.text.onEachIndexed.S,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.Unit)))/action) on each character, providing sequential index with the character, and returns the char sequence itself afterwards. Parameters ---------- `action` - function that takes the index of a character and the character itself and performs the action on the character. kotlin indexOfLast indexOfLast =========== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [indexOfLast](index-of-last) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun CharSequence.indexOfLast(     predicate: (Char) -> Boolean ): Int ``` Returns index of the last character matching the given [predicate](index-of-last#kotlin.text%24indexOfLast(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate), or -1 if the char sequence does not contain such character. kotlin findAnyOf findAnyOf ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [findAnyOf](find-any-of) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.findAnyOf(     strings: Collection<String>,     startIndex: Int = 0,     ignoreCase: Boolean = false ): Pair<Int, String>? ``` Finds the first occurrence of any of the specified [strings](find-any-of#kotlin.text%24findAnyOf(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) in this char sequence, starting from the specified [startIndex](find-any-of#kotlin.text%24findAnyOf(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/startIndex) and optionally ignoring the case. Parameters ---------- `ignoreCase` - `true` to ignore character case when matching a string. By default `false`. **Return** A pair of an index of the first occurrence of matched string from [strings](find-any-of#kotlin.text%24findAnyOf(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) and the string matched or `null` if none of [strings](find-any-of#kotlin.text%24findAnyOf(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) are found. To avoid ambiguous results when strings in [strings](find-any-of#kotlin.text%24findAnyOf(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) have characters in common, this method proceeds from the beginning to the end of this string, and finds at each position the first element in [strings](find-any-of#kotlin.text%24findAnyOf(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) that matches this string at that position. kotlin runningFoldIndexed runningFoldIndexed ================== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [runningFoldIndexed](running-fold-indexed) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` inline fun <R> CharSequence.runningFoldIndexed(     initial: R,     operation: (index: Int, acc: R, Char) -> R ): List<R> ``` Returns a list containing successive accumulation values generated by applying [operation](running-fold-indexed#kotlin.text%24runningFoldIndexed(kotlin.CharSequence,%20kotlin.text.runningFoldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.text.runningFoldIndexed.R,%20kotlin.Char,%20)))/operation) from left to right to each character, its index in the original char sequence and current accumulator value that starts with [initial](running-fold-indexed#kotlin.text%24runningFoldIndexed(kotlin.CharSequence,%20kotlin.text.runningFoldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.text.runningFoldIndexed.R,%20kotlin.Char,%20)))/initial) value. Note that `acc` value passed to [operation](running-fold-indexed#kotlin.text%24runningFoldIndexed(kotlin.CharSequence,%20kotlin.text.runningFoldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.text.runningFoldIndexed.R,%20kotlin.Char,%20)))/operation) function should not be mutated; otherwise it would affect the previous value in resulting list. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val strings = listOf("a", "b", "c", "d") println(strings.runningFold("s") { acc, string -> acc + string }) // [s, sa, sab, sabc, sabcd] println(strings.runningFoldIndexed("s") { index, acc, string -> acc + string + index }) // [s, sa0, sa0b1, sa0b1c2, sa0b1c2d3] println(emptyList<String>().runningFold("s") { _, _ -> "X" }) // [s] //sampleEnd } ``` Parameters ---------- `operation` - function that takes the index of a character, current accumulator value and the character itself, and calculates the next accumulator value. kotlin none none ==== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <none> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.none(): Boolean ``` Returns `true` if the char sequence has no characters. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val emptyList = emptyList<Int>() println("emptyList.none() is ${emptyList.none()}") // true val nonEmptyList = listOf("one", "two", "three") println("nonEmptyList.none() is ${nonEmptyList.none()}") // false //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun CharSequence.none(     predicate: (Char) -> Boolean ): Boolean ``` Returns `true` if no characters match the given [predicate](none#kotlin.text%24none(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val isEven: (Int) -> Boolean = { it % 2 == 0 } val zeroToTen = 0..10 println("zeroToTen.none { isEven(it) } is ${zeroToTen.none { isEven(it) }}") // false println("zeroToTen.none(isEven) is ${zeroToTen.none(isEven)}") // false val odds = zeroToTen.map { it * 2 + 1 } println("odds.none { isEven(it) } is ${odds.none { isEven(it) }}") // true val emptyList = emptyList<Int>() println("emptyList.none { true } is ${emptyList.none { true }}") // true //sampleEnd } ``` kotlin toFloat toFloat ======= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [toFloat](to-float) **Platform and version requirements:** JVM (1.0), JS (1.1), Native (1.3) ``` fun String.toFloat(): Float ``` Parses the string as a [Float](../kotlin/-float/index#kotlin.Float) number and returns the result. Exceptions ---------- `NumberFormatException` - if the string is not a valid representation of a number. kotlin maxByOrNull maxByOrNull =========== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [maxByOrNull](max-by-or-null) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` inline fun <R : Comparable<R>> CharSequence.maxByOrNull(     selector: (Char) -> R ): Char? ``` Returns the first character yielding the largest value of the given function or `null` if there are no characters. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val nameToAge = listOf("Alice" to 42, "Bob" to 28, "Carol" to 51) val oldestPerson = nameToAge.maxByOrNull { it.second } println(oldestPerson) // (Carol, 51) val emptyList = emptyList<Pair<String, Int>>() val emptyMax = emptyList.maxByOrNull { it.second } println(emptyMax) // null //sampleEnd } ``` kotlin maxOrNull maxOrNull ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [maxOrNull](max-or-null) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` fun CharSequence.maxOrNull(): Char? ``` Returns the largest character or `null` if there are no characters. kotlin chunkedSequence chunkedSequence =============== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [chunkedSequence](chunked-sequence) **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) ``` fun CharSequence.chunkedSequence(size: Int): Sequence<String> ``` Splits this char sequence into a sequence of strings each not exceeding the given [size](chunked-sequence#kotlin.text%24chunkedSequence(kotlin.CharSequence,%20kotlin.Int)/size). The last string in the resulting sequence may have fewer characters than the given [size](chunked-sequence#kotlin.text%24chunkedSequence(kotlin.CharSequence,%20kotlin.Int)/size). ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val words = "one two three four five six seven eight nine ten".split(' ') val chunks = words.chunked(3) println(chunks) // [[one, two, three], [four, five, six], [seven, eight, nine], [ten]] //sampleEnd } ``` Parameters ---------- `size` - the number of elements to take in each string, must be positive and can be greater than the number of elements in this char sequence. **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) ``` fun <R> CharSequence.chunkedSequence(     size: Int,     transform: (CharSequence) -> R ): Sequence<R> ``` Splits this char sequence into several char sequences each not exceeding the given [size](chunked-sequence#kotlin.text%24chunkedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunkedSequence.R)))/size) and applies the given [transform](chunked-sequence#kotlin.text%24chunkedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunkedSequence.R)))/transform) function to an each. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val codonTable = mapOf("ATT" to "Isoleucine", "CAA" to "Glutamine", "CGC" to "Arginine", "GGC" to "Glycine") val dnaFragment = "ATTCGCGGCCGCCAACGG" val proteins = dnaFragment.chunkedSequence(3) { codon: CharSequence -> codonTable[codon.toString()] ?: error("Unknown codon") } // sequence is evaluated lazily, so that unknown codon is not reached println(proteins.take(5).toList()) // [Isoleucine, Arginine, Glycine, Arginine, Glutamine] //sampleEnd } ``` Parameters ---------- `size` - the number of elements to take in each char sequence, must be positive and can be greater than the number of elements in this char sequence. **Return** sequence of results of the [transform](chunked-sequence#kotlin.text%24chunkedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunkedSequence.R)))/transform) applied to an each char sequence. Note that the char sequence passed to the [transform](chunked-sequence#kotlin.text%24chunkedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunkedSequence.R)))/transform) function is ephemeral and is valid only inside that function. You should not store it or allow it to escape in some way, unless you made a snapshot of it. The last char sequence may have fewer characters than the given [size](chunked-sequence#kotlin.text%24chunkedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunkedSequence.R)))/size). kotlin findLast findLast ======== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [findLast](find-last) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun CharSequence.findLast(     predicate: (Char) -> Boolean ): Char? ``` Returns the last character matching the given [predicate](find-last#kotlin.text%24findLast(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate), or `null` if no such character was found. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val numbers = listOf(1, 2, 3, 4, 5, 6, 7) val firstOdd = numbers.find { it % 2 != 0 } val lastEven = numbers.findLast { it % 2 == 0 } println(firstOdd) // 1 println(lastEven) // 6 //sampleEnd } ``` kotlin fold fold ==== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <fold> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <R> CharSequence.fold(     initial: R,     operation: (acc: R, Char) -> R ): R ``` Accumulates value starting with [initial](fold#kotlin.text%24fold(kotlin.CharSequence,%20kotlin.text.fold.R,%20kotlin.Function2((kotlin.text.fold.R,%20kotlin.Char,%20)))/initial) value and applying [operation](fold#kotlin.text%24fold(kotlin.CharSequence,%20kotlin.text.fold.R,%20kotlin.Function2((kotlin.text.fold.R,%20kotlin.Char,%20)))/operation) from left to right to current accumulator value and each character. Returns the specified [initial](fold#kotlin.text%24fold(kotlin.CharSequence,%20kotlin.text.fold.R,%20kotlin.Function2((kotlin.text.fold.R,%20kotlin.Char,%20)))/initial) value if the char sequence is empty. Parameters ---------- `operation` - function that takes current accumulator value and a character, and calculates the next accumulator value. kotlin windowedSequence windowedSequence ================ [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [windowedSequence](windowed-sequence) **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) ``` fun CharSequence.windowedSequence(     size: Int,     step: Int = 1,     partialWindows: Boolean = false ): Sequence<String> ``` Returns a sequence of snapshots of the window of the given [size](windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/size) sliding along this char sequence with the given [step](windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/step), where each snapshot is a string. Several last strings may have fewer characters than the given [size](windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/size). Both [size](windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/size) and [step](windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/step) must be positive and can be greater than the number of elements in this char sequence. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val sequence = generateSequence(1) { it + 1 } val windows = sequence.windowed(size = 5, step = 1) println(windows.take(4).toList()) // [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]] val moreSparseWindows = sequence.windowed(size = 5, step = 3) println(moreSparseWindows.take(4).toList()) // [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8], [7, 8, 9, 10, 11], [10, 11, 12, 13, 14]] val fullWindows = sequence.take(10).windowed(size = 5, step = 3) println(fullWindows.toList()) // [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8]] val partialWindows = sequence.take(10).windowed(size = 5, step = 3, partialWindows = true) println(partialWindows.toList()) // [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8], [7, 8, 9, 10], [10]] //sampleEnd } ``` Parameters ---------- `size` - the number of elements to take in each window `step` - the number of elements to move the window forward by on an each step, by default 1 `partialWindows` - controls whether or not to keep partial windows in the end if any, by default `false` which means partial windows won't be preserved **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) ``` fun <R> CharSequence.windowedSequence(     size: Int,     step: Int = 1,     partialWindows: Boolean = false,     transform: (CharSequence) -> R ): Sequence<R> ``` Returns a sequence of results of applying the given [transform](windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.windowedSequence.R)))/transform) function to an each char sequence representing a view over the window of the given [size](windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.windowedSequence.R)))/size) sliding along this char sequence with the given [step](windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.windowedSequence.R)))/step). Note that the char sequence passed to the [transform](windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.windowedSequence.R)))/transform) function is ephemeral and is valid only inside that function. You should not store it or allow it to escape in some way, unless you made a snapshot of it. Several last char sequences may have fewer characters than the given [size](windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.windowedSequence.R)))/size). Both [size](windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.windowedSequence.R)))/size) and [step](windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.windowedSequence.R)))/step) must be positive and can be greater than the number of elements in this char sequence. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val dataPoints = sequenceOf(10, 15, 18, 25, 19, 21, 14, 8, 5) val averaged = dataPoints.windowed(size = 4, step = 1, partialWindows = true) { window -> window.average() } println(averaged.toList()) // [17.0, 19.25, 20.75, 19.75, 15.5, 12.0, 9.0, 6.5, 5.0] val averagedNoPartialWindows = dataPoints.windowed(size = 4, step = 1).map { it.average() } println(averagedNoPartialWindows.toList()) // [17.0, 19.25, 20.75, 19.75, 15.5, 12.0] //sampleEnd } ``` Parameters ---------- `size` - the number of elements to take in each window `step` - the number of elements to move the window forward by on an each step, by default 1 `partialWindows` - controls whether or not to keep partial windows in the end if any, by default `false` which means partial windows won't be preserved
programming_docs
kotlin minOrNull minOrNull ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [minOrNull](min-or-null) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` fun CharSequence.minOrNull(): Char? ``` Returns the smallest character or `null` if there are no characters. kotlin filterIndexedTo filterIndexedTo =============== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [filterIndexedTo](filter-indexed-to) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <C : Appendable> CharSequence.filterIndexedTo(     destination: C,     predicate: (index: Int, Char) -> Boolean ): C ``` Appends all characters matching the given [predicate](filter-indexed-to#kotlin.text%24filterIndexedTo(kotlin.CharSequence,%20kotlin.text.filterIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.Boolean)))/predicate) to the given [destination](filter-indexed-to#kotlin.text%24filterIndexedTo(kotlin.CharSequence,%20kotlin.text.filterIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.Boolean)))/destination). ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val numbers: List<Int> = listOf(0, 1, 2, 3, 4, 8, 6) val numbersOnSameIndexAsValue = mutableListOf<Int>() println(numbersOnSameIndexAsValue) // [] numbers.filterIndexedTo(numbersOnSameIndexAsValue) { index, i -> index == i } println(numbersOnSameIndexAsValue) // [0, 1, 2, 3, 4, 6] //sampleEnd } ``` Parameters ---------- `predicate` - function that takes the index of a character and the character itself and returns the result of predicate evaluation on the character. kotlin mapIndexedNotNullTo mapIndexedNotNullTo =================== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [mapIndexedNotNullTo](map-indexed-not-null-to) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <R : Any, C : MutableCollection<in R>> CharSequence.mapIndexedNotNullTo(     destination: C,     transform: (index: Int, Char) -> R? ): C ``` Applies the given [transform](map-indexed-not-null-to#kotlin.text%24mapIndexedNotNullTo(kotlin.CharSequence,%20kotlin.text.mapIndexedNotNullTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.text.mapIndexedNotNullTo.R?)))/transform) function to each character and its index in the original char sequence and appends only the non-null results to the given [destination](map-indexed-not-null-to#kotlin.text%24mapIndexedNotNullTo(kotlin.CharSequence,%20kotlin.text.mapIndexedNotNullTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.text.mapIndexedNotNullTo.R?)))/destination). Parameters ---------- `transform` - function that takes the index of a character and the character itself and returns the result of the transform applied to the character. kotlin elementAt elementAt ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [elementAt](element-at) **Platform and version requirements:** JVM (1.0), JS (1.1), Native (1.3) ``` fun CharSequence.elementAt(index: Int): Char ``` Returns a character at the given [index](element-at#kotlin.text%24elementAt(kotlin.CharSequence,%20kotlin.Int)/index) or throws an [IndexOutOfBoundsException](../kotlin/-index-out-of-bounds-exception/index#kotlin.IndexOutOfBoundsException) if the [index](element-at#kotlin.text%24elementAt(kotlin.CharSequence,%20kotlin.Int)/index) is out of bounds of this char sequence. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val list = listOf(1, 2, 3) println(list.elementAt(0)) // 1 println(list.elementAt(2)) // 3 // list.elementAt(3) // will fail with IndexOutOfBoundsException val emptyList = emptyList<Int>() // emptyList.elementAt(0) // will fail with IndexOutOfBoundsException //sampleEnd } ``` kotlin isEmpty isEmpty ======= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [isEmpty](is-empty) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.isEmpty(): Boolean ``` Returns `true` if this char sequence is empty (contains no characters). ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart fun markdownLink(title: String, url: String) = if (title.isEmpty()) url else "[$title]($url)" // plain link println(markdownLink(title = "", url = "https://kotlinlang.org")) // https://kotlinlang.org // link with custom title println(markdownLink(title = "Kotlin Language", url = "https://kotlinlang.org")) // [Kotlin Language](https://kotlinlang.org) //sampleEnd } ``` kotlin toUByte toUByte ======= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [toUByte](to-u-byte) **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun String.toUByte(): UByte ``` Parses the string as a signed [UByte](../kotlin/-u-byte/index) number and returns the result. Exceptions ---------- `NumberFormatException` - if the string is not a valid representation of a number. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun String.toUByte(radix: Int): UByte ``` Parses the string as a signed [UByte](../kotlin/-u-byte/index) number and returns the result. Exceptions ---------- `NumberFormatException` - if the string is not a valid representation of a number. `IllegalArgumentException` - when [radix](to-u-byte#kotlin.text%24toUByte(kotlin.String,%20kotlin.Int)/radix) is not a valid radix for string to number conversion. kotlin foldRight foldRight ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [foldRight](fold-right) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <R> CharSequence.foldRight(     initial: R,     operation: (Char, acc: R) -> R ): R ``` Accumulates value starting with [initial](fold-right#kotlin.text%24foldRight(kotlin.CharSequence,%20kotlin.text.foldRight.R,%20kotlin.Function2((kotlin.Char,%20kotlin.text.foldRight.R,%20)))/initial) value and applying [operation](fold-right#kotlin.text%24foldRight(kotlin.CharSequence,%20kotlin.text.foldRight.R,%20kotlin.Function2((kotlin.Char,%20kotlin.text.foldRight.R,%20)))/operation) from right to left to each character and current accumulator value. Returns the specified [initial](fold-right#kotlin.text%24foldRight(kotlin.CharSequence,%20kotlin.text.foldRight.R,%20kotlin.Function2((kotlin.Char,%20kotlin.text.foldRight.R,%20)))/initial) value if the char sequence is empty. Parameters ---------- `operation` - function that takes a character and current accumulator value, and calculates the next accumulator value. kotlin maxOfWith maxOfWith ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [maxOfWith](max-of-with) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` inline fun <R> CharSequence.maxOfWith(     comparator: Comparator<in R>,     selector: (Char) -> R ): R ``` Returns the largest value according to the provided [comparator](max-of-with#kotlin.text%24maxOfWith(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.maxOfWith.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.maxOfWith.R)))/comparator) among all values produced by [selector](max-of-with#kotlin.text%24maxOfWith(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.maxOfWith.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.maxOfWith.R)))/selector) function applied to each character in the char sequence. Exceptions ---------- `NoSuchElementException` - if the char sequence is empty. kotlin isNullOrBlank isNullOrBlank ============= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [isNullOrBlank](is-null-or-blank) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence?.isNullOrBlank(): Boolean ``` Returns `true` if this nullable char sequence is either `null` or empty or consists solely of whitespace characters. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart fun validateName(name: String?): String { if (name.isNullOrBlank()) throw IllegalArgumentException("Name cannot be blank") // name is not nullable here anymore due to a smart cast after calling isNullOrBlank return name } println(validateName("Adam")) // Adam // validateName(null) // will fail // validateName("") // will fail // validateName(" \t\n") // will fail //sampleEnd } ``` kotlin minOfWith minOfWith ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [minOfWith](min-of-with) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` inline fun <R> CharSequence.minOfWith(     comparator: Comparator<in R>,     selector: (Char) -> R ): R ``` Returns the smallest value according to the provided [comparator](min-of-with#kotlin.text%24minOfWith(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.minOfWith.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.minOfWith.R)))/comparator) among all values produced by [selector](min-of-with#kotlin.text%24minOfWith(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.minOfWith.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.minOfWith.R)))/selector) function applied to each character in the char sequence. Exceptions ---------- `NoSuchElementException` - if the char sequence is empty. kotlin splitToSequence splitToSequence =============== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [splitToSequence](split-to-sequence) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.splitToSequence(     vararg delimiters: String,     ignoreCase: Boolean = false,     limit: Int = 0 ): Sequence<String> ``` Splits this char sequence to a sequence of strings around occurrences of the specified [delimiters](split-to-sequence#kotlin.text%24splitToSequence(kotlin.CharSequence,%20kotlin.Array((kotlin.String)),%20kotlin.Boolean,%20kotlin.Int)/delimiters). Parameters ---------- `delimiters` - One or more strings to be used as delimiters. `ignoreCase` - `true` to ignore character case when matching a delimiter. By default `false`. `limit` - The maximum number of substrings to return. Zero by default means no limit is set. To avoid ambiguous results when strings in [delimiters](split-to-sequence#kotlin.text%24splitToSequence(kotlin.CharSequence,%20kotlin.Array((kotlin.String)),%20kotlin.Boolean,%20kotlin.Int)/delimiters) have characters in common, this method proceeds from the beginning to the end of this string, and finds at each position the first element in [delimiters](split-to-sequence#kotlin.text%24splitToSequence(kotlin.CharSequence,%20kotlin.Array((kotlin.String)),%20kotlin.Boolean,%20kotlin.Int)/delimiters) that matches this string at that position. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.splitToSequence(     vararg delimiters: Char,     ignoreCase: Boolean = false,     limit: Int = 0 ): Sequence<String> ``` Splits this char sequence to a sequence of strings around occurrences of the specified [delimiters](split-to-sequence#kotlin.text%24splitToSequence(kotlin.CharSequence,%20kotlin.CharArray,%20kotlin.Boolean,%20kotlin.Int)/delimiters). Parameters ---------- `delimiters` - One or more characters to be used as delimiters. `ignoreCase` - `true` to ignore character case when matching a delimiter. By default `false`. `limit` - The maximum number of substrings to return. **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) ``` fun CharSequence.splitToSequence(     regex: Regex,     limit: Int = 0 ): Sequence<String> ``` Splits this char sequence to a sequence of strings around matches of the given regular expression. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val colors = "green, red , brown&blue, orange, pink&green" val regex = "[,\\s]+".toRegex() val mixedColor = colors.splitToSequence(regex) .onEach { println(it) } .firstOrNull { it.contains('&') } println(mixedColor) // brown&blue //sampleEnd } ``` Parameters ---------- `limit` - Non-negative value specifying the maximum number of substrings to return. Zero by default means no limit is set. kotlin chunked chunked ======= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <chunked> **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) ``` fun CharSequence.chunked(size: Int): List<String> ``` Splits this char sequence into a list of strings each not exceeding the given [size](chunked#kotlin.text%24chunked(kotlin.CharSequence,%20kotlin.Int)/size). The last string in the resulting list may have fewer characters than the given [size](chunked#kotlin.text%24chunked(kotlin.CharSequence,%20kotlin.Int)/size). ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val dnaFragment = "ATTCGCGGCCGCCAA" val codons = dnaFragment.chunked(3) println(codons) // [ATT, CGC, GGC, CGC, CAA] //sampleEnd } ``` Parameters ---------- `size` - the number of elements to take in each string, must be positive and can be greater than the number of elements in this char sequence. **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) ``` fun <R> CharSequence.chunked(     size: Int,     transform: (CharSequence) -> R ): List<R> ``` Splits this char sequence into several char sequences each not exceeding the given [size](chunked#kotlin.text%24chunked(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunked.R)))/size) and applies the given [transform](chunked#kotlin.text%24chunked(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunked.R)))/transform) function to an each. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val codonTable = mapOf("ATT" to "Isoleucine", "CAA" to "Glutamine", "CGC" to "Arginine", "GGC" to "Glycine") val dnaFragment = "ATTCGCGGCCGCCAA" val proteins = dnaFragment.chunked(3) { codon: CharSequence -> codonTable[codon.toString()] ?: error("Unknown codon") } println(proteins) // [Isoleucine, Arginine, Glycine, Arginine, Glutamine] //sampleEnd } ``` Parameters ---------- `size` - the number of elements to take in each char sequence, must be positive and can be greater than the number of elements in this char sequence. **Return** list of results of the [transform](chunked#kotlin.text%24chunked(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunked.R)))/transform) applied to an each char sequence. Note that the char sequence passed to the [transform](chunked#kotlin.text%24chunked(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunked.R)))/transform) function is ephemeral and is valid only inside that function. You should not store it or allow it to escape in some way, unless you made a snapshot of it. The last char sequence may have fewer characters than the given [size](chunked#kotlin.text%24chunked(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunked.R)))/size). kotlin indexOf indexOf ======= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [indexOf](index-of) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.indexOf(     char: Char,     startIndex: Int = 0,     ignoreCase: Boolean = false ): Int ``` Returns the index within this string of the first occurrence of the specified character, starting from the specified [startIndex](index-of#kotlin.text%24indexOf(kotlin.CharSequence,%20kotlin.Char,%20kotlin.Int,%20kotlin.Boolean)/startIndex). Parameters ---------- `ignoreCase` - `true` to ignore character case when matching a character. By default `false`. **Return** An index of the first occurrence of [char](index-of#kotlin.text%24indexOf(kotlin.CharSequence,%20kotlin.Char,%20kotlin.Int,%20kotlin.Boolean)/char) or -1 if none is found. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.indexOf(     string: String,     startIndex: Int = 0,     ignoreCase: Boolean = false ): Int ``` Returns the index within this char sequence of the first occurrence of the specified [string](index-of#kotlin.text%24indexOf(kotlin.CharSequence,%20kotlin.String,%20kotlin.Int,%20kotlin.Boolean)/string), starting from the specified [startIndex](index-of#kotlin.text%24indexOf(kotlin.CharSequence,%20kotlin.String,%20kotlin.Int,%20kotlin.Boolean)/startIndex). ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart fun matchDetails(inputString: String, whatToFind: String, startIndex: Int = 0): String { val matchIndex = inputString.indexOf(whatToFind, startIndex) return "Searching for '$whatToFind' in '$inputString' starting at position $startIndex: " + if (matchIndex >= 0) "Found at $matchIndex" else "Not found" } val inputString = "Never ever give up" val toFind = "ever" println(matchDetails(inputString, toFind)) // Searching for 'ever' in 'Never ever give up' starting at position 0: Found at 1 println(matchDetails(inputString, toFind, 2)) // Searching for 'ever' in 'Never ever give up' starting at position 2: Found at 6 println(matchDetails(inputString, toFind, 10)) // Searching for 'ever' in 'Never ever give up' starting at position 10: Not found //sampleEnd } ``` Parameters ---------- `ignoreCase` - `true` to ignore character case when matching a string. By default `false`. **Return** An index of the first occurrence of [string](index-of#kotlin.text%24indexOf(kotlin.CharSequence,%20kotlin.String,%20kotlin.Int,%20kotlin.Boolean)/string) or `-1` if none is found. kotlin isISOControl isISOControl ============ [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [isISOControl](is-i-s-o-control) **Platform and version requirements:** JVM (1.0), JS (1.5), Native (1.3) ``` fun Char.isISOControl(): Boolean ``` Returns `true` if this character is an ISO control character. A character is considered to be an ISO control character if its category is [CharCategory.CONTROL](-char-category/-c-o-n-t-r-o-l#kotlin.text.CharCategory.CONTROL), meaning the Char is in the range `'\u0000'..'\u001F'` or in the range `'\u007F'..'\u009F'`. ``` import java.util.* import kotlin.test.* fun main(args: Array<String>) { //sampleStart val chars = listOf('\u0000', '\u000E', '\u0009', '1', 'a') val (isoControls, notIsoControls) = chars.partition { it.isISOControl() } // some ISO-control char codes println(isoControls.map(Char::code)) // [0, 14, 9] // non-ISO-control chars println(notIsoControls) // [1, a] //sampleEnd } ``` kotlin removeSurrounding removeSurrounding ================= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [removeSurrounding](remove-surrounding) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.removeSurrounding(     prefix: CharSequence,     suffix: CharSequence ): CharSequence ``` When this char sequence starts with the given [prefix](remove-surrounding#kotlin.text%24removeSurrounding(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence)/prefix) and ends with the given [suffix](remove-surrounding#kotlin.text%24removeSurrounding(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence)/suffix), returns a new char sequence having both the given [prefix](remove-surrounding#kotlin.text%24removeSurrounding(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence)/prefix) and [suffix](remove-surrounding#kotlin.text%24removeSurrounding(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence)/suffix) removed. Otherwise returns a new char sequence with the same characters. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.removeSurrounding(     prefix: CharSequence,     suffix: CharSequence ): String ``` Removes from a string both the given [prefix](remove-surrounding#kotlin.text%24removeSurrounding(kotlin.String,%20kotlin.CharSequence,%20kotlin.CharSequence)/prefix) and [suffix](remove-surrounding#kotlin.text%24removeSurrounding(kotlin.String,%20kotlin.CharSequence,%20kotlin.CharSequence)/suffix) if and only if it starts with the [prefix](remove-surrounding#kotlin.text%24removeSurrounding(kotlin.String,%20kotlin.CharSequence,%20kotlin.CharSequence)/prefix) and ends with the [suffix](remove-surrounding#kotlin.text%24removeSurrounding(kotlin.String,%20kotlin.CharSequence,%20kotlin.CharSequence)/suffix). Otherwise returns this string unchanged. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.removeSurrounding(     delimiter: CharSequence ): CharSequence ``` When this char sequence starts with and ends with the given [delimiter](remove-surrounding#kotlin.text%24removeSurrounding(kotlin.CharSequence,%20kotlin.CharSequence)/delimiter), returns a new char sequence having this [delimiter](remove-surrounding#kotlin.text%24removeSurrounding(kotlin.CharSequence,%20kotlin.CharSequence)/delimiter) removed both from the start and end. Otherwise returns a new char sequence with the same characters. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.removeSurrounding(delimiter: CharSequence): String ``` Removes the given [delimiter](remove-surrounding#kotlin.text%24removeSurrounding(kotlin.String,%20kotlin.CharSequence)/delimiter) string from both the start and the end of this string if and only if it starts with and ends with the [delimiter](remove-surrounding#kotlin.text%24removeSurrounding(kotlin.String,%20kotlin.CharSequence)/delimiter). Otherwise returns this string unchanged.
programming_docs
kotlin toLongOrNull toLongOrNull ============ [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [toLongOrNull](to-long-or-null) **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) ``` fun String.toLongOrNull(): Long? ``` Parses the string as a [Long](../kotlin/-long/index#kotlin.Long) number and returns the result or `null` if the string is not a valid representation of a number. **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) ``` fun String.toLongOrNull(radix: Int): Long? ``` Parses the string as a [Long](../kotlin/-long/index#kotlin.Long) number and returns the result or `null` if the string is not a valid representation of a number. Exceptions ---------- `IllegalArgumentException` - when [radix](to-long-or-null#kotlin.text%24toLongOrNull(kotlin.String,%20kotlin.Int)/radix) is not a valid radix for string to number conversion. kotlin lastIndexOfAny lastIndexOfAny ============== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [lastIndexOfAny](last-index-of-any) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.lastIndexOfAny(     chars: CharArray,     startIndex: Int = lastIndex,     ignoreCase: Boolean = false ): Int ``` Finds the index of the last occurrence of any of the specified [chars](last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Boolean)/chars) in this char sequence, starting from the specified [startIndex](last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Boolean)/startIndex) and optionally ignoring the case. Parameters ---------- `startIndex` - The index of character to start searching at. The search proceeds backward toward the beginning of the string. `ignoreCase` - `true` to ignore character case when matching a character. By default `false`. **Return** An index of the last occurrence of matched character from [chars](last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Boolean)/chars) or -1 if none of [chars](last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Boolean)/chars) are found. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.lastIndexOfAny(     strings: Collection<String>,     startIndex: Int = lastIndex,     ignoreCase: Boolean = false ): Int ``` Finds the index of the last occurrence of any of the specified [strings](last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) in this char sequence, starting from the specified [startIndex](last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/startIndex) and optionally ignoring the case. Parameters ---------- `startIndex` - The index of character to start searching at. The search proceeds backward toward the beginning of the string. `ignoreCase` - `true` to ignore character case when matching a string. By default `false`. **Return** An index of the last occurrence of matched string from [strings](last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) or -1 if none of [strings](last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) are found. To avoid ambiguous results when strings in [strings](last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) have characters in common, this method proceeds from the end toward the beginning of this string, and finds at each position the first element in [strings](last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) that matches this string at that position. kotlin associate associate ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <associate> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <K, V> CharSequence.associate(     transform: (Char) -> Pair<K, V> ): Map<K, V> ``` Returns a [Map](../kotlin.collections/-map/index#kotlin.collections.Map) containing key-value pairs provided by [transform](associate#kotlin.text%24associate(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Pair((kotlin.text.associate.K,%20kotlin.text.associate.V)))))/transform) function applied to characters of the given char sequence. If any of two pairs would have the same key the last one gets added to the map. The returned map preserves the entry iteration order of the original char sequence. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val string = "bonne journée" // associate each character with its code val result = string.associate { char -> char to char.code } // notice each letter occurs only once println(result) // {b=98, o=111, n=110, e=101, =32, j=106, u=117, r=114, é=233} //sampleEnd } ``` kotlin hasSurrogatePairAt hasSurrogatePairAt ================== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [hasSurrogatePairAt](has-surrogate-pair-at) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.hasSurrogatePairAt(index: Int): Boolean ``` Returns `true` if this CharSequence has Unicode surrogate pair at the specified [index](has-surrogate-pair-at#kotlin.text%24hasSurrogatePairAt(kotlin.CharSequence,%20kotlin.Int)/index). kotlin toCharArray toCharArray =========== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [toCharArray](to-char-array) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.toCharArray(): CharArray ``` Returns a [CharArray](../kotlin/-char-array/index#kotlin.CharArray) containing characters of this string. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` fun String.toCharArray(     startIndex: Int = 0,     endIndex: Int = this.length ): CharArray ``` Returns a [CharArray](../kotlin/-char-array/index#kotlin.CharArray) containing characters of this string or its substring. Parameters ---------- `startIndex` - the beginning (inclusive) of the substring, 0 by default. `endIndex` - the end (exclusive) of the substring, length of this string by default. Exceptions ---------- `IndexOutOfBoundsException` - if [startIndex](to-char-array#kotlin.text%24toCharArray(kotlin.String,%20kotlin.Int,%20kotlin.Int)/startIndex) is less than zero or [endIndex](to-char-array#kotlin.text%24toCharArray(kotlin.String,%20kotlin.Int,%20kotlin.Int)/endIndex) is greater than the length of this string. `IllegalArgumentException` - if [startIndex](to-char-array#kotlin.text%24toCharArray(kotlin.String,%20kotlin.Int,%20kotlin.Int)/startIndex) is greater than [endIndex](to-char-array#kotlin.text%24toCharArray(kotlin.String,%20kotlin.Int,%20kotlin.Int)/endIndex). **Platform and version requirements:** JS (1.4) ``` fun StringBuilder.toCharArray(     destination: CharArray,     destinationOffset: Int = 0,     startIndex: Int = 0,     endIndex: Int = this.length) ``` Copies characters from this string builder into the [destination](to-char-array#kotlin.text%24toCharArray(kotlin.text.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destination) character array. Parameters ---------- `destination` - the array to copy to. `destinationOffset` - the position in the array to copy to, 0 by default. `startIndex` - the beginning (inclusive) of the range to copy, 0 by default. `endIndex` - the end (exclusive) of the range to copy, length of this string builder by default. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](to-char-array#kotlin.text%24toCharArray(kotlin.text.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](to-char-array#kotlin.text%24toCharArray(kotlin.text.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/endIndex) is out of range of this string builder indices or when `startIndex > endIndex`. `IndexOutOfBoundsException` - when the subrange doesn't fit into the [destination](to-char-array#kotlin.text%24toCharArray(kotlin.text.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destination) array starting at the specified [destinationOffset](to-char-array#kotlin.text%24toCharArray(kotlin.text.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destinationOffset), or when that index is out of the [destination](to-char-array#kotlin.text%24toCharArray(kotlin.text.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destination) array indices range. **Platform and version requirements:** JVM (1.0) ``` fun String.toCharArray(     destination: CharArray,     destinationOffset: Int = 0,     startIndex: Int = 0,     endIndex: Int = length ): CharArray ``` Copies characters from this string into the [destination](to-char-array#kotlin.text%24toCharArray(kotlin.String,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destination) character array and returns that array. Parameters ---------- `destination` - the array to copy to. `destinationOffset` - the position in the array to copy to. `startIndex` - the start offset (inclusive) of the substring to copy. `endIndex` - the end offset (exclusive) of the substring to copy. kotlin concat concat ====== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <concat> **Platform and version requirements:** JS (1.1) ``` @DeprecatedSinceKotlin("1.6") fun String.concat(     str: String ): String ``` **Deprecated:** Use String.plus() instead kotlin withIndex withIndex ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [withIndex](with-index) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.withIndex(): Iterable<IndexedValue<Char>> ``` Returns a lazy [Iterable](../kotlin.collections/-iterable/index#kotlin.collections.Iterable) that wraps each character of the original char sequence into an [IndexedValue](../kotlin.collections/-indexed-value/index) containing the index of that character and the character itself. kotlin trimIndent trimIndent ========== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [trimIndent](trim-indent) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.trimIndent(): String ``` Detects a common minimal indent of all the input lines, removes it from every line and also removes the first and the last lines if they are blank (notice difference blank vs empty). Note that blank lines do not affect the detected indent level. In case if there are non-blank lines with no leading whitespace characters (no indent at all) then the common indent is 0, and therefore this function doesn't change the indentation. Doesn't preserve the original line endings. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val withoutIndent = """ ABC 123 456 """.trimIndent() println(withoutIndent) // ABC\n123\n456 //sampleEnd } ``` **See Also** [trimMargin](trim-margin) [kotlin.text.isBlank](is-blank#kotlin.text%24isBlank(kotlin.CharSequence)) kotlin set set === [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <set> **Platform and version requirements:** JS (1.4) ``` operator fun StringBuilder.set(index: Int, value: Char) ``` Sets the character at the specified [index](set#kotlin.text%24set(kotlin.text.StringBuilder,%20kotlin.Int,%20kotlin.Char)/index) to the specified [value](set#kotlin.text%24set(kotlin.text.StringBuilder,%20kotlin.Int,%20kotlin.Char)/value). Exceptions ---------- `IndexOutOfBoundsException` - if [index](set#kotlin.text%24set(kotlin.text.StringBuilder,%20kotlin.Int,%20kotlin.Char)/index) is out of bounds of this string builder. kotlin groupByTo groupByTo ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [groupByTo](group-by-to) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <K, M : MutableMap<in K, MutableList<Char>>> CharSequence.groupByTo(     destination: M,     keySelector: (Char) -> K ): M ``` Groups characters of the original char sequence by the key returned by the given [keySelector](group-by-to#kotlin.text%24groupByTo(kotlin.CharSequence,%20kotlin.text.groupByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.K)))/keySelector) function applied to each character and puts to the [destination](group-by-to#kotlin.text%24groupByTo(kotlin.CharSequence,%20kotlin.text.groupByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.K)))/destination) map each group key associated with a list of corresponding characters. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val words = listOf("a", "abc", "ab", "def", "abcd") val byLength = words.groupBy { it.length } println(byLength.keys) // [1, 3, 2, 4] println(byLength.values) // [[a], [abc, def], [ab], [abcd]] val mutableByLength: MutableMap<Int, MutableList<String>> = words.groupByTo(mutableMapOf()) { it.length } // same content as in byLength map, but the map is mutable println("mutableByLength == byLength is ${mutableByLength == byLength}") // true //sampleEnd } ``` **Return** The [destination](group-by-to#kotlin.text%24groupByTo(kotlin.CharSequence,%20kotlin.text.groupByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.K)))/destination) map. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <K, V, M : MutableMap<in K, MutableList<V>>> CharSequence.groupByTo(     destination: M,     keySelector: (Char) -> K,     valueTransform: (Char) -> V ): M ``` Groups values returned by the [valueTransform](group-by-to#kotlin.text%24groupByTo(kotlin.CharSequence,%20kotlin.text.groupByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.V)))/valueTransform) function applied to each character of the original char sequence by the key returned by the given [keySelector](group-by-to#kotlin.text%24groupByTo(kotlin.CharSequence,%20kotlin.text.groupByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.V)))/keySelector) function applied to the character and puts to the [destination](group-by-to#kotlin.text%24groupByTo(kotlin.CharSequence,%20kotlin.text.groupByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.V)))/destination) map each group key associated with a list of corresponding values. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val nameToTeam = listOf("Alice" to "Marketing", "Bob" to "Sales", "Carol" to "Marketing") val namesByTeam = nameToTeam.groupBy({ it.second }, { it.first }) println(namesByTeam) // {Marketing=[Alice, Carol], Sales=[Bob]} val mutableNamesByTeam = nameToTeam.groupByTo(HashMap(), { it.second }, { it.first }) // same content as in namesByTeam map, but the map is mutable println("mutableNamesByTeam == namesByTeam is ${mutableNamesByTeam == namesByTeam}") // true //sampleEnd } ``` **Return** The [destination](group-by-to#kotlin.text%24groupByTo(kotlin.CharSequence,%20kotlin.text.groupByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.V)))/destination) map. kotlin toShort toShort ======= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [toShort](to-short) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.toShort(): Short ``` Parses the string as a [Short](../kotlin/-short/index#kotlin.Short) number and returns the result. Exceptions ---------- `NumberFormatException` - if the string is not a valid representation of a number. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.toShort(radix: Int): Short ``` Parses the string as a [Short](../kotlin/-short/index#kotlin.Short) number and returns the result. Exceptions ---------- `NumberFormatException` - if the string is not a valid representation of a number. `IllegalArgumentException` - when [radix](to-short#kotlin.text%24toShort(kotlin.String,%20kotlin.Int)/radix) is not a valid radix for string to number conversion. kotlin toULong toULong ======= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [toULong](to-u-long) **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun String.toULong(): ULong ``` Parses the string as a [ULong](../kotlin/-u-long/index) number and returns the result. Exceptions ---------- `NumberFormatException` - if the string is not a valid representation of a number. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun String.toULong(radix: Int): ULong ``` Parses the string as a [ULong](../kotlin/-u-long/index) number and returns the result. Exceptions ---------- `NumberFormatException` - if the string is not a valid representation of a number. `IllegalArgumentException` - when [radix](to-u-long#kotlin.text%24toULong(kotlin.String,%20kotlin.Int)/radix) is not a valid radix for string to number conversion. kotlin getOrNull getOrNull ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [getOrNull](get-or-null) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.getOrNull(index: Int): Char? ``` Returns a character at the given [index](get-or-null#kotlin.text%24getOrNull(kotlin.CharSequence,%20kotlin.Int)/index) or `null` if the [index](get-or-null#kotlin.text%24getOrNull(kotlin.CharSequence,%20kotlin.Int)/index) is out of bounds of this char sequence. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val list = listOf(1, 2, 3) println(list.getOrNull(0)) // 1 println(list.getOrNull(2)) // 3 println(list.getOrNull(3)) // null val emptyList = emptyList<Int>() println(emptyList.getOrNull(0)) // null //sampleEnd } ``` kotlin plus plus ==== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <plus> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun Char.plus(other: String): String ``` Concatenates this Char and a String. ``` import java.util.* import kotlin.test.* fun main(args: Array<String>) { //sampleStart val value = 'a' + "bcd" println(value) // abcd //sampleEnd } ``` kotlin mapNotNullTo mapNotNullTo ============ [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [mapNotNullTo](map-not-null-to) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <R : Any, C : MutableCollection<in R>> CharSequence.mapNotNullTo(     destination: C,     transform: (Char) -> R? ): C ``` Applies the given [transform](map-not-null-to#kotlin.text%24mapNotNullTo(kotlin.CharSequence,%20kotlin.text.mapNotNullTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.text.mapNotNullTo.R?)))/transform) function to each character in the original char sequence and appends only the non-null results to the given [destination](map-not-null-to#kotlin.text%24mapNotNullTo(kotlin.CharSequence,%20kotlin.text.mapNotNullTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.text.mapNotNullTo.R?)))/destination).
programming_docs
kotlin reduceRightIndexed reduceRightIndexed ================== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [reduceRightIndexed](reduce-right-indexed) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun CharSequence.reduceRightIndexed(     operation: (index: Int, Char, acc: Char) -> Char ): Char ``` Accumulates value starting with the last character and applying [operation](reduce-right-indexed#kotlin.text%24reduceRightIndexed(kotlin.CharSequence,%20kotlin.Function3((kotlin.Int,%20kotlin.Char,%20,%20)))/operation) from right to left to each character with its index in the original char sequence and current accumulator value. Throws an exception if this char sequence is empty. If the char sequence can be empty in an expected way, please use [reduceRightIndexedOrNull](reduce-right-indexed-or-null) instead. It returns `null` when its receiver is empty. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val strings = listOf("a", "b", "c", "d") println(strings.reduceRight { string, acc -> acc + string }) // dcba println(strings.reduceRightIndexed { index, string, acc -> acc + string + index }) // dc2b1a0 // emptyList<Int>().reduceRight { _, _ -> 0 } // will fail //sampleEnd } ``` Parameters ---------- `operation` - function that takes the index of a character, the character itself and current accumulator value, and calculates the next accumulator value. kotlin dropLastWhile dropLastWhile ============= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [dropLastWhile](drop-last-while) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun CharSequence.dropLastWhile(     predicate: (Char) -> Boolean ): CharSequence ``` Returns a subsequence of this char sequence containing all characters except last characters that satisfy the given [predicate](drop-last-while#kotlin.text%24dropLastWhile(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val string = "<<<First Grade>>>" println(string.drop(6)) // st Grade>>> println(string.dropLast(6)) // <<<First Gr println(string.dropWhile { !it.isLetter() }) // First Grade>>> println(string.dropLastWhile { !it.isLetter() }) // <<<First Grade //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun String.dropLastWhile(     predicate: (Char) -> Boolean ): String ``` Returns a string containing all characters except last characters that satisfy the given [predicate](drop-last-while#kotlin.text%24dropLastWhile(kotlin.String,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val string = "<<<First Grade>>>" println(string.drop(6)) // st Grade>>> println(string.dropLast(6)) // <<<First Gr println(string.dropWhile { !it.isLetter() }) // First Grade>>> println(string.dropLastWhile { !it.isLetter() }) // <<<First Grade //sampleEnd } ``` kotlin filterNot filterNot ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [filterNot](filter-not) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun CharSequence.filterNot(     predicate: (Char) -> Boolean ): CharSequence ``` Returns a char sequence containing only those characters from the original char sequence that do not match the given [predicate](filter-not#kotlin.text%24filterNot(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val text = "a1b2c3d4e5" val textWithoutDigits = text.filterNot { it.isDigit() } println(textWithoutDigits) // abcde //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun String.filterNot(     predicate: (Char) -> Boolean ): String ``` Returns a string containing only those characters from the original string that do not match the given [predicate](filter-not#kotlin.text%24filterNot(kotlin.String,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val text = "a1b2c3d4e5" val textWithoutDigits = text.filterNot { it.isDigit() } println(textWithoutDigits) // abcde //sampleEnd } ``` kotlin toBigDecimal toBigDecimal ============ [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [toBigDecimal](to-big-decimal) **Platform and version requirements:** JVM (1.2) ``` fun String.toBigDecimal(): BigDecimal ``` Parses the string as a [java.math.BigDecimal](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html) number and returns the result. Exceptions ---------- `NumberFormatException` - if the string is not a valid representation of a number. **Platform and version requirements:** JVM (1.2) ``` fun String.toBigDecimal(mathContext: MathContext): BigDecimal ``` Parses the string as a [java.math.BigDecimal](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html) number and returns the result. Exceptions ---------- `NumberFormatException` - if the string is not a valid representation of a number. `ArithmeticException` - if the rounding is needed, but the rounding mode is [java.math.RoundingMode.UNNECESSARY](https://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html#UNNECESSARY). Parameters ---------- `mathContext` - specifies the precision and the rounding mode. kotlin elementAtOrElse elementAtOrElse =============== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [elementAtOrElse](element-at-or-else) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun CharSequence.elementAtOrElse(     index: Int,     defaultValue: (Int) -> Char ): Char ``` Returns a character at the given [index](element-at-or-else#kotlin.text%24elementAtOrElse(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.Char)))/index) or the result of calling the [defaultValue](element-at-or-else#kotlin.text%24elementAtOrElse(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.Char)))/defaultValue) function if the [index](element-at-or-else#kotlin.text%24elementAtOrElse(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.Char)))/index) is out of bounds of this char sequence. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val list = listOf(1, 2, 3) println(list.elementAtOrElse(0) { 42 }) // 1 println(list.elementAtOrElse(2) { 42 }) // 3 println(list.elementAtOrElse(3) { 42 }) // 42 val emptyList = emptyList<Int>() println(emptyList.elementAtOrElse(0) { "no int" }) // no int //sampleEnd } ``` kotlin get get === [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <get> **Platform and version requirements:** JVM (1.2), JRE8 (1.2), JS (1.7) ``` operator fun MatchGroupCollection.get(     name: String ): MatchGroup? ``` Returns a named group with the specified [name](get#kotlin.text%24get(kotlin.text.MatchGroupCollection,%20kotlin.String)/name). Exceptions ---------- `IllegalArgumentException` - if there is no group with the specified [name](get#kotlin.text%24get(kotlin.text.MatchGroupCollection,%20kotlin.String)/name) defined in the regex pattern. `UnsupportedOperationException` - if this match group collection doesn't support getting match groups by name, for example, when it's not supported by the current platform. **Return** An instance of MatchGroup if the group with the specified [name](get#kotlin.text%24get(kotlin.text.MatchGroupCollection,%20kotlin.String)/name) was matched or `null` otherwise. kotlin runningReduceIndexed runningReduceIndexed ==================== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [runningReduceIndexed](running-reduce-indexed) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` inline fun CharSequence.runningReduceIndexed(     operation: (index: Int, acc: Char, Char) -> Char ): List<Char> ``` Returns a list containing successive accumulation values generated by applying [operation](running-reduce-indexed#kotlin.text%24runningReduceIndexed(kotlin.CharSequence,%20kotlin.Function3((kotlin.Int,%20kotlin.Char,%20,%20)))/operation) from left to right to each character, its index in the original char sequence and current accumulator value that starts with the first character of this char sequence. Note that `acc` value passed to [operation](running-reduce-indexed#kotlin.text%24runningReduceIndexed(kotlin.CharSequence,%20kotlin.Function3((kotlin.Int,%20kotlin.Char,%20,%20)))/operation) function should not be mutated; otherwise it would affect the previous value in resulting list. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val strings = listOf("a", "b", "c", "d") println(strings.runningReduce { acc, string -> acc + string }) // [a, ab, abc, abcd] println(strings.runningReduceIndexed { index, acc, string -> acc + string + index }) // [a, ab1, ab1c2, ab1c2d3] println(emptyList<String>().runningReduce { _, _ -> "X" }) // [] //sampleEnd } ``` Parameters ---------- `operation` - function that takes the index of a character, current accumulator value and the character itself, and calculates the next accumulator value. kotlin prependIndent prependIndent ============= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [prependIndent](prepend-indent) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.prependIndent(indent: String = " "): String ``` Prepends [indent](prepend-indent#kotlin.text%24prependIndent(kotlin.String,%20kotlin.String)/indent) to every line of the original string. Doesn't preserve the original line endings. kotlin toUShortOrNull toUShortOrNull ============== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [toUShortOrNull](to-u-short-or-null) **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun String.toUShortOrNull(): UShort? ``` Parses the string as an [UShort](../kotlin/-u-short/index) number and returns the result or `null` if the string is not a valid representation of a number. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun String.toUShortOrNull(radix: Int): UShort? ``` Parses the string as an [UShort](../kotlin/-u-short/index) number and returns the result or `null` if the string is not a valid representation of a number. Exceptions ---------- `IllegalArgumentException` - when [radix](to-u-short-or-null#kotlin.text%24toUShortOrNull(kotlin.String,%20kotlin.Int)/radix) is not a valid radix for string to number conversion. kotlin toPattern toPattern ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [toPattern](to-pattern) **Platform and version requirements:** JVM (1.0) ``` fun String.toPattern(flags: Int = 0): Pattern ``` Converts the string into a regular expression [Pattern](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) optionally with the specified [flags](to-pattern#kotlin.text%24toPattern(kotlin.String,%20kotlin.Int)/flags) from [Pattern](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) or'd together so that strings can be split or matched on. kotlin substring substring ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <substring> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.substring(startIndex: Int): String ``` Returns a substring of this string that starts at the specified [startIndex](substring#kotlin.text%24substring(kotlin.String,%20kotlin.Int)/startIndex) and continues to the end of the string. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.substring(startIndex: Int, endIndex: Int): String ``` Returns the substring of this string starting at the [startIndex](substring#kotlin.text%24substring(kotlin.String,%20kotlin.Int,%20kotlin.Int)/startIndex) and ending right before the [endIndex](substring#kotlin.text%24substring(kotlin.String,%20kotlin.Int,%20kotlin.Int)/endIndex). Parameters ---------- `startIndex` - the start index (inclusive). `endIndex` - the end index (exclusive). **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun String.substring(range: IntRange): String ``` Returns a substring specified by the given [range](substring#kotlin.text%24substring(kotlin.String,%20kotlin.ranges.IntRange)/range) of indices. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.substring(     startIndex: Int,     endIndex: Int = length ): String ``` Returns a substring of chars from a range of this char sequence starting at the [startIndex](substring#kotlin.text%24substring(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/startIndex) and ending right before the [endIndex](substring#kotlin.text%24substring(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/endIndex). Parameters ---------- `startIndex` - the start index (inclusive). `endIndex` - the end index (exclusive). If not specified, the length of the char sequence is used. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.substring(range: IntRange): String ``` Returns a substring of chars at indices from the specified [range](substring#kotlin.text%24substring(kotlin.CharSequence,%20kotlin.ranges.IntRange)/range) of this char sequence. kotlin minOfOrNull minOfOrNull =========== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [minOfOrNull](min-of-or-null) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` inline fun CharSequence.minOfOrNull(     selector: (Char) -> Double ): Double? ``` ``` inline fun CharSequence.minOfOrNull(     selector: (Char) -> Float ): Float? ``` Returns the smallest value among all values produced by [selector](min-of-or-null#kotlin.text%24minOfOrNull(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Double)))/selector) function applied to each character in the char sequence or `null` if there are no characters. If any of values produced by [selector](min-of-or-null#kotlin.text%24minOfOrNull(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Double)))/selector) function is `NaN`, the returned result is `NaN`. **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` inline fun <R : Comparable<R>> CharSequence.minOfOrNull(     selector: (Char) -> R ): R? ``` Returns the smallest value among all values produced by [selector](min-of-or-null#kotlin.text%24minOfOrNull(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.minOfOrNull.R)))/selector) function applied to each character in the char sequence or `null` if there are no characters. kotlin lowercase lowercase ========= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <lowercase> **Platform and version requirements:** JVM (1.5), JS (1.5) ``` fun Char.lowercase(): String ``` Converts this character to lower case using Unicode mapping rules of the invariant locale. This function supports one-to-many character mapping, thus the length of the returned string can be greater than one. For example, `'\u0130'.lowercase()` returns `"\u0069\u0307"`, where `'\u0130'` is the LATIN CAPITAL LETTER I WITH DOT ABOVE character (`İ`). If this character has no lower case mapping, the result of `toString()` of this char is returned. ``` import java.util.* import kotlin.test.* fun main(args: Array<String>) { //sampleStart val chars = listOf('A', 'Ω', '1', 'a', '+', 'İ') val lowercaseChar = chars.map { it.lowercaseChar() } val lowercase = chars.map { it.lowercase() } println(lowercaseChar) // [a, ω, 1, a, +, i] println(lowercase) // [a, ω, 1, a, +, \u0069\u0307] //sampleEnd } ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun String.lowercase(): String ``` Returns a copy of this string converted to lower case using Unicode mapping rules of the invariant locale. This function supports one-to-many and many-to-one character mapping, thus the length of the returned string can be different from the length of the original string. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart println("Iced frappé!".lowercase()) // iced frappé! //sampleEnd } ``` **Platform and version requirements:** JVM (1.5) ``` fun Char.lowercase(locale: Locale): String ``` Converts this character to lower case using Unicode mapping rules of the specified [locale](lowercase#kotlin.text%24lowercase(kotlin.Char,%20java.util.Locale)/locale). This function supports one-to-many character mapping, thus the length of the returned string can be greater than one. For example, `'\u0130'.lowercase(Locale.US)` returns `"\u0069\u0307"`, where `'\u0130'` is the LATIN CAPITAL LETTER I WITH DOT ABOVE character (`İ`). If this character has no lower case mapping, the result of `toString()` of this char is returned. ``` import java.util.* import kotlin.test.* fun main(args: Array<String>) { //sampleStart val chars = listOf('A', 'Ω', '1', 'a', '+', 'İ') val lowercase = chars.map { it.lowercase() } val turkishLocale = Locale.forLanguageTag("tr") val lowercaseTurkish = chars.map { it.lowercase(turkishLocale) } println(lowercase) // [a, ω, 1, a, +, \u0069\u0307] println(lowercaseTurkish) // [a, ω, 1, a, +, i] //sampleEnd } ``` **Platform and version requirements:** JVM (1.5) ``` fun String.lowercase(locale: Locale): String ``` Returns a copy of this string converted to lower case using the rules of the specified [locale](lowercase#kotlin.text%24lowercase(kotlin.String,%20java.util.Locale)/locale). This function supports one-to-many and many-to-one character mapping, thus the length of the returned string can be different from the length of the original string. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart println("KOTLIN".lowercase()) // kotlin val turkishLocale = Locale.forLanguageTag("tr") println("KOTLIN".lowercase(turkishLocale)) // kotlın //sampleEnd } ``` kotlin filter filter ====== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <filter> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun CharSequence.filter(     predicate: (Char) -> Boolean ): CharSequence ``` Returns a char sequence containing only those characters from the original char sequence that match the given [predicate](filter#kotlin.text%24filter(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val text = "a1b2c3d4e5" val textWithOnlyDigits = text.filter { it.isDigit() } println(textWithOnlyDigits) // 12345 //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun String.filter(     predicate: (Char) -> Boolean ): String ``` Returns a string containing only those characters from the original string that match the given [predicate](filter#kotlin.text%24filter(kotlin.String,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val text = "a1b2c3d4e5" val textWithOnlyDigits = text.filter { it.isDigit() } println(textWithOnlyDigits) // 12345 //sampleEnd } ```
programming_docs
kotlin associateWithTo associateWithTo =============== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [associateWithTo](associate-with-to) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` inline fun <V, M : MutableMap<in Char, in V>> CharSequence.associateWithTo(     destination: M,     valueSelector: (Char) -> V ): M ``` Populates and returns the [destination](associate-with-to#kotlin.text%24associateWithTo(kotlin.CharSequence,%20kotlin.text.associateWithTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateWithTo.V)))/destination) mutable map with key-value pairs for each character of the given char sequence, where key is the character itself and value is provided by the [valueSelector](associate-with-to#kotlin.text%24associateWithTo(kotlin.CharSequence,%20kotlin.text.associateWithTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateWithTo.V)))/valueSelector) function applied to that key. If any two characters are equal, the last one overwrites the former value in the map. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val string = "bonne journée" // associate each character with its code val result = mutableMapOf<Char, Int>() string.associateWithTo(result) { char -> char.code } // notice each letter occurs only once println(result) // {b=98, o=111, n=110, e=101, =32, j=106, u=117, r=114, é=233} //sampleEnd } ``` kotlin reduceRightOrNull reduceRightOrNull ================= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [reduceRightOrNull](reduce-right-or-null) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` inline fun CharSequence.reduceRightOrNull(     operation: (Char, acc: Char) -> Char ): Char? ``` Accumulates value starting with the last character and applying [operation](reduce-right-or-null#kotlin.text%24reduceRightOrNull(kotlin.CharSequence,%20kotlin.Function2((kotlin.Char,%20,%20)))/operation) from right to left to each character and current accumulator value. Returns `null` if the char sequence is empty. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val strings = listOf("a", "b", "c", "d") println(strings.reduceRightOrNull { string, acc -> acc + string }) // dcba println(strings.reduceRightIndexedOrNull { index, string, acc -> acc + string + index }) // dc2b1a0 println(emptyList<String>().reduceRightOrNull { _, _ -> "" }) // null //sampleEnd } ``` Parameters ---------- `operation` - function that takes a character and current accumulator value, and calculates the next accumulator value. kotlin firstNotNullOf firstNotNullOf ============== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [firstNotNullOf](first-not-null-of) **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` inline fun <R : Any> CharSequence.firstNotNullOf(     transform: (Char) -> R? ): R ``` Returns the first non-null value produced by [transform](first-not-null-of#kotlin.text%24firstNotNullOf(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.firstNotNullOf.R?)))/transform) function being applied to characters of this char sequence in iteration order, or throws [NoSuchElementException](../kotlin/-no-such-element-exception/index#kotlin.NoSuchElementException) if no non-null value was produced. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart data class Rectangle(val height: Int, val width: Int) { val area: Int get() = height * width } val rectangles = listOf( Rectangle(3, 4), Rectangle(1, 8), Rectangle(6, 3), Rectangle(4, 3), Rectangle(5, 7) ) val largeArea = rectangles.firstNotNullOf { it.area.takeIf { area -> area >= 15 } } val largeAreaOrNull = rectangles.firstNotNullOfOrNull { it.area.takeIf { area -> area >= 15 } } println(largeArea) // 18 println(largeAreaOrNull) // 18 // val evenLargerArea = rectangles.firstNotNullOf { it.area.takeIf { area -> area >= 50 } } // will fail with NoSuchElementException val evenLargerAreaOrNull = rectangles.firstNotNullOfOrNull { it.area.takeIf { area -> area >= 50 } } println(evenLargerAreaOrNull) // null //sampleEnd } ``` kotlin first first ===== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / <first> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun CharSequence.first(): Char ``` Returns the first character. Exceptions ---------- `NoSuchElementException` - if the char sequence is empty. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun CharSequence.first(     predicate: (Char) -> Boolean ): Char ``` Returns the first character matching the given [predicate](first#kotlin.text%24first(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). Exceptions ---------- `NoSuchElementException` - if no such character is found. kotlin mapTo mapTo ===== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [mapTo](map-to) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <R, C : MutableCollection<in R>> CharSequence.mapTo(     destination: C,     transform: (Char) -> R ): C ``` Applies the given [transform](map-to#kotlin.text%24mapTo(kotlin.CharSequence,%20kotlin.text.mapTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.text.mapTo.R)))/transform) function to each character of the original char sequence and appends the results to the given [destination](map-to#kotlin.text%24mapTo(kotlin.CharSequence,%20kotlin.text.mapTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.text.mapTo.R)))/destination). kotlin isUpperCase isUpperCase =========== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [isUpperCase](is-upper-case) **Platform and version requirements:** JVM (1.0), JS (1.5) ``` fun Char.isUpperCase(): Boolean ``` Returns `true` if this character is upper case. A character is considered to be an upper case character if its category is [CharCategory.UPPERCASE\_LETTER](-char-category/-u-p-p-e-r-c-a-s-e_-l-e-t-t-e-r#kotlin.text.CharCategory.UPPERCASE_LETTER), or it has contributory property `Other_Uppercase` as defined by the Unicode Standard. ``` import java.util.* import kotlin.test.* fun main(args: Array<String>) { //sampleStart val chars = listOf('A', 'Ψ', 'a', '1', '+') val (upperCases, notUpperCases) = chars.partition { it.isUpperCase() } println(upperCases) // [A, Ψ] println(notUpperCases) // [a, 1, +] //sampleEnd } ``` kotlin zipWithNext zipWithNext =========== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [zipWithNext](zip-with-next) **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) ``` fun CharSequence.zipWithNext(): List<Pair<Char, Char>> ``` Returns a list of pairs of each two adjacent characters in this char sequence. The returned list is empty if this char sequence contains less than two characters. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val letters = ('a'..'f').toList() val pairs = letters.zipWithNext() println(letters) // [a, b, c, d, e, f] println(pairs) // [(a, b), (b, c), (c, d), (d, e), (e, f)] //sampleEnd } ``` **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) ``` inline fun <R> CharSequence.zipWithNext(     transform: (a: Char, b: Char) -> R ): List<R> ``` Returns a list containing the results of applying the given [transform](zip-with-next#kotlin.text%24zipWithNext(kotlin.CharSequence,%20kotlin.Function2((kotlin.Char,%20,%20kotlin.text.zipWithNext.R)))/transform) function to an each pair of two adjacent characters in this char sequence. The returned list is empty if this char sequence contains less than two characters. ``` import kotlin.test.* fun main(args: Array<String>) { //sampleStart val values = listOf(1, 4, 9, 16, 25, 36) val deltas = values.zipWithNext { a, b -> b - a } println(deltas) // [3, 5, 7, 9, 11] //sampleEnd } ``` kotlin associateTo associateTo =========== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [associateTo](associate-to) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <K, V, M : MutableMap<in K, in V>> CharSequence.associateTo(     destination: M,     transform: (Char) -> Pair<K, V> ): M ``` Populates and returns the [destination](associate-to#kotlin.text%24associateTo(kotlin.CharSequence,%20kotlin.text.associateTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.Pair((kotlin.text.associateTo.K,%20kotlin.text.associateTo.V)))))/destination) mutable map with key-value pairs provided by [transform](associate-to#kotlin.text%24associateTo(kotlin.CharSequence,%20kotlin.text.associateTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.Pair((kotlin.text.associateTo.K,%20kotlin.text.associateTo.V)))))/transform) function applied to each character of the given char sequence. If any of two pairs would have the same key the last one gets added to the map. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val string = "bonne journée" // associate each character with its code val result = mutableMapOf<Char, Int>() string.associateTo(result) { char -> char to char.code } // notice each letter occurs only once println(result) // {b=98, o=111, n=110, e=101, =32, j=106, u=117, r=114, é=233} //sampleEnd } ``` kotlin offsetByCodePoints offsetByCodePoints ================== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [offsetByCodePoints](offset-by-code-points) **Platform and version requirements:** JVM (1.0) ``` fun String.offsetByCodePoints(     index: Int,     codePointOffset: Int ): Int ``` Returns the index within this string that is offset from the given [index](offset-by-code-points#kotlin.text%24offsetByCodePoints(kotlin.String,%20kotlin.Int,%20kotlin.Int)/index) by [codePointOffset](offset-by-code-points#kotlin.text%24offsetByCodePoints(kotlin.String,%20kotlin.Int,%20kotlin.Int)/codePointOffset) code points. kotlin titlecaseChar titlecaseChar ============= [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [titlecaseChar](titlecase-char) **Platform and version requirements:** JVM (1.5), JS (1.5) ``` fun Char.titlecaseChar(): Char ``` Converts this character to title case using Unicode mapping rules of the invariant locale. This function performs one-to-one character mapping. To support one-to-many character mapping use the <titlecase> function. If this character has no mapping equivalent, the result of calling [uppercaseChar](uppercase-char#kotlin.text%24uppercaseChar(kotlin.Char)) is returned. ``` import java.util.* import kotlin.test.* fun main(args: Array<String>) { //sampleStart val chars = listOf('a', 'Dž', 'ʼn', '+', 'ß') val titlecaseChar = chars.map { it.titlecaseChar() } val titlecase = chars.map { it.titlecase() } println(titlecaseChar) // [A, Dž, ʼn, +, ß] println(titlecase) // [A, Dž, ʼN, +, Ss] //sampleEnd } ``` kotlin toUShort toUShort ======== [kotlin-stdlib](../../../../../index) / [kotlin.text](index) / [toUShort](to-u-short) **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun String.toUShort(): UShort ``` Parses the string as a [UShort](../kotlin/-u-short/index) number and returns the result. Exceptions ---------- `NumberFormatException` - if the string is not a valid representation of a number. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun String.toUShort(radix: Int): UShort ``` Parses the string as a [UShort](../kotlin/-u-short/index) number and returns the result. Exceptions ---------- `NumberFormatException` - if the string is not a valid representation of a number. `IllegalArgumentException` - when [radix](to-u-short#kotlin.text%24toUShort(kotlin.String,%20kotlin.Int)/radix) is not a valid radix for string to number conversion. kotlin CharacterCodingException CharacterCodingException ======================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharacterCodingException](index) **Platform and version requirements:** JS (1.4), Native (1.3) ``` open class CharacterCodingException : Exception ``` **Platform and version requirements:** JVM (1.4) ``` typealias CharacterCodingException = CharacterCodingException ``` The exception thrown when a character encoding or decoding error occurs. Constructors ------------ #### [<init>](-init-) The exception thrown when a character encoding or decoding error occurs. **Platform and version requirements:** JS (1.1), Native (1.3) ``` <init>() ``` **Platform and version requirements:** JS (1.1), Native (1.3) ``` <init>(message: String?) ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getStackTraceAddresses](../../kotlin.native/get-stack-trace-addresses) Returns a list of stack trace addresses representing the stack trace pertaining to this throwable. ``` fun Throwable.getStackTraceAddresses(): List<Long> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharacterCodingException](index) / [<init>](-init-) **Platform and version requirements:** JS (1.0), Native (1.0) ``` <init>() ``` The exception thrown when a character encoding or decoding error occurs. **Platform and version requirements:** JS (1.1), Native (1.1) ``` <init>(message: String?) ``` The exception thrown when a character encoding or decoding error occurs. kotlin MatchNamedGroupCollection MatchNamedGroupCollection ========================= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchNamedGroupCollection](index) **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) ``` interface MatchNamedGroupCollection : MatchGroupCollection ``` Extends [MatchGroupCollection](../-match-group-collection/index) by introducing a way to get matched groups by name, when regex supports it. Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <get> Returns a named group with the specified [name](get#kotlin.text.MatchNamedGroupCollection%24get(kotlin.String)/name). ``` abstract operator fun get(name: String): MatchGroup? ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [indices](../../kotlin.collections/indices) Returns an [IntRange](../../kotlin.ranges/-int-range/index) of the valid indices for this collection. ``` val Collection<*>.indices: IntRange ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [all](../../kotlin.collections/all) Returns `true` if all elements match the given [predicate](../../kotlin.collections/all#kotlin.collections%24all(kotlin.collections.Iterable((kotlin.collections.all.T)),%20kotlin.Function1((kotlin.collections.all.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [any](../../kotlin.collections/any) Returns `true` if collection has at least one element. ``` fun <T> Iterable<T>.any(): Boolean ``` Returns `true` if at least one element matches the given [predicate](../../kotlin.collections/any#kotlin.collections%24any(kotlin.collections.Iterable((kotlin.collections.any.T)),%20kotlin.Function1((kotlin.collections.any.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [asIterable](../../kotlin.collections/as-iterable) Returns this collection as an [Iterable](../../kotlin.collections/-iterable/index#kotlin.collections.Iterable). ``` fun <T> Iterable<T>.asIterable(): Iterable<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [asSequence](../../kotlin.collections/as-sequence) Creates a [Sequence](../../kotlin.sequences/-sequence/index) instance that wraps the original collection returning its elements when being iterated. ``` fun <T> Iterable<T>.asSequence(): Sequence<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [associate](../../kotlin.collections/associate) Returns a [Map](../../kotlin.collections/-map/index#kotlin.collections.Map) containing key-value pairs provided by [transform](../../kotlin.collections/associate#kotlin.collections%24associate(kotlin.collections.Iterable((kotlin.collections.associate.T)),%20kotlin.Function1((kotlin.collections.associate.T,%20kotlin.Pair((kotlin.collections.associate.K,%20kotlin.collections.associate.V)))))/transform) function applied to elements of the given collection. ``` fun <T, K, V> Iterable<T>.associate(     transform: (T) -> Pair<K, V> ): Map<K, V> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [associateBy](../../kotlin.collections/associate-by) Returns a [Map](../../kotlin.collections/-map/index#kotlin.collections.Map) containing the elements from the given collection indexed by the key returned from [keySelector](../../kotlin.collections/associate-by#kotlin.collections%24associateBy(kotlin.collections.Iterable((kotlin.collections.associateBy.T)),%20kotlin.Function1((kotlin.collections.associateBy.T,%20kotlin.collections.associateBy.K)))/keySelector) function applied to each element. ``` fun <T, K> Iterable<T>.associateBy(     keySelector: (T) -> K ): Map<K, T> ``` Returns a [Map](../../kotlin.collections/-map/index#kotlin.collections.Map) containing the values provided by [valueTransform](../../kotlin.collections/associate-by#kotlin.collections%24associateBy(kotlin.collections.Iterable((kotlin.collections.associateBy.T)),%20kotlin.Function1((kotlin.collections.associateBy.T,%20kotlin.collections.associateBy.K)),%20kotlin.Function1((kotlin.collections.associateBy.T,%20kotlin.collections.associateBy.V)))/valueTransform) and indexed by [keySelector](../../kotlin.collections/associate-by#kotlin.collections%24associateBy(kotlin.collections.Iterable((kotlin.collections.associateBy.T)),%20kotlin.Function1((kotlin.collections.associateBy.T,%20kotlin.collections.associateBy.K)),%20kotlin.Function1((kotlin.collections.associateBy.T,%20kotlin.collections.associateBy.V)))/keySelector) functions applied to elements of the given collection. ``` fun <T, K, V> Iterable<T>.associateBy(     keySelector: (T) -> K,     valueTransform: (T) -> V ): Map<K, V> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [associateByTo](../../kotlin.collections/associate-by-to) Populates and returns the [destination](../../kotlin.collections/associate-by-to#kotlin.collections%24associateByTo(kotlin.collections.Iterable((kotlin.collections.associateByTo.T)),%20kotlin.collections.associateByTo.M,%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.K)))/destination) mutable map with key-value pairs, where key is provided by the [keySelector](../../kotlin.collections/associate-by-to#kotlin.collections%24associateByTo(kotlin.collections.Iterable((kotlin.collections.associateByTo.T)),%20kotlin.collections.associateByTo.M,%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.K)))/keySelector) function applied to each element of the given collection and value is the element itself. ``` fun <T, K, M : MutableMap<in K, in T>> Iterable<T>.associateByTo(     destination: M,     keySelector: (T) -> K ): M ``` Populates and returns the [destination](../../kotlin.collections/associate-by-to#kotlin.collections%24associateByTo(kotlin.collections.Iterable((kotlin.collections.associateByTo.T)),%20kotlin.collections.associateByTo.M,%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.K)),%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.V)))/destination) mutable map with key-value pairs, where key is provided by the [keySelector](../../kotlin.collections/associate-by-to#kotlin.collections%24associateByTo(kotlin.collections.Iterable((kotlin.collections.associateByTo.T)),%20kotlin.collections.associateByTo.M,%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.K)),%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.V)))/keySelector) function and and value is provided by the [valueTransform](../../kotlin.collections/associate-by-to#kotlin.collections%24associateByTo(kotlin.collections.Iterable((kotlin.collections.associateByTo.T)),%20kotlin.collections.associateByTo.M,%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.K)),%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.V)))/valueTransform) function applied to elements of the given collection. ``` fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.associateByTo(     destination: M,     keySelector: (T) -> K,     valueTransform: (T) -> V ): M ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [associateTo](../../kotlin.collections/associate-to) Populates and returns the [destination](../../kotlin.collections/associate-to#kotlin.collections%24associateTo(kotlin.collections.Iterable((kotlin.collections.associateTo.T)),%20kotlin.collections.associateTo.M,%20kotlin.Function1((kotlin.collections.associateTo.T,%20kotlin.Pair((kotlin.collections.associateTo.K,%20kotlin.collections.associateTo.V)))))/destination) mutable map with key-value pairs provided by [transform](../../kotlin.collections/associate-to#kotlin.collections%24associateTo(kotlin.collections.Iterable((kotlin.collections.associateTo.T)),%20kotlin.collections.associateTo.M,%20kotlin.Function1((kotlin.collections.associateTo.T,%20kotlin.Pair((kotlin.collections.associateTo.K,%20kotlin.collections.associateTo.V)))))/transform) function applied to each element of the given collection. ``` fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.associateTo(     destination: M,     transform: (T) -> Pair<K, V> ): M ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [associateWith](../../kotlin.collections/associate-with) Returns a [Map](../../kotlin.collections/-map/index#kotlin.collections.Map) where keys are elements from the given collection and values are produced by the [valueSelector](../../kotlin.collections/associate-with#kotlin.collections%24associateWith(kotlin.collections.Iterable((kotlin.collections.associateWith.K)),%20kotlin.Function1((kotlin.collections.associateWith.K,%20kotlin.collections.associateWith.V)))/valueSelector) function applied to each element. ``` fun <K, V> Iterable<K>.associateWith(     valueSelector: (K) -> V ): Map<K, V> ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [associateWithTo](../../kotlin.collections/associate-with-to) Populates and returns the [destination](../../kotlin.collections/associate-with-to#kotlin.collections%24associateWithTo(kotlin.collections.Iterable((kotlin.collections.associateWithTo.K)),%20kotlin.collections.associateWithTo.M,%20kotlin.Function1((kotlin.collections.associateWithTo.K,%20kotlin.collections.associateWithTo.V)))/destination) mutable map with key-value pairs for each element of the given collection, where key is the element itself and value is provided by the [valueSelector](../../kotlin.collections/associate-with-to#kotlin.collections%24associateWithTo(kotlin.collections.Iterable((kotlin.collections.associateWithTo.K)),%20kotlin.collections.associateWithTo.M,%20kotlin.Function1((kotlin.collections.associateWithTo.K,%20kotlin.collections.associateWithTo.V)))/valueSelector) function applied to that key. ``` fun <K, V, M : MutableMap<in K, in V>> Iterable<K>.associateWithTo(     destination: M,     valueSelector: (K) -> V ): M ``` **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) #### [chunked](../../kotlin.collections/chunked) Splits this collection into a list of lists each not exceeding the given [size](../../kotlin.collections/chunked#kotlin.collections%24chunked(kotlin.collections.Iterable((kotlin.collections.chunked.T)),%20kotlin.Int)/size). ``` fun <T> Iterable<T>.chunked(size: Int): List<List<T>> ``` Splits this collection into several lists each not exceeding the given [size](../../kotlin.collections/chunked#kotlin.collections%24chunked(kotlin.collections.Iterable((kotlin.collections.chunked.T)),%20kotlin.Int,%20kotlin.Function1((kotlin.collections.List((kotlin.collections.chunked.T)),%20kotlin.collections.chunked.R)))/size) and applies the given [transform](../../kotlin.collections/chunked#kotlin.collections%24chunked(kotlin.collections.Iterable((kotlin.collections.chunked.T)),%20kotlin.Int,%20kotlin.Function1((kotlin.collections.List((kotlin.collections.chunked.T)),%20kotlin.collections.chunked.R)))/transform) function to an each. ``` fun <T, R> Iterable<T>.chunked(     size: Int,     transform: (List<T>) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [contains](../../kotlin.collections/contains) Returns `true` if [element](../../kotlin.collections/contains#kotlin.collections%24contains(kotlin.collections.Iterable((kotlin.collections.contains.T)),%20kotlin.collections.contains.T)/element) is found in the collection. ``` operator fun <T> Iterable<T>.contains(element: T): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [containsAll](../../kotlin.collections/contains-all) Checks if all elements in the specified collection are contained in this collection. ``` fun <T> Collection<T>.containsAll(     elements: Collection<T> ): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [count](../../kotlin.collections/count) Returns the number of elements matching the given [predicate](../../kotlin.collections/count#kotlin.collections%24count(kotlin.collections.Iterable((kotlin.collections.count.T)),%20kotlin.Function1((kotlin.collections.count.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.count(predicate: (T) -> Boolean): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [distinct](../../kotlin.collections/distinct) Returns a list containing only distinct elements from the given collection. ``` fun <T> Iterable<T>.distinct(): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [distinctBy](../../kotlin.collections/distinct-by) Returns a list containing only elements from the given collection having distinct keys returned by the given [selector](../../kotlin.collections/distinct-by#kotlin.collections%24distinctBy(kotlin.collections.Iterable((kotlin.collections.distinctBy.T)),%20kotlin.Function1((kotlin.collections.distinctBy.T,%20kotlin.collections.distinctBy.K)))/selector) function. ``` fun <T, K> Iterable<T>.distinctBy(     selector: (T) -> K ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [drop](../../kotlin.collections/drop) Returns a list containing all elements except first [n](../../kotlin.collections/drop#kotlin.collections%24drop(kotlin.collections.Iterable((kotlin.collections.drop.T)),%20kotlin.Int)/n) elements. ``` fun <T> Iterable<T>.drop(n: Int): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [dropWhile](../../kotlin.collections/drop-while) Returns a list containing all elements except first elements that satisfy the given [predicate](../../kotlin.collections/drop-while#kotlin.collections%24dropWhile(kotlin.collections.Iterable((kotlin.collections.dropWhile.T)),%20kotlin.Function1((kotlin.collections.dropWhile.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.dropWhile(     predicate: (T) -> Boolean ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [elementAt](../../kotlin.collections/element-at) Returns an element at the given [index](../../kotlin.collections/element-at#kotlin.collections%24elementAt(kotlin.collections.Iterable((kotlin.collections.elementAt.T)),%20kotlin.Int)/index) or throws an [IndexOutOfBoundsException](../../kotlin/-index-out-of-bounds-exception/index#kotlin.IndexOutOfBoundsException) if the [index](../../kotlin.collections/element-at#kotlin.collections%24elementAt(kotlin.collections.Iterable((kotlin.collections.elementAt.T)),%20kotlin.Int)/index) is out of bounds of this collection. ``` fun <T> Iterable<T>.elementAt(index: Int): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [elementAtOrElse](../../kotlin.collections/element-at-or-else) Returns an element at the given [index](../../kotlin.collections/element-at-or-else#kotlin.collections%24elementAtOrElse(kotlin.collections.Iterable((kotlin.collections.elementAtOrElse.T)),%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.collections.elementAtOrElse.T)))/index) or the result of calling the [defaultValue](../../kotlin.collections/element-at-or-else#kotlin.collections%24elementAtOrElse(kotlin.collections.Iterable((kotlin.collections.elementAtOrElse.T)),%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.collections.elementAtOrElse.T)))/defaultValue) function if the [index](../../kotlin.collections/element-at-or-else#kotlin.collections%24elementAtOrElse(kotlin.collections.Iterable((kotlin.collections.elementAtOrElse.T)),%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.collections.elementAtOrElse.T)))/index) is out of bounds of this collection. ``` fun <T> Iterable<T>.elementAtOrElse(     index: Int,     defaultValue: (Int) -> T ): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [elementAtOrNull](../../kotlin.collections/element-at-or-null) Returns an element at the given [index](../../kotlin.collections/element-at-or-null#kotlin.collections%24elementAtOrNull(kotlin.collections.Iterable((kotlin.collections.elementAtOrNull.T)),%20kotlin.Int)/index) or `null` if the [index](../../kotlin.collections/element-at-or-null#kotlin.collections%24elementAtOrNull(kotlin.collections.Iterable((kotlin.collections.elementAtOrNull.T)),%20kotlin.Int)/index) is out of bounds of this collection. ``` fun <T> Iterable<T>.elementAtOrNull(index: Int): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filter](../../kotlin.collections/filter) Returns a list containing only elements matching the given [predicate](../../kotlin.collections/filter#kotlin.collections%24filter(kotlin.collections.Iterable((kotlin.collections.filter.T)),%20kotlin.Function1((kotlin.collections.filter.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.filter(     predicate: (T) -> Boolean ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterIndexed](../../kotlin.collections/filter-indexed) Returns a list containing only elements matching the given [predicate](../../kotlin.collections/filter-indexed#kotlin.collections%24filterIndexed(kotlin.collections.Iterable((kotlin.collections.filterIndexed.T)),%20kotlin.Function2((kotlin.Int,%20kotlin.collections.filterIndexed.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.filterIndexed(     predicate: (index: Int, T) -> Boolean ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterIndexedTo](../../kotlin.collections/filter-indexed-to) Appends all elements matching the given [predicate](../../kotlin.collections/filter-indexed-to#kotlin.collections%24filterIndexedTo(kotlin.collections.Iterable((kotlin.collections.filterIndexedTo.T)),%20kotlin.collections.filterIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.filterIndexedTo.T,%20kotlin.Boolean)))/predicate) to the given [destination](../../kotlin.collections/filter-indexed-to#kotlin.collections%24filterIndexedTo(kotlin.collections.Iterable((kotlin.collections.filterIndexedTo.T)),%20kotlin.collections.filterIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.filterIndexedTo.T,%20kotlin.Boolean)))/destination). ``` fun <T, C : MutableCollection<in T>> Iterable<T>.filterIndexedTo(     destination: C,     predicate: (index: Int, T) -> Boolean ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterIsInstance](../../kotlin.collections/filter-is-instance) Returns a list containing all elements that are instances of specified type parameter R. ``` fun <R> Iterable<*>.filterIsInstance(): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterIsInstanceTo](../../kotlin.collections/filter-is-instance-to) Appends all elements that are instances of specified type parameter R to the given [destination](../../kotlin.collections/filter-is-instance-to#kotlin.collections%24filterIsInstanceTo(kotlin.collections.Iterable((kotlin.Any?)),%20kotlin.collections.filterIsInstanceTo.C)/destination). ``` fun <R, C : MutableCollection<in R>> Iterable<*>.filterIsInstanceTo(     destination: C ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterNot](../../kotlin.collections/filter-not) Returns a list containing all elements not matching the given [predicate](../../kotlin.collections/filter-not#kotlin.collections%24filterNot(kotlin.collections.Iterable((kotlin.collections.filterNot.T)),%20kotlin.Function1((kotlin.collections.filterNot.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.filterNot(     predicate: (T) -> Boolean ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterNotNull](../../kotlin.collections/filter-not-null) Returns a list containing all elements that are not `null`. ``` fun <T : Any> Iterable<T?>.filterNotNull(): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterNotNullTo](../../kotlin.collections/filter-not-null-to) Appends all elements that are not `null` to the given [destination](../../kotlin.collections/filter-not-null-to#kotlin.collections%24filterNotNullTo(kotlin.collections.Iterable((kotlin.collections.filterNotNullTo.T?)),%20kotlin.collections.filterNotNullTo.C)/destination). ``` fun <C : MutableCollection<in T>, T : Any> Iterable<T?>.filterNotNullTo(     destination: C ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterNotTo](../../kotlin.collections/filter-not-to) Appends all elements not matching the given [predicate](../../kotlin.collections/filter-not-to#kotlin.collections%24filterNotTo(kotlin.collections.Iterable((kotlin.collections.filterNotTo.T)),%20kotlin.collections.filterNotTo.C,%20kotlin.Function1((kotlin.collections.filterNotTo.T,%20kotlin.Boolean)))/predicate) to the given [destination](../../kotlin.collections/filter-not-to#kotlin.collections%24filterNotTo(kotlin.collections.Iterable((kotlin.collections.filterNotTo.T)),%20kotlin.collections.filterNotTo.C,%20kotlin.Function1((kotlin.collections.filterNotTo.T,%20kotlin.Boolean)))/destination). ``` fun <T, C : MutableCollection<in T>> Iterable<T>.filterNotTo(     destination: C,     predicate: (T) -> Boolean ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterTo](../../kotlin.collections/filter-to) Appends all elements matching the given [predicate](../../kotlin.collections/filter-to#kotlin.collections%24filterTo(kotlin.collections.Iterable((kotlin.collections.filterTo.T)),%20kotlin.collections.filterTo.C,%20kotlin.Function1((kotlin.collections.filterTo.T,%20kotlin.Boolean)))/predicate) to the given [destination](../../kotlin.collections/filter-to#kotlin.collections%24filterTo(kotlin.collections.Iterable((kotlin.collections.filterTo.T)),%20kotlin.collections.filterTo.C,%20kotlin.Function1((kotlin.collections.filterTo.T,%20kotlin.Boolean)))/destination). ``` fun <T, C : MutableCollection<in T>> Iterable<T>.filterTo(     destination: C,     predicate: (T) -> Boolean ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [find](../../kotlin.collections/find) Returns the first element matching the given [predicate](../../kotlin.collections/find#kotlin.collections%24find(kotlin.collections.Iterable((kotlin.collections.find.T)),%20kotlin.Function1((kotlin.collections.find.T,%20kotlin.Boolean)))/predicate), or `null` if no such element was found. ``` fun <T> Iterable<T>.find(predicate: (T) -> Boolean): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [findLast](../../kotlin.collections/find-last) Returns the last element matching the given [predicate](../../kotlin.collections/find-last#kotlin.collections%24findLast(kotlin.collections.Iterable((kotlin.collections.findLast.T)),%20kotlin.Function1((kotlin.collections.findLast.T,%20kotlin.Boolean)))/predicate), or `null` if no such element was found. ``` fun <T> Iterable<T>.findLast(predicate: (T) -> Boolean): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [first](../../kotlin.collections/first) Returns the first element. ``` fun <T> Iterable<T>.first(): T ``` Returns the first element matching the given [predicate](../../kotlin.collections/first#kotlin.collections%24first(kotlin.collections.Iterable((kotlin.collections.first.T)),%20kotlin.Function1((kotlin.collections.first.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.first(predicate: (T) -> Boolean): T ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### [firstNotNullOf](../../kotlin.collections/first-not-null-of) Returns the first non-null value produced by [transform](../../kotlin.collections/first-not-null-of#kotlin.collections%24firstNotNullOf(kotlin.collections.Iterable((kotlin.collections.firstNotNullOf.T)),%20kotlin.Function1((kotlin.collections.firstNotNullOf.T,%20kotlin.collections.firstNotNullOf.R?)))/transform) function being applied to elements of this collection in iteration order, or throws [NoSuchElementException](../../kotlin/-no-such-element-exception/index#kotlin.NoSuchElementException) if no non-null value was produced. ``` fun <T, R : Any> Iterable<T>.firstNotNullOf(     transform: (T) -> R? ): R ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### [firstNotNullOfOrNull](../../kotlin.collections/first-not-null-of-or-null) Returns the first non-null value produced by [transform](../../kotlin.collections/first-not-null-of-or-null#kotlin.collections%24firstNotNullOfOrNull(kotlin.collections.Iterable((kotlin.collections.firstNotNullOfOrNull.T)),%20kotlin.Function1((kotlin.collections.firstNotNullOfOrNull.T,%20kotlin.collections.firstNotNullOfOrNull.R?)))/transform) function being applied to elements of this collection in iteration order, or `null` if no non-null value was produced. ``` fun <T, R : Any> Iterable<T>.firstNotNullOfOrNull(     transform: (T) -> R? ): R? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [firstOrNull](../../kotlin.collections/first-or-null) Returns the first element, or `null` if the collection is empty. ``` fun <T> Iterable<T>.firstOrNull(): T? ``` Returns the first element matching the given [predicate](../../kotlin.collections/first-or-null#kotlin.collections%24firstOrNull(kotlin.collections.Iterable((kotlin.collections.firstOrNull.T)),%20kotlin.Function1((kotlin.collections.firstOrNull.T,%20kotlin.Boolean)))/predicate), or `null` if element was not found. ``` fun <T> Iterable<T>.firstOrNull(     predicate: (T) -> Boolean ): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [flatMap](../../kotlin.collections/flat-map) Returns a single list of all elements yielded from results of [transform](../../kotlin.collections/flat-map#kotlin.collections%24flatMap(kotlin.collections.Iterable((kotlin.collections.flatMap.T)),%20kotlin.Function1((kotlin.collections.flatMap.T,%20kotlin.collections.Iterable((kotlin.collections.flatMap.R)))))/transform) function being invoked on each element of original collection. ``` fun <T, R> Iterable<T>.flatMap(     transform: (T) -> Iterable<R> ): List<R> ``` ``` fun <T, R> Iterable<T>.flatMap(     transform: (T) -> Sequence<R> ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [flatMapIndexed](../../kotlin.collections/flat-map-indexed) Returns a single list of all elements yielded from results of [transform](../../kotlin.collections/flat-map-indexed#kotlin.collections%24flatMapIndexed(kotlin.collections.Iterable((kotlin.collections.flatMapIndexed.T)),%20kotlin.Function2((kotlin.Int,%20kotlin.collections.flatMapIndexed.T,%20kotlin.collections.Iterable((kotlin.collections.flatMapIndexed.R)))))/transform) function being invoked on each element and its index in the original collection. ``` fun <T, R> Iterable<T>.flatMapIndexed(     transform: (index: Int, T) -> Iterable<R> ): List<R> ``` ``` fun <T, R> Iterable<T>.flatMapIndexed(     transform: (index: Int, T) -> Sequence<R> ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [flatMapIndexedTo](../../kotlin.collections/flat-map-indexed-to) Appends all elements yielded from results of [transform](../../kotlin.collections/flat-map-indexed-to#kotlin.collections%24flatMapIndexedTo(kotlin.collections.Iterable((kotlin.collections.flatMapIndexedTo.T)),%20kotlin.collections.flatMapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.flatMapIndexedTo.T,%20kotlin.collections.Iterable((kotlin.collections.flatMapIndexedTo.R)))))/transform) function being invoked on each element and its index in the original collection, to the given [destination](../../kotlin.collections/flat-map-indexed-to#kotlin.collections%24flatMapIndexedTo(kotlin.collections.Iterable((kotlin.collections.flatMapIndexedTo.T)),%20kotlin.collections.flatMapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.flatMapIndexedTo.T,%20kotlin.collections.Iterable((kotlin.collections.flatMapIndexedTo.R)))))/destination). ``` fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapIndexedTo(     destination: C,     transform: (index: Int, T) -> Iterable<R> ): C ``` ``` fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapIndexedTo(     destination: C,     transform: (index: Int, T) -> Sequence<R> ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [flatMapTo](../../kotlin.collections/flat-map-to) Appends all elements yielded from results of [transform](../../kotlin.collections/flat-map-to#kotlin.collections%24flatMapTo(kotlin.collections.Iterable((kotlin.collections.flatMapTo.T)),%20kotlin.collections.flatMapTo.C,%20kotlin.Function1((kotlin.collections.flatMapTo.T,%20kotlin.collections.Iterable((kotlin.collections.flatMapTo.R)))))/transform) function being invoked on each element of original collection, to the given [destination](../../kotlin.collections/flat-map-to#kotlin.collections%24flatMapTo(kotlin.collections.Iterable((kotlin.collections.flatMapTo.T)),%20kotlin.collections.flatMapTo.C,%20kotlin.Function1((kotlin.collections.flatMapTo.T,%20kotlin.collections.Iterable((kotlin.collections.flatMapTo.R)))))/destination). ``` fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(     destination: C,     transform: (T) -> Iterable<R> ): C ``` ``` fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(     destination: C,     transform: (T) -> Sequence<R> ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [fold](../../kotlin.collections/fold) Accumulates value starting with [initial](../../kotlin.collections/fold#kotlin.collections%24fold(kotlin.collections.Iterable((kotlin.collections.fold.T)),%20kotlin.collections.fold.R,%20kotlin.Function2((kotlin.collections.fold.R,%20kotlin.collections.fold.T,%20)))/initial) value and applying [operation](../../kotlin.collections/fold#kotlin.collections%24fold(kotlin.collections.Iterable((kotlin.collections.fold.T)),%20kotlin.collections.fold.R,%20kotlin.Function2((kotlin.collections.fold.R,%20kotlin.collections.fold.T,%20)))/operation) from left to right to current accumulator value and each element. ``` fun <T, R> Iterable<T>.fold(     initial: R,     operation: (acc: R, T) -> R ): R ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [foldIndexed](../../kotlin.collections/fold-indexed) Accumulates value starting with [initial](../../kotlin.collections/fold-indexed#kotlin.collections%24foldIndexed(kotlin.collections.Iterable((kotlin.collections.foldIndexed.T)),%20kotlin.collections.foldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.collections.foldIndexed.R,%20kotlin.collections.foldIndexed.T,%20)))/initial) value and applying [operation](../../kotlin.collections/fold-indexed#kotlin.collections%24foldIndexed(kotlin.collections.Iterable((kotlin.collections.foldIndexed.T)),%20kotlin.collections.foldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.collections.foldIndexed.R,%20kotlin.collections.foldIndexed.T,%20)))/operation) from left to right to current accumulator value and each element with its index in the original collection. ``` fun <T, R> Iterable<T>.foldIndexed(     initial: R,     operation: (index: Int, acc: R, T) -> R ): R ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [forEach](../../kotlin.collections/for-each) Performs the given [action](../../kotlin.collections/for-each#kotlin.collections%24forEach(kotlin.collections.Iterable((kotlin.collections.forEach.T)),%20kotlin.Function1((kotlin.collections.forEach.T,%20kotlin.Unit)))/action) on each element. ``` fun <T> Iterable<T>.forEach(action: (T) -> Unit) ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [forEachIndexed](../../kotlin.collections/for-each-indexed) Performs the given [action](../../kotlin.collections/for-each-indexed#kotlin.collections%24forEachIndexed(kotlin.collections.Iterable((kotlin.collections.forEachIndexed.T)),%20kotlin.Function2((kotlin.Int,%20kotlin.collections.forEachIndexed.T,%20kotlin.Unit)))/action) on each element, providing sequential index with the element. ``` fun <T> Iterable<T>.forEachIndexed(     action: (index: Int, T) -> Unit) ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [groupBy](../../kotlin.collections/group-by) Groups elements of the original collection by the key returned by the given [keySelector](../../kotlin.collections/group-by#kotlin.collections%24groupBy(kotlin.collections.Iterable((kotlin.collections.groupBy.T)),%20kotlin.Function1((kotlin.collections.groupBy.T,%20kotlin.collections.groupBy.K)))/keySelector) function applied to each element and returns a map where each group key is associated with a list of corresponding elements. ``` fun <T, K> Iterable<T>.groupBy(     keySelector: (T) -> K ): Map<K, List<T>> ``` Groups values returned by the [valueTransform](../../kotlin.collections/group-by#kotlin.collections%24groupBy(kotlin.collections.Iterable((kotlin.collections.groupBy.T)),%20kotlin.Function1((kotlin.collections.groupBy.T,%20kotlin.collections.groupBy.K)),%20kotlin.Function1((kotlin.collections.groupBy.T,%20kotlin.collections.groupBy.V)))/valueTransform) function applied to each element of the original collection by the key returned by the given [keySelector](../../kotlin.collections/group-by#kotlin.collections%24groupBy(kotlin.collections.Iterable((kotlin.collections.groupBy.T)),%20kotlin.Function1((kotlin.collections.groupBy.T,%20kotlin.collections.groupBy.K)),%20kotlin.Function1((kotlin.collections.groupBy.T,%20kotlin.collections.groupBy.V)))/keySelector) function applied to the element and returns a map where each group key is associated with a list of corresponding values. ``` fun <T, K, V> Iterable<T>.groupBy(     keySelector: (T) -> K,     valueTransform: (T) -> V ): Map<K, List<V>> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [groupByTo](../../kotlin.collections/group-by-to) Groups elements of the original collection by the key returned by the given [keySelector](../../kotlin.collections/group-by-to#kotlin.collections%24groupByTo(kotlin.collections.Iterable((kotlin.collections.groupByTo.T)),%20kotlin.collections.groupByTo.M,%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.K)))/keySelector) function applied to each element and puts to the [destination](../../kotlin.collections/group-by-to#kotlin.collections%24groupByTo(kotlin.collections.Iterable((kotlin.collections.groupByTo.T)),%20kotlin.collections.groupByTo.M,%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.K)))/destination) map each group key associated with a list of corresponding elements. ``` fun <T, K, M : MutableMap<in K, MutableList<T>>> Iterable<T>.groupByTo(     destination: M,     keySelector: (T) -> K ): M ``` Groups values returned by the [valueTransform](../../kotlin.collections/group-by-to#kotlin.collections%24groupByTo(kotlin.collections.Iterable((kotlin.collections.groupByTo.T)),%20kotlin.collections.groupByTo.M,%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.K)),%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.V)))/valueTransform) function applied to each element of the original collection by the key returned by the given [keySelector](../../kotlin.collections/group-by-to#kotlin.collections%24groupByTo(kotlin.collections.Iterable((kotlin.collections.groupByTo.T)),%20kotlin.collections.groupByTo.M,%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.K)),%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.V)))/keySelector) function applied to the element and puts to the [destination](../../kotlin.collections/group-by-to#kotlin.collections%24groupByTo(kotlin.collections.Iterable((kotlin.collections.groupByTo.T)),%20kotlin.collections.groupByTo.M,%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.K)),%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.V)))/destination) map each group key associated with a list of corresponding values. ``` fun <T, K, V, M : MutableMap<in K, MutableList<V>>> Iterable<T>.groupByTo(     destination: M,     keySelector: (T) -> K,     valueTransform: (T) -> V ): M ``` **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) #### [groupingBy](../../kotlin.collections/grouping-by) Creates a [Grouping](../../kotlin.collections/-grouping/index) source from a collection to be used later with one of group-and-fold operations using the specified [keySelector](../../kotlin.collections/grouping-by#kotlin.collections%24groupingBy(kotlin.collections.Iterable((kotlin.collections.groupingBy.T)),%20kotlin.Function1((kotlin.collections.groupingBy.T,%20kotlin.collections.groupingBy.K)))/keySelector) function to extract a key from each element. ``` fun <T, K> Iterable<T>.groupingBy(     keySelector: (T) -> K ): Grouping<T, K> ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [ifEmpty](../../kotlin.collections/if-empty) Returns this array if it's not empty or the result of calling [defaultValue](../../kotlin.collections/if-empty#kotlin.collections%24ifEmpty(kotlin.collections.ifEmpty.C,%20kotlin.Function0((kotlin.collections.ifEmpty.R)))/defaultValue) function if the array is empty. ``` fun <C, R> C.ifEmpty(     defaultValue: () -> R ): R where C : Array<*>, C : R ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [indexOf](../../kotlin.collections/index-of) Returns first index of [element](../../kotlin.collections/index-of#kotlin.collections%24indexOf(kotlin.collections.Iterable((kotlin.collections.indexOf.T)),%20kotlin.collections.indexOf.T)/element), or -1 if the collection does not contain element. ``` fun <T> Iterable<T>.indexOf(element: T): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [indexOfFirst](../../kotlin.collections/index-of-first) Returns index of the first element matching the given [predicate](../../kotlin.collections/index-of-first#kotlin.collections%24indexOfFirst(kotlin.collections.Iterable((kotlin.collections.indexOfFirst.T)),%20kotlin.Function1((kotlin.collections.indexOfFirst.T,%20kotlin.Boolean)))/predicate), or -1 if the collection does not contain such element. ``` fun <T> Iterable<T>.indexOfFirst(     predicate: (T) -> Boolean ): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [indexOfLast](../../kotlin.collections/index-of-last) Returns index of the last element matching the given [predicate](../../kotlin.collections/index-of-last#kotlin.collections%24indexOfLast(kotlin.collections.Iterable((kotlin.collections.indexOfLast.T)),%20kotlin.Function1((kotlin.collections.indexOfLast.T,%20kotlin.Boolean)))/predicate), or -1 if the collection does not contain such element. ``` fun <T> Iterable<T>.indexOfLast(     predicate: (T) -> Boolean ): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [intersect](../../kotlin.collections/intersect) Returns a set containing all elements that are contained by both this collection and the specified collection. ``` infix fun <T> Iterable<T>.intersect(     other: Iterable<T> ): Set<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [isNotEmpty](../../kotlin.collections/is-not-empty) Returns `true` if the collection is not empty. ``` fun <T> Collection<T>.isNotEmpty(): Boolean ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [isNullOrEmpty](../../kotlin.collections/is-null-or-empty) Returns `true` if this nullable collection is either null or empty. ``` fun <T> Collection<T>?.isNullOrEmpty(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [joinTo](../../kotlin.collections/join-to) Appends the string from all the elements separated using [separator](../../kotlin.collections/join-to#kotlin.collections%24joinTo(kotlin.collections.Iterable((kotlin.collections.joinTo.T)),%20kotlin.collections.joinTo.A,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Function1?((kotlin.collections.joinTo.T,%20kotlin.CharSequence)))/separator) and using the given [prefix](../../kotlin.collections/join-to#kotlin.collections%24joinTo(kotlin.collections.Iterable((kotlin.collections.joinTo.T)),%20kotlin.collections.joinTo.A,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Function1?((kotlin.collections.joinTo.T,%20kotlin.CharSequence)))/prefix) and [postfix](../../kotlin.collections/join-to#kotlin.collections%24joinTo(kotlin.collections.Iterable((kotlin.collections.joinTo.T)),%20kotlin.collections.joinTo.A,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Function1?((kotlin.collections.joinTo.T,%20kotlin.CharSequence)))/postfix) if supplied. ``` fun <T, A : Appendable> Iterable<T>.joinTo(     buffer: A,     separator: CharSequence = ", ",     prefix: CharSequence = "",     postfix: CharSequence = "",     limit: Int = -1,     truncated: CharSequence = "...",     transform: ((T) -> CharSequence)? = null ): A ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [joinToString](../../kotlin.collections/join-to-string) Creates a string from all the elements separated using [separator](../../kotlin.collections/join-to-string#kotlin.collections%24joinToString(kotlin.collections.Iterable((kotlin.collections.joinToString.T)),%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Function1?((kotlin.collections.joinToString.T,%20kotlin.CharSequence)))/separator) and using the given [prefix](../../kotlin.collections/join-to-string#kotlin.collections%24joinToString(kotlin.collections.Iterable((kotlin.collections.joinToString.T)),%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Function1?((kotlin.collections.joinToString.T,%20kotlin.CharSequence)))/prefix) and [postfix](../../kotlin.collections/join-to-string#kotlin.collections%24joinToString(kotlin.collections.Iterable((kotlin.collections.joinToString.T)),%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Function1?((kotlin.collections.joinToString.T,%20kotlin.CharSequence)))/postfix) if supplied. ``` fun <T> Iterable<T>.joinToString(     separator: CharSequence = ", ",     prefix: CharSequence = "",     postfix: CharSequence = "",     limit: Int = -1,     truncated: CharSequence = "...",     transform: ((T) -> CharSequence)? = null ): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [last](../../kotlin.collections/last) Returns the last element. ``` fun <T> Iterable<T>.last(): T ``` Returns the last element matching the given [predicate](../../kotlin.collections/last#kotlin.collections%24last(kotlin.collections.Iterable((kotlin.collections.last.T)),%20kotlin.Function1((kotlin.collections.last.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.last(predicate: (T) -> Boolean): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [lastIndexOf](../../kotlin.collections/last-index-of) Returns last index of [element](../../kotlin.collections/last-index-of#kotlin.collections%24lastIndexOf(kotlin.collections.Iterable((kotlin.collections.lastIndexOf.T)),%20kotlin.collections.lastIndexOf.T)/element), or -1 if the collection does not contain element. ``` fun <T> Iterable<T>.lastIndexOf(element: T): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [lastOrNull](../../kotlin.collections/last-or-null) Returns the last element, or `null` if the collection is empty. ``` fun <T> Iterable<T>.lastOrNull(): T? ``` Returns the last element matching the given [predicate](../../kotlin.collections/last-or-null#kotlin.collections%24lastOrNull(kotlin.collections.Iterable((kotlin.collections.lastOrNull.T)),%20kotlin.Function1((kotlin.collections.lastOrNull.T,%20kotlin.Boolean)))/predicate), or `null` if no such element was found. ``` fun <T> Iterable<T>.lastOrNull(predicate: (T) -> Boolean): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [map](../../kotlin.collections/map) Returns a list containing the results of applying the given [transform](../../kotlin.collections/map#kotlin.collections%24map(kotlin.collections.Iterable((kotlin.collections.map.T)),%20kotlin.Function1((kotlin.collections.map.T,%20kotlin.collections.map.R)))/transform) function to each element in the original collection. ``` fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapIndexed](../../kotlin.collections/map-indexed) Returns a list containing the results of applying the given [transform](../../kotlin.collections/map-indexed#kotlin.collections%24mapIndexed(kotlin.collections.Iterable((kotlin.collections.mapIndexed.T)),%20kotlin.Function2((kotlin.Int,%20kotlin.collections.mapIndexed.T,%20kotlin.collections.mapIndexed.R)))/transform) function to each element and its index in the original collection. ``` fun <T, R> Iterable<T>.mapIndexed(     transform: (index: Int, T) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapIndexedNotNull](../../kotlin.collections/map-indexed-not-null) Returns a list containing only the non-null results of applying the given [transform](../../kotlin.collections/map-indexed-not-null#kotlin.collections%24mapIndexedNotNull(kotlin.collections.Iterable((kotlin.collections.mapIndexedNotNull.T)),%20kotlin.Function2((kotlin.Int,%20kotlin.collections.mapIndexedNotNull.T,%20kotlin.collections.mapIndexedNotNull.R?)))/transform) function to each element and its index in the original collection. ``` fun <T, R : Any> Iterable<T>.mapIndexedNotNull(     transform: (index: Int, T) -> R? ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapIndexedNotNullTo](../../kotlin.collections/map-indexed-not-null-to) Applies the given [transform](../../kotlin.collections/map-indexed-not-null-to#kotlin.collections%24mapIndexedNotNullTo(kotlin.collections.Iterable((kotlin.collections.mapIndexedNotNullTo.T)),%20kotlin.collections.mapIndexedNotNullTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.mapIndexedNotNullTo.T,%20kotlin.collections.mapIndexedNotNullTo.R?)))/transform) function to each element and its index in the original collection and appends only the non-null results to the given [destination](../../kotlin.collections/map-indexed-not-null-to#kotlin.collections%24mapIndexedNotNullTo(kotlin.collections.Iterable((kotlin.collections.mapIndexedNotNullTo.T)),%20kotlin.collections.mapIndexedNotNullTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.mapIndexedNotNullTo.T,%20kotlin.collections.mapIndexedNotNullTo.R?)))/destination). ``` fun <T, R : Any, C : MutableCollection<in R>> Iterable<T>.mapIndexedNotNullTo(     destination: C,     transform: (index: Int, T) -> R? ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapIndexedTo](../../kotlin.collections/map-indexed-to) Applies the given [transform](../../kotlin.collections/map-indexed-to#kotlin.collections%24mapIndexedTo(kotlin.collections.Iterable((kotlin.collections.mapIndexedTo.T)),%20kotlin.collections.mapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.mapIndexedTo.T,%20kotlin.collections.mapIndexedTo.R)))/transform) function to each element and its index in the original collection and appends the results to the given [destination](../../kotlin.collections/map-indexed-to#kotlin.collections%24mapIndexedTo(kotlin.collections.Iterable((kotlin.collections.mapIndexedTo.T)),%20kotlin.collections.mapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.mapIndexedTo.T,%20kotlin.collections.mapIndexedTo.R)))/destination). ``` fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapIndexedTo(     destination: C,     transform: (index: Int, T) -> R ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapNotNull](../../kotlin.collections/map-not-null) Returns a list containing only the non-null results of applying the given [transform](../../kotlin.collections/map-not-null#kotlin.collections%24mapNotNull(kotlin.collections.Iterable((kotlin.collections.mapNotNull.T)),%20kotlin.Function1((kotlin.collections.mapNotNull.T,%20kotlin.collections.mapNotNull.R?)))/transform) function to each element in the original collection. ``` fun <T, R : Any> Iterable<T>.mapNotNull(     transform: (T) -> R? ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapNotNullTo](../../kotlin.collections/map-not-null-to) Applies the given [transform](../../kotlin.collections/map-not-null-to#kotlin.collections%24mapNotNullTo(kotlin.collections.Iterable((kotlin.collections.mapNotNullTo.T)),%20kotlin.collections.mapNotNullTo.C,%20kotlin.Function1((kotlin.collections.mapNotNullTo.T,%20kotlin.collections.mapNotNullTo.R?)))/transform) function to each element in the original collection and appends only the non-null results to the given [destination](../../kotlin.collections/map-not-null-to#kotlin.collections%24mapNotNullTo(kotlin.collections.Iterable((kotlin.collections.mapNotNullTo.T)),%20kotlin.collections.mapNotNullTo.C,%20kotlin.Function1((kotlin.collections.mapNotNullTo.T,%20kotlin.collections.mapNotNullTo.R?)))/destination). ``` fun <T, R : Any, C : MutableCollection<in R>> Iterable<T>.mapNotNullTo(     destination: C,     transform: (T) -> R? ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapTo](../../kotlin.collections/map-to) Applies the given [transform](../../kotlin.collections/map-to#kotlin.collections%24mapTo(kotlin.collections.Iterable((kotlin.collections.mapTo.T)),%20kotlin.collections.mapTo.C,%20kotlin.Function1((kotlin.collections.mapTo.T,%20kotlin.collections.mapTo.R)))/transform) function to each element of the original collection and appends the results to the given [destination](../../kotlin.collections/map-to#kotlin.collections%24mapTo(kotlin.collections.Iterable((kotlin.collections.mapTo.T)),%20kotlin.collections.mapTo.C,%20kotlin.Function1((kotlin.collections.mapTo.T,%20kotlin.collections.mapTo.R)))/destination). ``` fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(     destination: C,     transform: (T) -> R ): C ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxByOrNull](../../kotlin.collections/max-by-or-null) Returns the first element yielding the largest value of the given function or `null` if there are no elements. ``` fun <T, R : Comparable<R>> Iterable<T>.maxByOrNull(     selector: (T) -> R ): T? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxOf](../../kotlin.collections/max-of) Returns the largest value among all values produced by [selector](../../kotlin.collections/max-of#kotlin.collections%24maxOf(kotlin.collections.Iterable((kotlin.collections.maxOf.T)),%20kotlin.Function1((kotlin.collections.maxOf.T,%20kotlin.Double)))/selector) function applied to each element in the collection. ``` fun <T> Iterable<T>.maxOf(selector: (T) -> Double): Double ``` ``` fun <T> Iterable<T>.maxOf(selector: (T) -> Float): Float ``` ``` fun <T, R : Comparable<R>> Iterable<T>.maxOf(     selector: (T) -> R ): R ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxOfOrNull](../../kotlin.collections/max-of-or-null) Returns the largest value among all values produced by [selector](../../kotlin.collections/max-of-or-null#kotlin.collections%24maxOfOrNull(kotlin.collections.Iterable((kotlin.collections.maxOfOrNull.T)),%20kotlin.Function1((kotlin.collections.maxOfOrNull.T,%20kotlin.Double)))/selector) function applied to each element in the collection or `null` if there are no elements. ``` fun <T> Iterable<T>.maxOfOrNull(     selector: (T) -> Double ): Double? ``` ``` fun <T> Iterable<T>.maxOfOrNull(     selector: (T) -> Float ): Float? ``` ``` fun <T, R : Comparable<R>> Iterable<T>.maxOfOrNull(     selector: (T) -> R ): R? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxOfWith](../../kotlin.collections/max-of-with) Returns the largest value according to the provided [comparator](../../kotlin.collections/max-of-with#kotlin.collections%24maxOfWith(kotlin.collections.Iterable((kotlin.collections.maxOfWith.T)),%20kotlin.Comparator((kotlin.collections.maxOfWith.R)),%20kotlin.Function1((kotlin.collections.maxOfWith.T,%20kotlin.collections.maxOfWith.R)))/comparator) among all values produced by [selector](../../kotlin.collections/max-of-with#kotlin.collections%24maxOfWith(kotlin.collections.Iterable((kotlin.collections.maxOfWith.T)),%20kotlin.Comparator((kotlin.collections.maxOfWith.R)),%20kotlin.Function1((kotlin.collections.maxOfWith.T,%20kotlin.collections.maxOfWith.R)))/selector) function applied to each element in the collection. ``` fun <T, R> Iterable<T>.maxOfWith(     comparator: Comparator<in R>,     selector: (T) -> R ): R ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxOfWithOrNull](../../kotlin.collections/max-of-with-or-null) Returns the largest value according to the provided [comparator](../../kotlin.collections/max-of-with-or-null#kotlin.collections%24maxOfWithOrNull(kotlin.collections.Iterable((kotlin.collections.maxOfWithOrNull.T)),%20kotlin.Comparator((kotlin.collections.maxOfWithOrNull.R)),%20kotlin.Function1((kotlin.collections.maxOfWithOrNull.T,%20kotlin.collections.maxOfWithOrNull.R)))/comparator) among all values produced by [selector](../../kotlin.collections/max-of-with-or-null#kotlin.collections%24maxOfWithOrNull(kotlin.collections.Iterable((kotlin.collections.maxOfWithOrNull.T)),%20kotlin.Comparator((kotlin.collections.maxOfWithOrNull.R)),%20kotlin.Function1((kotlin.collections.maxOfWithOrNull.T,%20kotlin.collections.maxOfWithOrNull.R)))/selector) function applied to each element in the collection or `null` if there are no elements. ``` fun <T, R> Iterable<T>.maxOfWithOrNull(     comparator: Comparator<in R>,     selector: (T) -> R ): R? ``` **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) #### [maxWith](../../kotlin.collections/max-with) Returns the first element having the largest value according to the provided [comparator](../../kotlin.collections/max-with#kotlin.collections%24maxWith(kotlin.collections.Iterable((kotlin.collections.maxWith.T)),%20kotlin.Comparator((kotlin.collections.maxWith.T)))/comparator). ``` fun <T> Iterable<T>.maxWith(comparator: Comparator<in T>): T ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxWithOrNull](../../kotlin.collections/max-with-or-null) Returns the first element having the largest value according to the provided [comparator](../../kotlin.collections/max-with-or-null#kotlin.collections%24maxWithOrNull(kotlin.collections.Iterable((kotlin.collections.maxWithOrNull.T)),%20kotlin.Comparator((kotlin.collections.maxWithOrNull.T)))/comparator) or `null` if there are no elements. ``` fun <T> Iterable<T>.maxWithOrNull(     comparator: Comparator<in T> ): T? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minByOrNull](../../kotlin.collections/min-by-or-null) Returns the first element yielding the smallest value of the given function or `null` if there are no elements. ``` fun <T, R : Comparable<R>> Iterable<T>.minByOrNull(     selector: (T) -> R ): T? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minOf](../../kotlin.collections/min-of) Returns the smallest value among all values produced by [selector](../../kotlin.collections/min-of#kotlin.collections%24minOf(kotlin.collections.Iterable((kotlin.collections.minOf.T)),%20kotlin.Function1((kotlin.collections.minOf.T,%20kotlin.Double)))/selector) function applied to each element in the collection. ``` fun <T> Iterable<T>.minOf(selector: (T) -> Double): Double ``` ``` fun <T> Iterable<T>.minOf(selector: (T) -> Float): Float ``` ``` fun <T, R : Comparable<R>> Iterable<T>.minOf(     selector: (T) -> R ): R ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minOfOrNull](../../kotlin.collections/min-of-or-null) Returns the smallest value among all values produced by [selector](../../kotlin.collections/min-of-or-null#kotlin.collections%24minOfOrNull(kotlin.collections.Iterable((kotlin.collections.minOfOrNull.T)),%20kotlin.Function1((kotlin.collections.minOfOrNull.T,%20kotlin.Double)))/selector) function applied to each element in the collection or `null` if there are no elements. ``` fun <T> Iterable<T>.minOfOrNull(     selector: (T) -> Double ): Double? ``` ``` fun <T> Iterable<T>.minOfOrNull(     selector: (T) -> Float ): Float? ``` ``` fun <T, R : Comparable<R>> Iterable<T>.minOfOrNull(     selector: (T) -> R ): R? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minOfWith](../../kotlin.collections/min-of-with) Returns the smallest value according to the provided [comparator](../../kotlin.collections/min-of-with#kotlin.collections%24minOfWith(kotlin.collections.Iterable((kotlin.collections.minOfWith.T)),%20kotlin.Comparator((kotlin.collections.minOfWith.R)),%20kotlin.Function1((kotlin.collections.minOfWith.T,%20kotlin.collections.minOfWith.R)))/comparator) among all values produced by [selector](../../kotlin.collections/min-of-with#kotlin.collections%24minOfWith(kotlin.collections.Iterable((kotlin.collections.minOfWith.T)),%20kotlin.Comparator((kotlin.collections.minOfWith.R)),%20kotlin.Function1((kotlin.collections.minOfWith.T,%20kotlin.collections.minOfWith.R)))/selector) function applied to each element in the collection. ``` fun <T, R> Iterable<T>.minOfWith(     comparator: Comparator<in R>,     selector: (T) -> R ): R ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minOfWithOrNull](../../kotlin.collections/min-of-with-or-null) Returns the smallest value according to the provided [comparator](../../kotlin.collections/min-of-with-or-null#kotlin.collections%24minOfWithOrNull(kotlin.collections.Iterable((kotlin.collections.minOfWithOrNull.T)),%20kotlin.Comparator((kotlin.collections.minOfWithOrNull.R)),%20kotlin.Function1((kotlin.collections.minOfWithOrNull.T,%20kotlin.collections.minOfWithOrNull.R)))/comparator) among all values produced by [selector](../../kotlin.collections/min-of-with-or-null#kotlin.collections%24minOfWithOrNull(kotlin.collections.Iterable((kotlin.collections.minOfWithOrNull.T)),%20kotlin.Comparator((kotlin.collections.minOfWithOrNull.R)),%20kotlin.Function1((kotlin.collections.minOfWithOrNull.T,%20kotlin.collections.minOfWithOrNull.R)))/selector) function applied to each element in the collection or `null` if there are no elements. ``` fun <T, R> Iterable<T>.minOfWithOrNull(     comparator: Comparator<in R>,     selector: (T) -> R ): R? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [minus](../../kotlin.collections/minus) Returns a list containing all elements of the original collection without the first occurrence of the given [element](../../kotlin.collections/minus#kotlin.collections%24minus(kotlin.collections.Iterable((kotlin.collections.minus.T)),%20kotlin.collections.minus.T)/element). ``` operator fun <T> Iterable<T>.minus(element: T): List<T> ``` Returns a list containing all elements of the original collection except the elements contained in the given [elements](../../kotlin.collections/minus#kotlin.collections%24minus(kotlin.collections.Iterable((kotlin.collections.minus.T)),%20kotlin.Array((kotlin.collections.minus.T)))/elements) array. ``` operator fun <T> Iterable<T>.minus(     elements: Array<out T> ): List<T> ``` Returns a list containing all elements of the original collection except the elements contained in the given [elements](../../kotlin.collections/minus#kotlin.collections%24minus(kotlin.collections.Iterable((kotlin.collections.minus.T)),%20kotlin.collections.Iterable((kotlin.collections.minus.T)))/elements) collection. ``` operator fun <T> Iterable<T>.minus(     elements: Iterable<T> ): List<T> ``` Returns a list containing all elements of the original collection except the elements contained in the given [elements](../../kotlin.collections/minus#kotlin.collections%24minus(kotlin.collections.Iterable((kotlin.collections.minus.T)),%20kotlin.sequences.Sequence((kotlin.collections.minus.T)))/elements) sequence. ``` operator fun <T> Iterable<T>.minus(     elements: Sequence<T> ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [minusElement](../../kotlin.collections/minus-element) Returns a list containing all elements of the original collection without the first occurrence of the given [element](../../kotlin.collections/minus-element#kotlin.collections%24minusElement(kotlin.collections.Iterable((kotlin.collections.minusElement.T)),%20kotlin.collections.minusElement.T)/element). ``` fun <T> Iterable<T>.minusElement(element: T): List<T> ``` **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) #### [minWith](../../kotlin.collections/min-with) Returns the first element having the smallest value according to the provided [comparator](../../kotlin.collections/min-with#kotlin.collections%24minWith(kotlin.collections.Iterable((kotlin.collections.minWith.T)),%20kotlin.Comparator((kotlin.collections.minWith.T)))/comparator). ``` fun <T> Iterable<T>.minWith(comparator: Comparator<in T>): T ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minWithOrNull](../../kotlin.collections/min-with-or-null) Returns the first element having the smallest value according to the provided [comparator](../../kotlin.collections/min-with-or-null#kotlin.collections%24minWithOrNull(kotlin.collections.Iterable((kotlin.collections.minWithOrNull.T)),%20kotlin.Comparator((kotlin.collections.minWithOrNull.T)))/comparator) or `null` if there are no elements. ``` fun <T> Iterable<T>.minWithOrNull(     comparator: Comparator<in T> ): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [none](../../kotlin.collections/none) Returns `true` if the collection has no elements. ``` fun <T> Iterable<T>.none(): Boolean ``` Returns `true` if no elements match the given [predicate](../../kotlin.collections/none#kotlin.collections%24none(kotlin.collections.Iterable((kotlin.collections.none.T)),%20kotlin.Function1((kotlin.collections.none.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.none(predicate: (T) -> Boolean): Boolean ``` **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) #### [onEach](../../kotlin.collections/on-each) Performs the given [action](../../kotlin.collections/on-each#kotlin.collections%24onEach(kotlin.collections.onEach.C,%20kotlin.Function1((kotlin.collections.onEach.T,%20kotlin.Unit)))/action) on each element and returns the collection itself afterwards. ``` fun <T, C : Iterable<T>> C.onEach(action: (T) -> Unit): C ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [onEachIndexed](../../kotlin.collections/on-each-indexed) Performs the given [action](../../kotlin.collections/on-each-indexed#kotlin.collections%24onEachIndexed(kotlin.collections.onEachIndexed.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.onEachIndexed.T,%20kotlin.Unit)))/action) on each element, providing sequential index with the element, and returns the collection itself afterwards. ``` fun <T, C : Iterable<T>> C.onEachIndexed(     action: (index: Int, T) -> Unit ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [orEmpty](../../kotlin.collections/or-empty) Returns this Collection if it's not `null` and the empty list otherwise. ``` fun <T> Collection<T>?.orEmpty(): Collection<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [partition](../../kotlin.collections/partition) Splits the original collection into pair of lists, where *first* list contains elements for which [predicate](../../kotlin.collections/partition#kotlin.collections%24partition(kotlin.collections.Iterable((kotlin.collections.partition.T)),%20kotlin.Function1((kotlin.collections.partition.T,%20kotlin.Boolean)))/predicate) yielded `true`, while *second* list contains elements for which [predicate](../../kotlin.collections/partition#kotlin.collections%24partition(kotlin.collections.Iterable((kotlin.collections.partition.T)),%20kotlin.Function1((kotlin.collections.partition.T,%20kotlin.Boolean)))/predicate) yielded `false`. ``` fun <T> Iterable<T>.partition(     predicate: (T) -> Boolean ): Pair<List<T>, List<T>> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [plus](../../kotlin.collections/plus) Returns a list containing all elements of the original collection and then the given [element](../../kotlin.collections/plus#kotlin.collections%24plus(kotlin.collections.Iterable((kotlin.collections.plus.T)),%20kotlin.collections.plus.T)/element). ``` operator fun <T> Iterable<T>.plus(element: T): List<T> ``` ``` operator fun <T> Collection<T>.plus(element: T): List<T> ``` Returns a list containing all elements of the original collection and then all elements of the given [elements](../../kotlin.collections/plus#kotlin.collections%24plus(kotlin.collections.Iterable((kotlin.collections.plus.T)),%20kotlin.Array((kotlin.collections.plus.T)))/elements) array. ``` operator fun <T> Iterable<T>.plus(     elements: Array<out T> ): List<T> ``` ``` operator fun <T> Collection<T>.plus(     elements: Array<out T> ): List<T> ``` Returns a list containing all elements of the original collection and then all elements of the given [elements](../../kotlin.collections/plus#kotlin.collections%24plus(kotlin.collections.Iterable((kotlin.collections.plus.T)),%20kotlin.collections.Iterable((kotlin.collections.plus.T)))/elements) collection. ``` operator fun <T> Iterable<T>.plus(     elements: Iterable<T> ): List<T> ``` ``` operator fun <T> Collection<T>.plus(     elements: Iterable<T> ): List<T> ``` Returns a list containing all elements of the original collection and then all elements of the given [elements](../../kotlin.collections/plus#kotlin.collections%24plus(kotlin.collections.Iterable((kotlin.collections.plus.T)),%20kotlin.sequences.Sequence((kotlin.collections.plus.T)))/elements) sequence. ``` operator fun <T> Iterable<T>.plus(     elements: Sequence<T> ): List<T> ``` ``` operator fun <T> Collection<T>.plus(     elements: Sequence<T> ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [plusElement](../../kotlin.collections/plus-element) Returns a list containing all elements of the original collection and then the given [element](../../kotlin.collections/plus-element#kotlin.collections%24plusElement(kotlin.collections.Iterable((kotlin.collections.plusElement.T)),%20kotlin.collections.plusElement.T)/element). ``` fun <T> Iterable<T>.plusElement(element: T): List<T> ``` ``` fun <T> Collection<T>.plusElement(element: T): List<T> ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [random](../../kotlin.collections/random) Returns a random element from this collection. ``` fun <T> Collection<T>.random(): T ``` Returns a random element from this collection using the specified source of randomness. ``` fun <T> Collection<T>.random(random: Random): T ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [randomOrNull](../../kotlin.collections/random-or-null) Returns a random element from this collection, or `null` if this collection is empty. ``` fun <T> Collection<T>.randomOrNull(): T? ``` Returns a random element from this collection using the specified source of randomness, or `null` if this collection is empty. ``` fun <T> Collection<T>.randomOrNull(random: Random): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [reduce](../../kotlin.collections/reduce) Accumulates value starting with the first element and applying [operation](../../kotlin.collections/reduce#kotlin.collections%24reduce(kotlin.collections.Iterable((kotlin.collections.reduce.T)),%20kotlin.Function2((kotlin.collections.reduce.S,%20kotlin.collections.reduce.T,%20)))/operation) from left to right to current accumulator value and each element. ``` fun <S, T : S> Iterable<T>.reduce(     operation: (acc: S, T) -> S ): S ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [reduceIndexed](../../kotlin.collections/reduce-indexed) Accumulates value starting with the first element and applying [operation](../../kotlin.collections/reduce-indexed#kotlin.collections%24reduceIndexed(kotlin.collections.Iterable((kotlin.collections.reduceIndexed.T)),%20kotlin.Function3((kotlin.Int,%20kotlin.collections.reduceIndexed.S,%20kotlin.collections.reduceIndexed.T,%20)))/operation) from left to right to current accumulator value and each element with its index in the original collection. ``` fun <S, T : S> Iterable<T>.reduceIndexed(     operation: (index: Int, acc: S, T) -> S ): S ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [reduceIndexedOrNull](../../kotlin.collections/reduce-indexed-or-null) Accumulates value starting with the first element and applying [operation](../../kotlin.collections/reduce-indexed-or-null#kotlin.collections%24reduceIndexedOrNull(kotlin.collections.Iterable((kotlin.collections.reduceIndexedOrNull.T)),%20kotlin.Function3((kotlin.Int,%20kotlin.collections.reduceIndexedOrNull.S,%20kotlin.collections.reduceIndexedOrNull.T,%20)))/operation) from left to right to current accumulator value and each element with its index in the original collection. ``` fun <S, T : S> Iterable<T>.reduceIndexedOrNull(     operation: (index: Int, acc: S, T) -> S ): S? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [reduceOrNull](../../kotlin.collections/reduce-or-null) Accumulates value starting with the first element and applying [operation](../../kotlin.collections/reduce-or-null#kotlin.collections%24reduceOrNull(kotlin.collections.Iterable((kotlin.collections.reduceOrNull.T)),%20kotlin.Function2((kotlin.collections.reduceOrNull.S,%20kotlin.collections.reduceOrNull.T,%20)))/operation) from left to right to current accumulator value and each element. ``` fun <S, T : S> Iterable<T>.reduceOrNull(     operation: (acc: S, T) -> S ): S? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [requireNoNulls](../../kotlin.collections/require-no-nulls) Returns an original collection containing all the non-`null` elements, throwing an [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) if there are any `null` elements. ``` fun <T : Any> Iterable<T?>.requireNoNulls(): Iterable<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [reversed](../../kotlin.collections/reversed) Returns a list with elements in reversed order. ``` fun <T> Iterable<T>.reversed(): List<T> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [runningFold](../../kotlin.collections/running-fold) Returns a list containing successive accumulation values generated by applying [operation](../../kotlin.collections/running-fold#kotlin.collections%24runningFold(kotlin.collections.Iterable((kotlin.collections.runningFold.T)),%20kotlin.collections.runningFold.R,%20kotlin.Function2((kotlin.collections.runningFold.R,%20kotlin.collections.runningFold.T,%20)))/operation) from left to right to each element and current accumulator value that starts with [initial](../../kotlin.collections/running-fold#kotlin.collections%24runningFold(kotlin.collections.Iterable((kotlin.collections.runningFold.T)),%20kotlin.collections.runningFold.R,%20kotlin.Function2((kotlin.collections.runningFold.R,%20kotlin.collections.runningFold.T,%20)))/initial) value. ``` fun <T, R> Iterable<T>.runningFold(     initial: R,     operation: (acc: R, T) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [runningFoldIndexed](../../kotlin.collections/running-fold-indexed) Returns a list containing successive accumulation values generated by applying [operation](../../kotlin.collections/running-fold-indexed#kotlin.collections%24runningFoldIndexed(kotlin.collections.Iterable((kotlin.collections.runningFoldIndexed.T)),%20kotlin.collections.runningFoldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.collections.runningFoldIndexed.R,%20kotlin.collections.runningFoldIndexed.T,%20)))/operation) from left to right to each element, its index in the original collection and current accumulator value that starts with [initial](../../kotlin.collections/running-fold-indexed#kotlin.collections%24runningFoldIndexed(kotlin.collections.Iterable((kotlin.collections.runningFoldIndexed.T)),%20kotlin.collections.runningFoldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.collections.runningFoldIndexed.R,%20kotlin.collections.runningFoldIndexed.T,%20)))/initial) value. ``` fun <T, R> Iterable<T>.runningFoldIndexed(     initial: R,     operation: (index: Int, acc: R, T) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [runningReduce](../../kotlin.collections/running-reduce) Returns a list containing successive accumulation values generated by applying [operation](../../kotlin.collections/running-reduce#kotlin.collections%24runningReduce(kotlin.collections.Iterable((kotlin.collections.runningReduce.T)),%20kotlin.Function2((kotlin.collections.runningReduce.S,%20kotlin.collections.runningReduce.T,%20)))/operation) from left to right to each element and current accumulator value that starts with the first element of this collection. ``` fun <S, T : S> Iterable<T>.runningReduce(     operation: (acc: S, T) -> S ): List<S> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [runningReduceIndexed](../../kotlin.collections/running-reduce-indexed) Returns a list containing successive accumulation values generated by applying [operation](../../kotlin.collections/running-reduce-indexed#kotlin.collections%24runningReduceIndexed(kotlin.collections.Iterable((kotlin.collections.runningReduceIndexed.T)),%20kotlin.Function3((kotlin.Int,%20kotlin.collections.runningReduceIndexed.S,%20kotlin.collections.runningReduceIndexed.T,%20)))/operation) from left to right to each element, its index in the original collection and current accumulator value that starts with the first element of this collection. ``` fun <S, T : S> Iterable<T>.runningReduceIndexed(     operation: (index: Int, acc: S, T) -> S ): List<S> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [scan](../../kotlin.collections/scan) Returns a list containing successive accumulation values generated by applying [operation](../../kotlin.collections/scan#kotlin.collections%24scan(kotlin.collections.Iterable((kotlin.collections.scan.T)),%20kotlin.collections.scan.R,%20kotlin.Function2((kotlin.collections.scan.R,%20kotlin.collections.scan.T,%20)))/operation) from left to right to each element and current accumulator value that starts with [initial](../../kotlin.collections/scan#kotlin.collections%24scan(kotlin.collections.Iterable((kotlin.collections.scan.T)),%20kotlin.collections.scan.R,%20kotlin.Function2((kotlin.collections.scan.R,%20kotlin.collections.scan.T,%20)))/initial) value. ``` fun <T, R> Iterable<T>.scan(     initial: R,     operation: (acc: R, T) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [scanIndexed](../../kotlin.collections/scan-indexed) Returns a list containing successive accumulation values generated by applying [operation](../../kotlin.collections/scan-indexed#kotlin.collections%24scanIndexed(kotlin.collections.Iterable((kotlin.collections.scanIndexed.T)),%20kotlin.collections.scanIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.collections.scanIndexed.R,%20kotlin.collections.scanIndexed.T,%20)))/operation) from left to right to each element, its index in the original collection and current accumulator value that starts with [initial](../../kotlin.collections/scan-indexed#kotlin.collections%24scanIndexed(kotlin.collections.Iterable((kotlin.collections.scanIndexed.T)),%20kotlin.collections.scanIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.collections.scanIndexed.R,%20kotlin.collections.scanIndexed.T,%20)))/initial) value. ``` fun <T, R> Iterable<T>.scanIndexed(     initial: R,     operation: (index: Int, acc: R, T) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [shuffled](../../kotlin.collections/shuffled) Returns a new list with the elements of this list randomly shuffled using the specified [random](../../kotlin.collections/shuffled#kotlin.collections%24shuffled(kotlin.collections.Iterable((kotlin.collections.shuffled.T)),%20kotlin.random.Random)/random) instance as the source of randomness. ``` fun <T> Iterable<T>.shuffled(random: Random): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [single](../../kotlin.collections/single) Returns the single element, or throws an exception if the collection is empty or has more than one element. ``` fun <T> Iterable<T>.single(): T ``` Returns the single element matching the given [predicate](../../kotlin.collections/single#kotlin.collections%24single(kotlin.collections.Iterable((kotlin.collections.single.T)),%20kotlin.Function1((kotlin.collections.single.T,%20kotlin.Boolean)))/predicate), or throws exception if there is no or more than one matching element. ``` fun <T> Iterable<T>.single(predicate: (T) -> Boolean): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [singleOrNull](../../kotlin.collections/single-or-null) Returns single element, or `null` if the collection is empty or has more than one element. ``` fun <T> Iterable<T>.singleOrNull(): T? ``` Returns the single element matching the given [predicate](../../kotlin.collections/single-or-null#kotlin.collections%24singleOrNull(kotlin.collections.Iterable((kotlin.collections.singleOrNull.T)),%20kotlin.Function1((kotlin.collections.singleOrNull.T,%20kotlin.Boolean)))/predicate), or `null` if element was not found or more than one element was found. ``` fun <T> Iterable<T>.singleOrNull(     predicate: (T) -> Boolean ): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [sortedBy](../../kotlin.collections/sorted-by) Returns a list of all elements sorted according to natural sort order of the value returned by specified [selector](../../kotlin.collections/sorted-by#kotlin.collections%24sortedBy(kotlin.collections.Iterable((kotlin.collections.sortedBy.T)),%20kotlin.Function1((kotlin.collections.sortedBy.T,%20kotlin.collections.sortedBy.R?)))/selector) function. ``` fun <T, R : Comparable<R>> Iterable<T>.sortedBy(     selector: (T) -> R? ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [sortedByDescending](../../kotlin.collections/sorted-by-descending) Returns a list of all elements sorted descending according to natural sort order of the value returned by specified [selector](../../kotlin.collections/sorted-by-descending#kotlin.collections%24sortedByDescending(kotlin.collections.Iterable((kotlin.collections.sortedByDescending.T)),%20kotlin.Function1((kotlin.collections.sortedByDescending.T,%20kotlin.collections.sortedByDescending.R?)))/selector) function. ``` fun <T, R : Comparable<R>> Iterable<T>.sortedByDescending(     selector: (T) -> R? ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [sortedWith](../../kotlin.collections/sorted-with) Returns a list of all elements sorted according to the specified [comparator](../../kotlin.collections/sorted-with#kotlin.collections%24sortedWith(kotlin.collections.Iterable((kotlin.collections.sortedWith.T)),%20kotlin.Comparator((kotlin.collections.sortedWith.T)))/comparator). ``` fun <T> Iterable<T>.sortedWith(     comparator: Comparator<in T> ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [subtract](../../kotlin.collections/subtract) Returns a set containing all elements that are contained by this collection and not contained by the specified collection. ``` infix fun <T> Iterable<T>.subtract(     other: Iterable<T> ): Set<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [sumBy](../../kotlin.collections/sum-by) Returns the sum of all values produced by [selector](../../kotlin.collections/sum-by#kotlin.collections%24sumBy(kotlin.collections.Iterable((kotlin.collections.sumBy.T)),%20kotlin.Function1((kotlin.collections.sumBy.T,%20kotlin.Int)))/selector) function applied to each element in the collection. ``` fun <T> Iterable<T>.sumBy(selector: (T) -> Int): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [sumByDouble](../../kotlin.collections/sum-by-double) Returns the sum of all values produced by [selector](../../kotlin.collections/sum-by-double#kotlin.collections%24sumByDouble(kotlin.collections.Iterable((kotlin.collections.sumByDouble.T)),%20kotlin.Function1((kotlin.collections.sumByDouble.T,%20kotlin.Double)))/selector) function applied to each element in the collection. ``` fun <T> Iterable<T>.sumByDouble(     selector: (T) -> Double ): Double ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [sumOf](../../kotlin.collections/sum-of) Returns the sum of all values produced by [selector](../../kotlin.collections/sum-of#kotlin.collections%24sumOf(kotlin.collections.Iterable((kotlin.collections.sumOf.T)),%20kotlin.Function1((kotlin.collections.sumOf.T,%20kotlin.Double)))/selector) function applied to each element in the collection. ``` fun <T> Iterable<T>.sumOf(selector: (T) -> Double): Double ``` ``` fun <T> Iterable<T>.sumOf(selector: (T) -> Int): Int ``` ``` fun <T> Iterable<T>.sumOf(selector: (T) -> Long): Long ``` ``` fun <T> Iterable<T>.sumOf(selector: (T) -> UInt): UInt ``` ``` fun <T> Iterable<T>.sumOf(selector: (T) -> ULong): ULong ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [take](../../kotlin.collections/take) Returns a list containing first [n](../../kotlin.collections/take#kotlin.collections%24take(kotlin.collections.Iterable((kotlin.collections.take.T)),%20kotlin.Int)/n) elements. ``` fun <T> Iterable<T>.take(n: Int): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [takeWhile](../../kotlin.collections/take-while) Returns a list containing first elements satisfying the given [predicate](../../kotlin.collections/take-while#kotlin.collections%24takeWhile(kotlin.collections.Iterable((kotlin.collections.takeWhile.T)),%20kotlin.Function1((kotlin.collections.takeWhile.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.takeWhile(     predicate: (T) -> Boolean ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toCollection](../../kotlin.collections/to-collection) Appends all elements to the given [destination](../../kotlin.collections/to-collection#kotlin.collections%24toCollection(kotlin.collections.Iterable((kotlin.collections.toCollection.T)),%20kotlin.collections.toCollection.C)/destination) collection. ``` fun <T, C : MutableCollection<in T>> Iterable<T>.toCollection(     destination: C ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toHashSet](../../kotlin.collections/to-hash-set) Returns a new [HashSet](../../kotlin.collections/-hash-set/index#kotlin.collections.HashSet) of all elements. ``` fun <T> Iterable<T>.toHashSet(): HashSet<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toList](../../kotlin.collections/to-list) Returns a [List](../../kotlin.collections/-list/index#kotlin.collections.List) containing all elements. ``` fun <T> Iterable<T>.toList(): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toMutableSet](../../kotlin.collections/to-mutable-set) Returns a new [MutableSet](../../kotlin.collections/-mutable-set/index#kotlin.collections.MutableSet) containing all distinct elements from the given collection. ``` fun <T> Iterable<T>.toMutableSet(): MutableSet<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toSet](../../kotlin.collections/to-set) Returns a [Set](../../kotlin.collections/-set/index#kotlin.collections.Set) of all elements. ``` fun <T> Iterable<T>.toSet(): Set<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [union](../../kotlin.collections/union) Returns a set containing all distinct elements from both collections. ``` infix fun <T> Iterable<T>.union(other: Iterable<T>): Set<T> ``` **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) #### [windowed](../../kotlin.collections/windowed) Returns a list of snapshots of the window of the given [size](../../kotlin.collections/windowed#kotlin.collections%24windowed(kotlin.collections.Iterable((kotlin.collections.windowed.T)),%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/size) sliding along this collection with the given [step](../../kotlin.collections/windowed#kotlin.collections%24windowed(kotlin.collections.Iterable((kotlin.collections.windowed.T)),%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/step), where each snapshot is a list. ``` fun <T> Iterable<T>.windowed(     size: Int,     step: Int = 1,     partialWindows: Boolean = false ): List<List<T>> ``` Returns a list of results of applying the given [transform](../../kotlin.collections/windowed#kotlin.collections%24windowed(kotlin.collections.Iterable((kotlin.collections.windowed.T)),%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.collections.List((kotlin.collections.windowed.T)),%20kotlin.collections.windowed.R)))/transform) function to an each list representing a view over the window of the given [size](../../kotlin.collections/windowed#kotlin.collections%24windowed(kotlin.collections.Iterable((kotlin.collections.windowed.T)),%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.collections.List((kotlin.collections.windowed.T)),%20kotlin.collections.windowed.R)))/size) sliding along this collection with the given [step](../../kotlin.collections/windowed#kotlin.collections%24windowed(kotlin.collections.Iterable((kotlin.collections.windowed.T)),%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.collections.List((kotlin.collections.windowed.T)),%20kotlin.collections.windowed.R)))/step). ``` fun <T, R> Iterable<T>.windowed(     size: Int,     step: Int = 1,     partialWindows: Boolean = false,     transform: (List<T>) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [withIndex](../../kotlin.collections/with-index) Returns a lazy [Iterable](../../kotlin.collections/-iterable/index#kotlin.collections.Iterable) that wraps each element of the original collection into an [IndexedValue](../../kotlin.collections/-indexed-value/index) containing the index of that element and the element itself. ``` fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [zip](../../kotlin.collections/zip) Returns a list of pairs built from the elements of `this` collection and the [other](../../kotlin.collections/zip#kotlin.collections%24zip(kotlin.collections.Iterable((kotlin.collections.zip.T)),%20kotlin.Array((kotlin.collections.zip.R)))/other) array with the same index. The returned list has length of the shortest collection. ``` infix fun <T, R> Iterable<T>.zip(     other: Array<out R> ): List<Pair<T, R>> ``` Returns a list of values built from the elements of `this` collection and the [other](../../kotlin.collections/zip#kotlin.collections%24zip(kotlin.collections.Iterable((kotlin.collections.zip.T)),%20kotlin.Array((kotlin.collections.zip.R)),%20kotlin.Function2((kotlin.collections.zip.T,%20kotlin.collections.zip.R,%20kotlin.collections.zip.V)))/other) array with the same index using the provided [transform](../../kotlin.collections/zip#kotlin.collections%24zip(kotlin.collections.Iterable((kotlin.collections.zip.T)),%20kotlin.Array((kotlin.collections.zip.R)),%20kotlin.Function2((kotlin.collections.zip.T,%20kotlin.collections.zip.R,%20kotlin.collections.zip.V)))/transform) function applied to each pair of elements. The returned list has length of the shortest collection. ``` fun <T, R, V> Iterable<T>.zip(     other: Array<out R>,     transform: (a: T, b: R) -> V ): List<V> ``` Returns a list of pairs built from the elements of `this` collection and [other](../../kotlin.collections/zip#kotlin.collections%24zip(kotlin.collections.Iterable((kotlin.collections.zip.T)),%20kotlin.collections.Iterable((kotlin.collections.zip.R)))/other) collection with the same index. The returned list has length of the shortest collection. ``` infix fun <T, R> Iterable<T>.zip(     other: Iterable<R> ): List<Pair<T, R>> ``` Returns a list of values built from the elements of `this` collection and the [other](../../kotlin.collections/zip#kotlin.collections%24zip(kotlin.collections.Iterable((kotlin.collections.zip.T)),%20kotlin.collections.Iterable((kotlin.collections.zip.R)),%20kotlin.Function2((kotlin.collections.zip.T,%20kotlin.collections.zip.R,%20kotlin.collections.zip.V)))/other) collection with the same index using the provided [transform](../../kotlin.collections/zip#kotlin.collections%24zip(kotlin.collections.Iterable((kotlin.collections.zip.T)),%20kotlin.collections.Iterable((kotlin.collections.zip.R)),%20kotlin.Function2((kotlin.collections.zip.T,%20kotlin.collections.zip.R,%20kotlin.collections.zip.V)))/transform) function applied to each pair of elements. The returned list has length of the shortest collection. ``` fun <T, R, V> Iterable<T>.zip(     other: Iterable<R>,     transform: (a: T, b: R) -> V ): List<V> ``` **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) #### [zipWithNext](../../kotlin.collections/zip-with-next) Returns a list of pairs of each two adjacent elements in this collection. ``` fun <T> Iterable<T>.zipWithNext(): List<Pair<T, T>> ``` Returns a list containing the results of applying the given [transform](../../kotlin.collections/zip-with-next#kotlin.collections%24zipWithNext(kotlin.collections.Iterable((kotlin.collections.zipWithNext.T)),%20kotlin.Function2((kotlin.collections.zipWithNext.T,%20,%20kotlin.collections.zipWithNext.R)))/transform) function to an each pair of two adjacent elements in this collection. ``` fun <T, R> Iterable<T>.zipWithNext(     transform: (a: T, b: T) -> R ): List<R> ```
programming_docs
kotlin get get === [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchNamedGroupCollection](index) / <get> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract operator fun get(name: String): MatchGroup? ``` Returns a named group with the specified [name](get#kotlin.text.MatchNamedGroupCollection%24get(kotlin.String)/name). Exceptions ---------- `IllegalArgumentException` - if there is no group with the specified [name](get#kotlin.text.MatchNamedGroupCollection%24get(kotlin.String)/name) defined in the regex pattern. `UnsupportedOperationException` - if this match group collection doesn't support getting match groups by name, for example, when it's not supported by the current platform. **Return** An instance of [MatchGroup](../-match-group/index#kotlin.text.MatchGroup) if the group with the specified [name](get#kotlin.text.MatchNamedGroupCollection%24get(kotlin.String)/name) was matched or `null` otherwise. kotlin insert insert ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / <insert> **Platform and version requirements:** JS (1.4) ``` fun insert(index: Int, value: Boolean): StringBuilder ``` Inserts the string representation of the specified boolean [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Boolean)/value) into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Boolean)/index) and returns this instance. The overall effect is exactly as if the [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Boolean)/value) were converted to a string by the `value.toString()` method, and then that string was inserted into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Boolean)/index). Exceptions ---------- `IndexOutOfBoundsException` - if [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Boolean)/index) is less than zero or greater than the length of this string builder. **Platform and version requirements:** JS (1.4) ``` fun insert(index: Int, value: Char): StringBuilder ``` Inserts the specified character [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Char)/value) into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Char)/index) and returns this instance. Exceptions ---------- `IndexOutOfBoundsException` - if [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Char)/index) is less than zero or greater than the length of this string builder. **Platform and version requirements:** JS (1.4) ``` fun insert(index: Int, value: CharArray): StringBuilder ``` Inserts characters in the specified character array [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharArray)/value) into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharArray)/index) and returns this instance. The inserted characters go in same order as in the [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharArray)/value) character array, starting at [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharArray)/index). Exceptions ---------- `IndexOutOfBoundsException` - if [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharArray)/index) is less than zero or greater than the length of this string builder. **Platform and version requirements:** JS (1.4) ``` fun insert(index: Int, value: CharSequence?): StringBuilder ``` Inserts characters in the specified character sequence [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharSequence?)/value) into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharSequence?)/index) and returns this instance. The inserted characters go in the same order as in the [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharSequence?)/value) character sequence, starting at [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharSequence?)/index). Parameters ---------- `index` - the position in this string builder to insert at. `value` - the character sequence from which characters are inserted. If [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharSequence?)/value) is `null`, then the four characters `"null"` are inserted. Exceptions ---------- `IndexOutOfBoundsException` - if [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharSequence?)/index) is less than zero or greater than the length of this string builder. **Platform and version requirements:** JS (1.4) ``` fun insert(index: Int, value: Any?): StringBuilder ``` Inserts the string representation of the specified object [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Any?)/value) into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Any?)/index) and returns this instance. The overall effect is exactly as if the [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Any?)/value) were converted to a string by the `value.toString()` method, and then that string was inserted into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Any?)/index). Exceptions ---------- `IndexOutOfBoundsException` - if [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Any?)/index) is less than zero or greater than the length of this string builder. **Platform and version requirements:** JS (1.4) ``` fun insert(index: Int, value: String?): StringBuilder ``` Inserts the string [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.String?)/value) into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.String?)/index) and returns this instance. If [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.String?)/value) is `null`, then the four characters `"null"` are inserted. Exceptions ---------- `IndexOutOfBoundsException` - if [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.String?)/index) is less than zero or greater than the length of this string builder. kotlin StringBuilder StringBuilder ============= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) **Platform and version requirements:** JS (1.1) ``` class StringBuilder : Appendable, CharSequence ``` **Platform and version requirements:** JVM (1.1) ``` typealias StringBuilder = StringBuilder ``` A mutable sequence of characters. String builder can be used to efficiently perform multiple string manipulation operations. Constructors ------------ **Platform and version requirements:** JS (1.0) #### [<init>](-init-) Constructs an empty string builder. ``` <init>() ``` Constructs an empty string builder with the specified initial capacity. ``` <init>(capacity: Int) ``` Constructs a string builder that contains the same characters as the specified content char sequence. ``` <init>(content: CharSequence) ``` Constructs a string builder that contains the same characters as the specified content string. ``` <init>(content: String) ``` Properties ---------- **Platform and version requirements:** JS (1.0) #### <length> Returns the length of this character sequence. ``` val length: Int ``` Functions --------- **Platform and version requirements:** JS (1.0) #### <append> Appends the specified character [value](../-appendable/append#kotlin.text.Appendable%24append(kotlin.Char)/value) to this Appendable and returns this instance. ``` fun append(value: Char): StringBuilder ``` Appends the specified character sequence [value](../-appendable/append#kotlin.text.Appendable%24append(kotlin.CharSequence?)/value) to this Appendable and returns this instance. ``` fun append(value: CharSequence?): StringBuilder ``` Appends a subsequence of the specified character sequence [value](../-appendable/append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/value) to this Appendable and returns this instance. ``` fun append(     value: CharSequence?,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Appends the string representation of the specified object [value](append#kotlin.text.StringBuilder%24append(kotlin.Any?)/value) to this string builder and returns this instance. ``` fun append(value: Any?): StringBuilder ``` Appends the string representation of the specified boolean [value](append#kotlin.text.StringBuilder%24append(kotlin.Boolean)/value) to this string builder and returns this instance. ``` fun append(value: Boolean): StringBuilder ``` Appends characters in the specified character array [value](append#kotlin.text.StringBuilder%24append(kotlin.CharArray)/value) to this string builder and returns this instance. ``` fun append(value: CharArray): StringBuilder ``` Appends the specified string [value](append#kotlin.text.StringBuilder%24append(kotlin.String?)/value) to this string builder and returns this instance. ``` fun append(value: String?): StringBuilder ``` **Platform and version requirements:** JS (1.4) #### [appendRange](append-range) Appends characters in a subarray of the specified character array [value](append-range#kotlin.text.StringBuilder%24appendRange(kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) to this string builder and returns this instance. ``` fun appendRange(     value: CharArray,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Appends a subsequence of the specified character sequence [value](append-range#kotlin.text.StringBuilder%24appendRange(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) to this string builder and returns this instance. ``` fun appendRange(     value: CharSequence,     startIndex: Int,     endIndex: Int ): StringBuilder ``` **Platform and version requirements:** JS (1.3) #### <capacity> Returns the current capacity of this string builder. ``` fun capacity(): Int ``` **Platform and version requirements:** JS (1.3) #### <clear> Clears the content of this string builder making it empty and returns this instance. ``` fun clear(): StringBuilder ``` **Platform and version requirements:** JS (1.4) #### [deleteAt](delete-at) Removes the character at the specified [index](delete-at#kotlin.text.StringBuilder%24deleteAt(kotlin.Int)/index) from this string builder and returns this instance. ``` fun deleteAt(index: Int): StringBuilder ``` **Platform and version requirements:** JS (1.4) #### [deleteRange](delete-range) Removes characters in the specified range from this string builder and returns this instance. ``` fun deleteRange(     startIndex: Int,     endIndex: Int ): StringBuilder ``` **Platform and version requirements:** JS (1.4) #### [ensureCapacity](ensure-capacity) Ensures that the capacity of this string builder is at least equal to the specified [minimumCapacity](ensure-capacity#kotlin.text.StringBuilder%24ensureCapacity(kotlin.Int)/minimumCapacity). ``` fun ensureCapacity(minimumCapacity: Int) ``` #### <get> Returns the character at the specified [index](../../kotlin/-char-sequence/get#kotlin.CharSequence%24get(kotlin.Int)/index) in this character sequence. **Platform and version requirements:** ``` operator fun get(index: Int): Char ``` **Platform and version requirements:** JS (1.1) ``` fun get(index: Int): Char ``` **Platform and version requirements:** JS (1.4) #### [indexOf](index-of) Returns the index within this string builder of the first occurrence of the specified [string](index-of#kotlin.text.StringBuilder%24indexOf(kotlin.String)/string). ``` fun indexOf(string: String): Int ``` Returns the index within this string builder of the first occurrence of the specified [string](index-of#kotlin.text.StringBuilder%24indexOf(kotlin.String,%20kotlin.Int)/string), starting at the specified [startIndex](index-of#kotlin.text.StringBuilder%24indexOf(kotlin.String,%20kotlin.Int)/startIndex). ``` fun indexOf(string: String, startIndex: Int): Int ``` **Platform and version requirements:** JS (1.4) #### <insert> Inserts the string representation of the specified boolean [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Boolean)/value) into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Boolean)/index) and returns this instance. ``` fun insert(index: Int, value: Boolean): StringBuilder ``` Inserts the specified character [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Char)/value) into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Char)/index) and returns this instance. ``` fun insert(index: Int, value: Char): StringBuilder ``` Inserts characters in the specified character array [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharArray)/value) into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharArray)/index) and returns this instance. ``` fun insert(index: Int, value: CharArray): StringBuilder ``` Inserts characters in the specified character sequence [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharSequence?)/value) into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.CharSequence?)/index) and returns this instance. ``` fun insert(index: Int, value: CharSequence?): StringBuilder ``` Inserts the string representation of the specified object [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Any?)/value) into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.Any?)/index) and returns this instance. ``` fun insert(index: Int, value: Any?): StringBuilder ``` Inserts the string [value](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.String?)/value) into this string builder at the specified [index](insert#kotlin.text.StringBuilder%24insert(kotlin.Int,%20kotlin.String?)/index) and returns this instance. ``` fun insert(index: Int, value: String?): StringBuilder ``` **Platform and version requirements:** JS (1.4) #### [insertRange](insert-range) Inserts characters in a subarray of the specified character array [value](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) into this string builder at the specified [index](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/index) and returns this instance. ``` fun insertRange(     index: Int,     value: CharArray,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Inserts characters in a subsequence of the specified character sequence [value](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) into this string builder at the specified [index](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/index) and returns this instance. ``` fun insertRange(     index: Int,     value: CharSequence,     startIndex: Int,     endIndex: Int ): StringBuilder ``` **Platform and version requirements:** JS (1.4) #### [lastIndexOf](last-index-of) Returns the index within this string builder of the last occurrence of the specified [string](last-index-of#kotlin.text.StringBuilder%24lastIndexOf(kotlin.String)/string). The last occurrence of empty string `""` is considered to be at the index equal to `this.length`. ``` fun lastIndexOf(string: String): Int ``` Returns the index within this string builder of the last occurrence of the specified [string](last-index-of#kotlin.text.StringBuilder%24lastIndexOf(kotlin.String,%20kotlin.Int)/string), starting from the specified [startIndex](last-index-of#kotlin.text.StringBuilder%24lastIndexOf(kotlin.String,%20kotlin.Int)/startIndex) toward the beginning. ``` fun lastIndexOf(string: String, startIndex: Int): Int ``` **Platform and version requirements:** JS (1.0) #### <reverse> Reverses the contents of this string builder and returns this instance. ``` fun reverse(): StringBuilder ``` **Platform and version requirements:** JS (1.4) #### <set> Sets the character at the specified [index](set#kotlin.text.StringBuilder%24set(kotlin.Int,%20kotlin.Char)/index) to the specified [value](set#kotlin.text.StringBuilder%24set(kotlin.Int,%20kotlin.Char)/value). ``` operator fun set(index: Int, value: Char) ``` **Platform and version requirements:** JS (1.4) #### [setLength](set-length) Sets the length of this string builder to the specified [newLength](set-length#kotlin.text.StringBuilder%24setLength(kotlin.Int)/newLength). ``` fun setLength(newLength: Int) ``` **Platform and version requirements:** JS (1.4) #### [setRange](set-range) Replaces characters in the specified range of this string builder with characters in the specified string [value](set-range#kotlin.text.StringBuilder%24setRange(kotlin.Int,%20kotlin.Int,%20kotlin.String)/value) and returns this instance. ``` fun setRange(     startIndex: Int,     endIndex: Int,     value: String ): StringBuilder ``` **Platform and version requirements:** JS (1.0) #### [subSequence](sub-sequence) Returns a new character sequence that is a subsequence of this character sequence, starting at the specified [startIndex](../../kotlin/-char-sequence/sub-sequence#kotlin.CharSequence%24subSequence(kotlin.Int,%20kotlin.Int)/startIndex) and ending right before the specified [endIndex](../../kotlin/-char-sequence/sub-sequence#kotlin.CharSequence%24subSequence(kotlin.Int,%20kotlin.Int)/endIndex). ``` fun subSequence(startIndex: Int, endIndex: Int): CharSequence ``` **Platform and version requirements:** JS (1.4) #### <substring> Returns a new [String](../../kotlin/-string/index#kotlin.String) that contains characters in this string builder at [startIndex](substring#kotlin.text.StringBuilder%24substring(kotlin.Int)/startIndex) (inclusive) and up to the [length](length#kotlin.text.StringBuilder%24length) (exclusive). ``` fun substring(startIndex: Int): String ``` Returns a new [String](../../kotlin/-string/index#kotlin.String) that contains characters in this string builder at [startIndex](substring#kotlin.text.StringBuilder%24substring(kotlin.Int,%20kotlin.Int)/startIndex) (inclusive) and up to the [endIndex](substring#kotlin.text.StringBuilder%24substring(kotlin.Int,%20kotlin.Int)/endIndex) (exclusive). ``` fun substring(startIndex: Int, endIndex: Int): String ``` **Platform and version requirements:** JS (1.4) #### [toCharArray](to-char-array) Copies characters from this string builder into the [destination](to-char-array#kotlin.text.StringBuilder%24toCharArray(kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destination) character array. ``` fun toCharArray(     destination: CharArray,     destinationOffset: Int = 0,     startIndex: Int = 0,     endIndex: Int = this.length) ``` **Platform and version requirements:** JS (1.1) #### [toString](to-string) ``` fun toString(): String ``` **Platform and version requirements:** JS (1.4) #### [trimToSize](trim-to-size) Attempts to reduce storage used for this string builder. ``` fun trimToSize() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [indices](../indices) Returns the range of valid character indices for this char sequence. ``` val CharSequence.indices: IntRange ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [lastIndex](../last-index) Returns the index of the last character in the char sequence or -1 if it is empty. ``` val CharSequence.lastIndex: Int ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [all](../all) Returns `true` if all characters match the given [predicate](../all#kotlin.text%24all(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` fun CharSequence.all(predicate: (Char) -> Boolean): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [any](../any) Returns `true` if char sequence has at least one character. ``` fun CharSequence.any(): Boolean ``` Returns `true` if at least one character matches the given [predicate](../any#kotlin.text%24any(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` fun CharSequence.any(predicate: (Char) -> Boolean): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [append](../append) ``` fun StringBuilder.append(obj: Any?): StringBuilder ``` ``` fun StringBuilder.append(     str: CharArray,     offset: Int,     len: Int ): StringBuilder ``` Appends all arguments to the given StringBuilder. ``` fun StringBuilder.append(     vararg value: String? ): StringBuilder ``` ``` fun StringBuilder.append(vararg value: Any?): StringBuilder ``` Appends all arguments to the given [Appendable](../-appendable/index#kotlin.text.Appendable). ``` fun <T : Appendable> T.append(vararg value: CharSequence?): T ``` #### [appendLine](../append-line) Appends a line feed character (`\n`) to this StringBuilder. **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` fun StringBuilder.appendLine(): StringBuilder ``` Appends [value](../append-line#kotlin.text%24appendLine(kotlin.text.StringBuilder,%20kotlin.CharSequence?)/value) to this [StringBuilder](index#kotlin.text.StringBuilder), followed by a line feed character (`\n`). **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` fun StringBuilder.appendLine(     value: CharSequence? ): StringBuilder ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` fun StringBuilder.appendLine(value: String?): StringBuilder ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` fun StringBuilder.appendLine(value: Any?): StringBuilder ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` fun StringBuilder.appendLine(value: CharArray): StringBuilder ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` fun StringBuilder.appendLine(value: Char): StringBuilder ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` fun StringBuilder.appendLine(value: Boolean): StringBuilder ``` **Platform and version requirements:** Native (1.4) ``` fun StringBuilder.appendLine(value: Byte): StringBuilder ``` **Platform and version requirements:** Native (1.4) ``` fun StringBuilder.appendLine(value: Short): StringBuilder ``` **Platform and version requirements:** Native (1.4) ``` fun StringBuilder.appendLine(value: Int): StringBuilder ``` **Platform and version requirements:** Native (1.4) ``` fun StringBuilder.appendLine(value: Long): StringBuilder ``` **Platform and version requirements:** Native (1.4) ``` fun StringBuilder.appendLine(value: Float): StringBuilder ``` **Platform and version requirements:** Native (1.4) ``` fun StringBuilder.appendLine(value: Double): StringBuilder ``` **Platform and version requirements:** Native (1.3) #### [appendln](../appendln) ``` fun StringBuilder.appendln(it: String): StringBuilder ``` ``` fun StringBuilder.appendln(it: Boolean): StringBuilder ``` ``` fun StringBuilder.appendln(it: Byte): StringBuilder ``` ``` fun StringBuilder.appendln(it: Short): StringBuilder ``` ``` fun StringBuilder.appendln(it: Int): StringBuilder ``` ``` fun StringBuilder.appendln(it: Long): StringBuilder ``` ``` fun StringBuilder.appendln(it: Float): StringBuilder ``` ``` fun StringBuilder.appendln(it: Double): StringBuilder ``` ``` fun StringBuilder.appendln(it: Any?): StringBuilder ``` ``` fun StringBuilder.appendln(): StringBuilder ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [asIterable](../as-iterable) Creates an [Iterable](../../kotlin.collections/-iterable/index#kotlin.collections.Iterable) instance that wraps the original char sequence returning its characters when being iterated. ``` fun CharSequence.asIterable(): Iterable<Char> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [asSequence](../as-sequence) Creates a [Sequence](../../kotlin.sequences/-sequence/index) instance that wraps the original char sequence returning its characters when being iterated. ``` fun CharSequence.asSequence(): Sequence<Char> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [associate](../associate) Returns a [Map](../../kotlin.collections/-map/index#kotlin.collections.Map) containing key-value pairs provided by [transform](../associate#kotlin.text%24associate(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Pair((kotlin.text.associate.K,%20kotlin.text.associate.V)))))/transform) function applied to characters of the given char sequence. ``` fun <K, V> CharSequence.associate(     transform: (Char) -> Pair<K, V> ): Map<K, V> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [associateBy](../associate-by) Returns a [Map](../../kotlin.collections/-map/index#kotlin.collections.Map) containing the characters from the given char sequence indexed by the key returned from [keySelector](../associate-by#kotlin.text%24associateBy(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateBy.K)))/keySelector) function applied to each character. ``` fun <K> CharSequence.associateBy(     keySelector: (Char) -> K ): Map<K, Char> ``` Returns a [Map](../../kotlin.collections/-map/index#kotlin.collections.Map) containing the values provided by [valueTransform](../associate-by#kotlin.text%24associateBy(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateBy.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateBy.V)))/valueTransform) and indexed by [keySelector](../associate-by#kotlin.text%24associateBy(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateBy.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateBy.V)))/keySelector) functions applied to characters of the given char sequence. ``` fun <K, V> CharSequence.associateBy(     keySelector: (Char) -> K,     valueTransform: (Char) -> V ): Map<K, V> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [associateByTo](../associate-by-to) Populates and returns the [destination](../associate-by-to#kotlin.text%24associateByTo(kotlin.CharSequence,%20kotlin.text.associateByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateByTo.K)))/destination) mutable map with key-value pairs, where key is provided by the [keySelector](../associate-by-to#kotlin.text%24associateByTo(kotlin.CharSequence,%20kotlin.text.associateByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateByTo.K)))/keySelector) function applied to each character of the given char sequence and value is the character itself. ``` fun <K, M : MutableMap<in K, in Char>> CharSequence.associateByTo(     destination: M,     keySelector: (Char) -> K ): M ``` Populates and returns the [destination](../associate-by-to#kotlin.text%24associateByTo(kotlin.CharSequence,%20kotlin.text.associateByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateByTo.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateByTo.V)))/destination) mutable map with key-value pairs, where key is provided by the [keySelector](../associate-by-to#kotlin.text%24associateByTo(kotlin.CharSequence,%20kotlin.text.associateByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateByTo.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateByTo.V)))/keySelector) function and and value is provided by the [valueTransform](../associate-by-to#kotlin.text%24associateByTo(kotlin.CharSequence,%20kotlin.text.associateByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateByTo.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateByTo.V)))/valueTransform) function applied to characters of the given char sequence. ``` fun <K, V, M : MutableMap<in K, in V>> CharSequence.associateByTo(     destination: M,     keySelector: (Char) -> K,     valueTransform: (Char) -> V ): M ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [associateTo](../associate-to) Populates and returns the [destination](../associate-to#kotlin.text%24associateTo(kotlin.CharSequence,%20kotlin.text.associateTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.Pair((kotlin.text.associateTo.K,%20kotlin.text.associateTo.V)))))/destination) mutable map with key-value pairs provided by [transform](../associate-to#kotlin.text%24associateTo(kotlin.CharSequence,%20kotlin.text.associateTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.Pair((kotlin.text.associateTo.K,%20kotlin.text.associateTo.V)))))/transform) function applied to each character of the given char sequence. ``` fun <K, V, M : MutableMap<in K, in V>> CharSequence.associateTo(     destination: M,     transform: (Char) -> Pair<K, V> ): M ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [associateWith](../associate-with) Returns a [Map](../../kotlin.collections/-map/index#kotlin.collections.Map) where keys are characters from the given char sequence and values are produced by the [valueSelector](../associate-with#kotlin.text%24associateWith(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateWith.V)))/valueSelector) function applied to each character. ``` fun <V> CharSequence.associateWith(     valueSelector: (Char) -> V ): Map<Char, V> ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [associateWithTo](../associate-with-to) Populates and returns the [destination](../associate-with-to#kotlin.text%24associateWithTo(kotlin.CharSequence,%20kotlin.text.associateWithTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateWithTo.V)))/destination) mutable map with key-value pairs for each character of the given char sequence, where key is the character itself and value is provided by the [valueSelector](../associate-with-to#kotlin.text%24associateWithTo(kotlin.CharSequence,%20kotlin.text.associateWithTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.associateWithTo.V)))/valueSelector) function applied to that key. ``` fun <V, M : MutableMap<in Char, in V>> CharSequence.associateWithTo(     destination: M,     valueSelector: (Char) -> V ): M ``` **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) #### [chunked](../chunked) Splits this char sequence into a list of strings each not exceeding the given [size](../chunked#kotlin.text%24chunked(kotlin.CharSequence,%20kotlin.Int)/size). ``` fun CharSequence.chunked(size: Int): List<String> ``` Splits this char sequence into several char sequences each not exceeding the given [size](../chunked#kotlin.text%24chunked(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunked.R)))/size) and applies the given [transform](../chunked#kotlin.text%24chunked(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunked.R)))/transform) function to an each. ``` fun <R> CharSequence.chunked(     size: Int,     transform: (CharSequence) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) #### [chunkedSequence](../chunked-sequence) Splits this char sequence into a sequence of strings each not exceeding the given [size](../chunked-sequence#kotlin.text%24chunkedSequence(kotlin.CharSequence,%20kotlin.Int)/size). ``` fun CharSequence.chunkedSequence(size: Int): Sequence<String> ``` Splits this char sequence into several char sequences each not exceeding the given [size](../chunked-sequence#kotlin.text%24chunkedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunkedSequence.R)))/size) and applies the given [transform](../chunked-sequence#kotlin.text%24chunkedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.chunkedSequence.R)))/transform) function to an each. ``` fun <R> CharSequence.chunkedSequence(     size: Int,     transform: (CharSequence) -> R ): Sequence<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [commonPrefixWith](../common-prefix-with) Returns the longest string `prefix` such that this char sequence and [other](../common-prefix-with#kotlin.text%24commonPrefixWith(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Boolean)/other) char sequence both start with this prefix, taking care not to split surrogate pairs. If this and [other](../common-prefix-with#kotlin.text%24commonPrefixWith(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Boolean)/other) have no common prefix, returns the empty string. ``` fun CharSequence.commonPrefixWith(     other: CharSequence,     ignoreCase: Boolean = false ): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [commonSuffixWith](../common-suffix-with) Returns the longest string `suffix` such that this char sequence and [other](../common-suffix-with#kotlin.text%24commonSuffixWith(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Boolean)/other) char sequence both end with this suffix, taking care not to split surrogate pairs. If this and [other](../common-suffix-with#kotlin.text%24commonSuffixWith(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Boolean)/other) have no common suffix, returns the empty string. ``` fun CharSequence.commonSuffixWith(     other: CharSequence,     ignoreCase: Boolean = false ): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [contains](../contains) Returns `true` if this char sequence contains the specified [other](../contains#kotlin.text%24contains(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Boolean)/other) sequence of characters as a substring. ``` operator fun CharSequence.contains(     other: CharSequence,     ignoreCase: Boolean = false ): Boolean ``` Returns `true` if this char sequence contains the specified character [char](../contains#kotlin.text%24contains(kotlin.CharSequence,%20kotlin.Char,%20kotlin.Boolean)/char). ``` operator fun CharSequence.contains(     char: Char,     ignoreCase: Boolean = false ): Boolean ``` Returns `true` if this char sequence contains at least one match of the specified regular expression [regex](../contains#kotlin.text%24contains(kotlin.CharSequence,%20kotlin.text.Regex)/regex). ``` operator fun CharSequence.contains(regex: Regex): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [count](../count) Returns the length of this char sequence. ``` fun CharSequence.count(): Int ``` Returns the number of characters matching the given [predicate](../count#kotlin.text%24count(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` fun CharSequence.count(predicate: (Char) -> Boolean): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [drop](../drop) Returns a subsequence of this char sequence with the first [n](../drop#kotlin.text%24drop(kotlin.CharSequence,%20kotlin.Int)/n) characters removed. ``` fun CharSequence.drop(n: Int): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [dropLast](../drop-last) Returns a subsequence of this char sequence with the last [n](../drop-last#kotlin.text%24dropLast(kotlin.CharSequence,%20kotlin.Int)/n) characters removed. ``` fun CharSequence.dropLast(n: Int): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [dropLastWhile](../drop-last-while) Returns a subsequence of this char sequence containing all characters except last characters that satisfy the given [predicate](../drop-last-while#kotlin.text%24dropLastWhile(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` fun CharSequence.dropLastWhile(     predicate: (Char) -> Boolean ): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [dropWhile](../drop-while) Returns a subsequence of this char sequence containing all characters except first characters that satisfy the given [predicate](../drop-while#kotlin.text%24dropWhile(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` fun CharSequence.dropWhile(     predicate: (Char) -> Boolean ): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [elementAtOrElse](../element-at-or-else) Returns a character at the given [index](../element-at-or-else#kotlin.text%24elementAtOrElse(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.Char)))/index) or the result of calling the [defaultValue](../element-at-or-else#kotlin.text%24elementAtOrElse(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.Char)))/defaultValue) function if the [index](../element-at-or-else#kotlin.text%24elementAtOrElse(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.Char)))/index) is out of bounds of this char sequence. ``` fun CharSequence.elementAtOrElse(     index: Int,     defaultValue: (Int) -> Char ): Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [elementAtOrNull](../element-at-or-null) Returns a character at the given [index](../element-at-or-null#kotlin.text%24elementAtOrNull(kotlin.CharSequence,%20kotlin.Int)/index) or `null` if the [index](../element-at-or-null#kotlin.text%24elementAtOrNull(kotlin.CharSequence,%20kotlin.Int)/index) is out of bounds of this char sequence. ``` fun CharSequence.elementAtOrNull(index: Int): Char? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [endsWith](../ends-with) Returns `true` if this char sequence ends with the specified character. ``` fun CharSequence.endsWith(     char: Char,     ignoreCase: Boolean = false ): Boolean ``` Returns `true` if this char sequence ends with the specified suffix. ``` fun CharSequence.endsWith(     suffix: CharSequence,     ignoreCase: Boolean = false ): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filter](../filter) Returns a char sequence containing only those characters from the original char sequence that match the given [predicate](../filter#kotlin.text%24filter(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` fun CharSequence.filter(     predicate: (Char) -> Boolean ): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterIndexed](../filter-indexed) Returns a char sequence containing only those characters from the original char sequence that match the given [predicate](../filter-indexed#kotlin.text%24filterIndexed(kotlin.CharSequence,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.Boolean)))/predicate). ``` fun CharSequence.filterIndexed(     predicate: (index: Int, Char) -> Boolean ): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterIndexedTo](../filter-indexed-to) Appends all characters matching the given [predicate](../filter-indexed-to#kotlin.text%24filterIndexedTo(kotlin.CharSequence,%20kotlin.text.filterIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.Boolean)))/predicate) to the given [destination](../filter-indexed-to#kotlin.text%24filterIndexedTo(kotlin.CharSequence,%20kotlin.text.filterIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.Boolean)))/destination). ``` fun <C : Appendable> CharSequence.filterIndexedTo(     destination: C,     predicate: (index: Int, Char) -> Boolean ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterNot](../filter-not) Returns a char sequence containing only those characters from the original char sequence that do not match the given [predicate](../filter-not#kotlin.text%24filterNot(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` fun CharSequence.filterNot(     predicate: (Char) -> Boolean ): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterNotTo](../filter-not-to) Appends all characters not matching the given [predicate](../filter-not-to#kotlin.text%24filterNotTo(kotlin.CharSequence,%20kotlin.text.filterNotTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate) to the given [destination](../filter-not-to#kotlin.text%24filterNotTo(kotlin.CharSequence,%20kotlin.text.filterNotTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/destination). ``` fun <C : Appendable> CharSequence.filterNotTo(     destination: C,     predicate: (Char) -> Boolean ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterTo](../filter-to) Appends all characters matching the given [predicate](../filter-to#kotlin.text%24filterTo(kotlin.CharSequence,%20kotlin.text.filterTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate) to the given [destination](../filter-to#kotlin.text%24filterTo(kotlin.CharSequence,%20kotlin.text.filterTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/destination). ``` fun <C : Appendable> CharSequence.filterTo(     destination: C,     predicate: (Char) -> Boolean ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [find](../find) Returns the first character matching the given [predicate](../find#kotlin.text%24find(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate), or `null` if no such character was found. ``` fun CharSequence.find(predicate: (Char) -> Boolean): Char? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [findAnyOf](../find-any-of) Finds the first occurrence of any of the specified [strings](../find-any-of#kotlin.text%24findAnyOf(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) in this char sequence, starting from the specified [startIndex](../find-any-of#kotlin.text%24findAnyOf(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/startIndex) and optionally ignoring the case. ``` fun CharSequence.findAnyOf(     strings: Collection<String>,     startIndex: Int = 0,     ignoreCase: Boolean = false ): Pair<Int, String>? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [findLast](../find-last) Returns the last character matching the given [predicate](../find-last#kotlin.text%24findLast(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate), or `null` if no such character was found. ``` fun CharSequence.findLast(     predicate: (Char) -> Boolean ): Char? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [findLastAnyOf](../find-last-any-of) Finds the last occurrence of any of the specified [strings](../find-last-any-of#kotlin.text%24findLastAnyOf(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) in this char sequence, starting from the specified [startIndex](../find-last-any-of#kotlin.text%24findLastAnyOf(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/startIndex) and optionally ignoring the case. ``` fun CharSequence.findLastAnyOf(     strings: Collection<String>,     startIndex: Int = lastIndex,     ignoreCase: Boolean = false ): Pair<Int, String>? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [first](../first) Returns the first character. ``` fun CharSequence.first(): Char ``` Returns the first character matching the given [predicate](../first#kotlin.text%24first(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` fun CharSequence.first(predicate: (Char) -> Boolean): Char ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### [firstNotNullOf](../first-not-null-of) Returns the first non-null value produced by [transform](../first-not-null-of#kotlin.text%24firstNotNullOf(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.firstNotNullOf.R?)))/transform) function being applied to characters of this char sequence in iteration order, or throws [NoSuchElementException](../../kotlin/-no-such-element-exception/index#kotlin.NoSuchElementException) if no non-null value was produced. ``` fun <R : Any> CharSequence.firstNotNullOf(     transform: (Char) -> R? ): R ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### [firstNotNullOfOrNull](../first-not-null-of-or-null) Returns the first non-null value produced by [transform](../first-not-null-of-or-null#kotlin.text%24firstNotNullOfOrNull(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.firstNotNullOfOrNull.R?)))/transform) function being applied to characters of this char sequence in iteration order, or `null` if no non-null value was produced. ``` fun <R : Any> CharSequence.firstNotNullOfOrNull(     transform: (Char) -> R? ): R? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [firstOrNull](../first-or-null) Returns the first character, or `null` if the char sequence is empty. ``` fun CharSequence.firstOrNull(): Char? ``` Returns the first character matching the given [predicate](../first-or-null#kotlin.text%24firstOrNull(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate), or `null` if character was not found. ``` fun CharSequence.firstOrNull(     predicate: (Char) -> Boolean ): Char? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [flatMap](../flat-map) Returns a single list of all elements yielded from results of [transform](../flat-map#kotlin.text%24flatMap(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.collections.Iterable((kotlin.text.flatMap.R)))))/transform) function being invoked on each character of original char sequence. ``` fun <R> CharSequence.flatMap(     transform: (Char) -> Iterable<R> ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [flatMapIndexed](../flat-map-indexed) Returns a single list of all elements yielded from results of [transform](../flat-map-indexed#kotlin.text%24flatMapIndexed(kotlin.CharSequence,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.collections.Iterable((kotlin.text.flatMapIndexed.R)))))/transform) function being invoked on each character and its index in the original char sequence. ``` fun <R> CharSequence.flatMapIndexed(     transform: (index: Int, Char) -> Iterable<R> ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [flatMapIndexedTo](../flat-map-indexed-to) Appends all elements yielded from results of [transform](../flat-map-indexed-to#kotlin.text%24flatMapIndexedTo(kotlin.CharSequence,%20kotlin.text.flatMapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.collections.Iterable((kotlin.text.flatMapIndexedTo.R)))))/transform) function being invoked on each character and its index in the original char sequence, to the given [destination](../flat-map-indexed-to#kotlin.text%24flatMapIndexedTo(kotlin.CharSequence,%20kotlin.text.flatMapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.collections.Iterable((kotlin.text.flatMapIndexedTo.R)))))/destination). ``` fun <R, C : MutableCollection<in R>> CharSequence.flatMapIndexedTo(     destination: C,     transform: (index: Int, Char) -> Iterable<R> ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [flatMapTo](../flat-map-to) Appends all elements yielded from results of [transform](../flat-map-to#kotlin.text%24flatMapTo(kotlin.CharSequence,%20kotlin.text.flatMapTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.collections.Iterable((kotlin.text.flatMapTo.R)))))/transform) function being invoked on each character of original char sequence, to the given [destination](../flat-map-to#kotlin.text%24flatMapTo(kotlin.CharSequence,%20kotlin.text.flatMapTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.collections.Iterable((kotlin.text.flatMapTo.R)))))/destination). ``` fun <R, C : MutableCollection<in R>> CharSequence.flatMapTo(     destination: C,     transform: (Char) -> Iterable<R> ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [fold](../fold) Accumulates value starting with [initial](../fold#kotlin.text%24fold(kotlin.CharSequence,%20kotlin.text.fold.R,%20kotlin.Function2((kotlin.text.fold.R,%20kotlin.Char,%20)))/initial) value and applying [operation](../fold#kotlin.text%24fold(kotlin.CharSequence,%20kotlin.text.fold.R,%20kotlin.Function2((kotlin.text.fold.R,%20kotlin.Char,%20)))/operation) from left to right to current accumulator value and each character. ``` fun <R> CharSequence.fold(     initial: R,     operation: (acc: R, Char) -> R ): R ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [foldIndexed](../fold-indexed) Accumulates value starting with [initial](../fold-indexed#kotlin.text%24foldIndexed(kotlin.CharSequence,%20kotlin.text.foldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.text.foldIndexed.R,%20kotlin.Char,%20)))/initial) value and applying [operation](../fold-indexed#kotlin.text%24foldIndexed(kotlin.CharSequence,%20kotlin.text.foldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.text.foldIndexed.R,%20kotlin.Char,%20)))/operation) from left to right to current accumulator value and each character with its index in the original char sequence. ``` fun <R> CharSequence.foldIndexed(     initial: R,     operation: (index: Int, acc: R, Char) -> R ): R ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [foldRight](../fold-right) Accumulates value starting with [initial](../fold-right#kotlin.text%24foldRight(kotlin.CharSequence,%20kotlin.text.foldRight.R,%20kotlin.Function2((kotlin.Char,%20kotlin.text.foldRight.R,%20)))/initial) value and applying [operation](../fold-right#kotlin.text%24foldRight(kotlin.CharSequence,%20kotlin.text.foldRight.R,%20kotlin.Function2((kotlin.Char,%20kotlin.text.foldRight.R,%20)))/operation) from right to left to each character and current accumulator value. ``` fun <R> CharSequence.foldRight(     initial: R,     operation: (Char, acc: R) -> R ): R ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [foldRightIndexed](../fold-right-indexed) Accumulates value starting with [initial](../fold-right-indexed#kotlin.text%24foldRightIndexed(kotlin.CharSequence,%20kotlin.text.foldRightIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.Char,%20kotlin.text.foldRightIndexed.R,%20)))/initial) value and applying [operation](../fold-right-indexed#kotlin.text%24foldRightIndexed(kotlin.CharSequence,%20kotlin.text.foldRightIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.Char,%20kotlin.text.foldRightIndexed.R,%20)))/operation) from right to left to each character with its index in the original char sequence and current accumulator value. ``` fun <R> CharSequence.foldRightIndexed(     initial: R,     operation: (index: Int, Char, acc: R) -> R ): R ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [forEach](../for-each) Performs the given [action](../for-each#kotlin.text%24forEach(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Unit)))/action) on each character. ``` fun CharSequence.forEach(action: (Char) -> Unit) ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [forEachIndexed](../for-each-indexed) Performs the given [action](../for-each-indexed#kotlin.text%24forEachIndexed(kotlin.CharSequence,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.Unit)))/action) on each character, providing sequential index with the character. ``` fun CharSequence.forEachIndexed(     action: (index: Int, Char) -> Unit) ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [getOrElse](../get-or-else) Returns a character at the given [index](../get-or-else#kotlin.text%24getOrElse(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.Char)))/index) or the result of calling the [defaultValue](../get-or-else#kotlin.text%24getOrElse(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.Char)))/defaultValue) function if the [index](../get-or-else#kotlin.text%24getOrElse(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.Char)))/index) is out of bounds of this char sequence. ``` fun CharSequence.getOrElse(     index: Int,     defaultValue: (Int) -> Char ): Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [getOrNull](../get-or-null) Returns a character at the given [index](../get-or-null#kotlin.text%24getOrNull(kotlin.CharSequence,%20kotlin.Int)/index) or `null` if the [index](../get-or-null#kotlin.text%24getOrNull(kotlin.CharSequence,%20kotlin.Int)/index) is out of bounds of this char sequence. ``` fun CharSequence.getOrNull(index: Int): Char? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [groupBy](../group-by) Groups characters of the original char sequence by the key returned by the given [keySelector](../group-by#kotlin.text%24groupBy(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupBy.K)))/keySelector) function applied to each character and returns a map where each group key is associated with a list of corresponding characters. ``` fun <K> CharSequence.groupBy(     keySelector: (Char) -> K ): Map<K, List<Char>> ``` Groups values returned by the [valueTransform](../group-by#kotlin.text%24groupBy(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupBy.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupBy.V)))/valueTransform) function applied to each character of the original char sequence by the key returned by the given [keySelector](../group-by#kotlin.text%24groupBy(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupBy.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupBy.V)))/keySelector) function applied to the character and returns a map where each group key is associated with a list of corresponding values. ``` fun <K, V> CharSequence.groupBy(     keySelector: (Char) -> K,     valueTransform: (Char) -> V ): Map<K, List<V>> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [groupByTo](../group-by-to) Groups characters of the original char sequence by the key returned by the given [keySelector](../group-by-to#kotlin.text%24groupByTo(kotlin.CharSequence,%20kotlin.text.groupByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.K)))/keySelector) function applied to each character and puts to the [destination](../group-by-to#kotlin.text%24groupByTo(kotlin.CharSequence,%20kotlin.text.groupByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.K)))/destination) map each group key associated with a list of corresponding characters. ``` fun <K, M : MutableMap<in K, MutableList<Char>>> CharSequence.groupByTo(     destination: M,     keySelector: (Char) -> K ): M ``` Groups values returned by the [valueTransform](../group-by-to#kotlin.text%24groupByTo(kotlin.CharSequence,%20kotlin.text.groupByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.V)))/valueTransform) function applied to each character of the original char sequence by the key returned by the given [keySelector](../group-by-to#kotlin.text%24groupByTo(kotlin.CharSequence,%20kotlin.text.groupByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.V)))/keySelector) function applied to the character and puts to the [destination](../group-by-to#kotlin.text%24groupByTo(kotlin.CharSequence,%20kotlin.text.groupByTo.M,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.K)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupByTo.V)))/destination) map each group key associated with a list of corresponding values. ``` fun <K, V, M : MutableMap<in K, MutableList<V>>> CharSequence.groupByTo(     destination: M,     keySelector: (Char) -> K,     valueTransform: (Char) -> V ): M ``` **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) #### [groupingBy](../grouping-by) Creates a [Grouping](../../kotlin.collections/-grouping/index) source from a char sequence to be used later with one of group-and-fold operations using the specified [keySelector](../grouping-by#kotlin.text%24groupingBy(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.groupingBy.K)))/keySelector) function to extract a key from each character. ``` fun <K> CharSequence.groupingBy(     keySelector: (Char) -> K ): Grouping<Char, K> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [hasSurrogatePairAt](../has-surrogate-pair-at) Returns `true` if this CharSequence has Unicode surrogate pair at the specified [index](../has-surrogate-pair-at#kotlin.text%24hasSurrogatePairAt(kotlin.CharSequence,%20kotlin.Int)/index). ``` fun CharSequence.hasSurrogatePairAt(index: Int): Boolean ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [ifBlank](../if-blank) Returns this char sequence if it is not empty and doesn't consist solely of whitespace characters, or the result of calling [defaultValue](../if-blank#kotlin.text%24ifBlank(kotlin.text.ifBlank.C,%20kotlin.Function0((kotlin.text.ifBlank.R)))/defaultValue) function otherwise. ``` fun <C, R> C.ifBlank(     defaultValue: () -> R ): R where C : CharSequence, C : R ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [ifEmpty](../if-empty) Returns this char sequence if it's not empty or the result of calling [defaultValue](../if-empty#kotlin.text%24ifEmpty(kotlin.text.ifEmpty.C,%20kotlin.Function0((kotlin.text.ifEmpty.R)))/defaultValue) function if the char sequence is empty. ``` fun <C, R> C.ifEmpty(     defaultValue: () -> R ): R where C : CharSequence, C : R ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [indexOf](../index-of) Returns the index within this string of the first occurrence of the specified character, starting from the specified [startIndex](../index-of#kotlin.text%24indexOf(kotlin.CharSequence,%20kotlin.Char,%20kotlin.Int,%20kotlin.Boolean)/startIndex). ``` fun CharSequence.indexOf(     char: Char,     startIndex: Int = 0,     ignoreCase: Boolean = false ): Int ``` Returns the index within this char sequence of the first occurrence of the specified [string](../index-of#kotlin.text%24indexOf(kotlin.CharSequence,%20kotlin.String,%20kotlin.Int,%20kotlin.Boolean)/string), starting from the specified [startIndex](../index-of#kotlin.text%24indexOf(kotlin.CharSequence,%20kotlin.String,%20kotlin.Int,%20kotlin.Boolean)/startIndex). ``` fun CharSequence.indexOf(     string: String,     startIndex: Int = 0,     ignoreCase: Boolean = false ): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [indexOfAny](../index-of-any) Finds the index of the first occurrence of any of the specified [chars](../index-of-any#kotlin.text%24indexOfAny(kotlin.CharSequence,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Boolean)/chars) in this char sequence, starting from the specified [startIndex](../index-of-any#kotlin.text%24indexOfAny(kotlin.CharSequence,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Boolean)/startIndex) and optionally ignoring the case. ``` fun CharSequence.indexOfAny(     chars: CharArray,     startIndex: Int = 0,     ignoreCase: Boolean = false ): Int ``` Finds the index of the first occurrence of any of the specified [strings](../index-of-any#kotlin.text%24indexOfAny(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) in this char sequence, starting from the specified [startIndex](../index-of-any#kotlin.text%24indexOfAny(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/startIndex) and optionally ignoring the case. ``` fun CharSequence.indexOfAny(     strings: Collection<String>,     startIndex: Int = 0,     ignoreCase: Boolean = false ): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [indexOfFirst](../index-of-first) Returns index of the first character matching the given [predicate](../index-of-first#kotlin.text%24indexOfFirst(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate), or -1 if the char sequence does not contain such character. ``` fun CharSequence.indexOfFirst(     predicate: (Char) -> Boolean ): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [indexOfLast](../index-of-last) Returns index of the last character matching the given [predicate](../index-of-last#kotlin.text%24indexOfLast(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate), or -1 if the char sequence does not contain such character. ``` fun CharSequence.indexOfLast(     predicate: (Char) -> Boolean ): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [isEmpty](../is-empty) Returns `true` if this char sequence is empty (contains no characters). ``` fun CharSequence.isEmpty(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [isNotBlank](../is-not-blank) Returns `true` if this char sequence is not empty and contains some characters except of whitespace characters. ``` fun CharSequence.isNotBlank(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [isNotEmpty](../is-not-empty) Returns `true` if this char sequence is not empty. ``` fun CharSequence.isNotEmpty(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [isNullOrBlank](../is-null-or-blank) Returns `true` if this nullable char sequence is either `null` or empty or consists solely of whitespace characters. ``` fun CharSequence?.isNullOrBlank(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [isNullOrEmpty](../is-null-or-empty) Returns `true` if this nullable char sequence is either `null` or empty. ``` fun CharSequence?.isNullOrEmpty(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [iterator](../iterator) Iterator for characters of the given char sequence. ``` operator fun CharSequence.iterator(): CharIterator ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [last](../last) Returns the last character. ``` fun CharSequence.last(): Char ``` Returns the last character matching the given [predicate](../last#kotlin.text%24last(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` fun CharSequence.last(predicate: (Char) -> Boolean): Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [lastIndexOf](../last-index-of) Returns the index within this char sequence of the last occurrence of the specified character, starting from the specified [startIndex](../last-index-of#kotlin.text%24lastIndexOf(kotlin.CharSequence,%20kotlin.Char,%20kotlin.Int,%20kotlin.Boolean)/startIndex). ``` fun CharSequence.lastIndexOf(     char: Char,     startIndex: Int = lastIndex,     ignoreCase: Boolean = false ): Int ``` Returns the index within this char sequence of the last occurrence of the specified [string](../last-index-of#kotlin.text%24lastIndexOf(kotlin.CharSequence,%20kotlin.String,%20kotlin.Int,%20kotlin.Boolean)/string), starting from the specified [startIndex](../last-index-of#kotlin.text%24lastIndexOf(kotlin.CharSequence,%20kotlin.String,%20kotlin.Int,%20kotlin.Boolean)/startIndex). ``` fun CharSequence.lastIndexOf(     string: String,     startIndex: Int = lastIndex,     ignoreCase: Boolean = false ): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [lastIndexOfAny](../last-index-of-any) Finds the index of the last occurrence of any of the specified [chars](../last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Boolean)/chars) in this char sequence, starting from the specified [startIndex](../last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Boolean)/startIndex) and optionally ignoring the case. ``` fun CharSequence.lastIndexOfAny(     chars: CharArray,     startIndex: Int = lastIndex,     ignoreCase: Boolean = false ): Int ``` Finds the index of the last occurrence of any of the specified [strings](../last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/strings) in this char sequence, starting from the specified [startIndex](../last-index-of-any#kotlin.text%24lastIndexOfAny(kotlin.CharSequence,%20kotlin.collections.Collection((kotlin.String)),%20kotlin.Int,%20kotlin.Boolean)/startIndex) and optionally ignoring the case. ``` fun CharSequence.lastIndexOfAny(     strings: Collection<String>,     startIndex: Int = lastIndex,     ignoreCase: Boolean = false ): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [lastOrNull](../last-or-null) Returns the last character, or `null` if the char sequence is empty. ``` fun CharSequence.lastOrNull(): Char? ``` Returns the last character matching the given [predicate](../last-or-null#kotlin.text%24lastOrNull(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate), or `null` if no such character was found. ``` fun CharSequence.lastOrNull(     predicate: (Char) -> Boolean ): Char? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [lines](../lines) Splits this char sequence to a list of lines delimited by any of the following character sequences: CRLF, LF or CR. ``` fun CharSequence.lines(): List<String> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [lineSequence](../line-sequence) Splits this char sequence to a sequence of lines delimited by any of the following character sequences: CRLF, LF or CR. ``` fun CharSequence.lineSequence(): Sequence<String> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [map](../map) Returns a list containing the results of applying the given [transform](../map#kotlin.text%24map(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.map.R)))/transform) function to each character in the original char sequence. ``` fun <R> CharSequence.map(transform: (Char) -> R): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapIndexed](../map-indexed) Returns a list containing the results of applying the given [transform](../map-indexed#kotlin.text%24mapIndexed(kotlin.CharSequence,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.text.mapIndexed.R)))/transform) function to each character and its index in the original char sequence. ``` fun <R> CharSequence.mapIndexed(     transform: (index: Int, Char) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapIndexedNotNull](../map-indexed-not-null) Returns a list containing only the non-null results of applying the given [transform](../map-indexed-not-null#kotlin.text%24mapIndexedNotNull(kotlin.CharSequence,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.text.mapIndexedNotNull.R?)))/transform) function to each character and its index in the original char sequence. ``` fun <R : Any> CharSequence.mapIndexedNotNull(     transform: (index: Int, Char) -> R? ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapIndexedNotNullTo](../map-indexed-not-null-to) Applies the given [transform](../map-indexed-not-null-to#kotlin.text%24mapIndexedNotNullTo(kotlin.CharSequence,%20kotlin.text.mapIndexedNotNullTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.text.mapIndexedNotNullTo.R?)))/transform) function to each character and its index in the original char sequence and appends only the non-null results to the given [destination](../map-indexed-not-null-to#kotlin.text%24mapIndexedNotNullTo(kotlin.CharSequence,%20kotlin.text.mapIndexedNotNullTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.text.mapIndexedNotNullTo.R?)))/destination). ``` fun <R : Any, C : MutableCollection<in R>> CharSequence.mapIndexedNotNullTo(     destination: C,     transform: (index: Int, Char) -> R? ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapIndexedTo](../map-indexed-to) Applies the given [transform](../map-indexed-to#kotlin.text%24mapIndexedTo(kotlin.CharSequence,%20kotlin.text.mapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.text.mapIndexedTo.R)))/transform) function to each character and its index in the original char sequence and appends the results to the given [destination](../map-indexed-to#kotlin.text%24mapIndexedTo(kotlin.CharSequence,%20kotlin.text.mapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.text.mapIndexedTo.R)))/destination). ``` fun <R, C : MutableCollection<in R>> CharSequence.mapIndexedTo(     destination: C,     transform: (index: Int, Char) -> R ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapNotNull](../map-not-null) Returns a list containing only the non-null results of applying the given [transform](../map-not-null#kotlin.text%24mapNotNull(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.text.mapNotNull.R?)))/transform) function to each character in the original char sequence. ``` fun <R : Any> CharSequence.mapNotNull(     transform: (Char) -> R? ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapNotNullTo](../map-not-null-to) Applies the given [transform](../map-not-null-to#kotlin.text%24mapNotNullTo(kotlin.CharSequence,%20kotlin.text.mapNotNullTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.text.mapNotNullTo.R?)))/transform) function to each character in the original char sequence and appends only the non-null results to the given [destination](../map-not-null-to#kotlin.text%24mapNotNullTo(kotlin.CharSequence,%20kotlin.text.mapNotNullTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.text.mapNotNullTo.R?)))/destination). ``` fun <R : Any, C : MutableCollection<in R>> CharSequence.mapNotNullTo(     destination: C,     transform: (Char) -> R? ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapTo](../map-to) Applies the given [transform](../map-to#kotlin.text%24mapTo(kotlin.CharSequence,%20kotlin.text.mapTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.text.mapTo.R)))/transform) function to each character of the original char sequence and appends the results to the given [destination](../map-to#kotlin.text%24mapTo(kotlin.CharSequence,%20kotlin.text.mapTo.C,%20kotlin.Function1((kotlin.Char,%20kotlin.text.mapTo.R)))/destination). ``` fun <R, C : MutableCollection<in R>> CharSequence.mapTo(     destination: C,     transform: (Char) -> R ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [matches](../matches) Returns `true` if this char sequence matches the given regular expression. ``` infix fun CharSequence.matches(regex: Regex): Boolean ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxByOrNull](../max-by-or-null) Returns the first character yielding the largest value of the given function or `null` if there are no characters. ``` fun <R : Comparable<R>> CharSequence.maxByOrNull(     selector: (Char) -> R ): Char? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxOf](../max-of) Returns the largest value among all values produced by [selector](../max-of#kotlin.text%24maxOf(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Double)))/selector) function applied to each character in the char sequence. ``` fun <R : Comparable<R>> any_iterable<R>.maxOf(     selector: (Char) -> R ): R ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxOfOrNull](../max-of-or-null) Returns the largest value among all values produced by [selector](../max-of-or-null#kotlin.text%24maxOfOrNull(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Double)))/selector) function applied to each character in the char sequence or `null` if there are no characters. ``` fun <R : Comparable<R>> any_iterable<R>.maxOfOrNull(     selector: (Char) -> R ): R? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxOfWith](../max-of-with) Returns the largest value according to the provided [comparator](../max-of-with#kotlin.text%24maxOfWith(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.maxOfWith.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.maxOfWith.R)))/comparator) among all values produced by [selector](../max-of-with#kotlin.text%24maxOfWith(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.maxOfWith.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.maxOfWith.R)))/selector) function applied to each character in the char sequence. ``` fun <R> CharSequence.maxOfWith(     comparator: Comparator<in R>,     selector: (Char) -> R ): R ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxOfWithOrNull](../max-of-with-or-null) Returns the largest value according to the provided [comparator](../max-of-with-or-null#kotlin.text%24maxOfWithOrNull(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.maxOfWithOrNull.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.maxOfWithOrNull.R)))/comparator) among all values produced by [selector](../max-of-with-or-null#kotlin.text%24maxOfWithOrNull(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.maxOfWithOrNull.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.maxOfWithOrNull.R)))/selector) function applied to each character in the char sequence or `null` if there are no characters. ``` fun <R> CharSequence.maxOfWithOrNull(     comparator: Comparator<in R>,     selector: (Char) -> R ): R? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxOrNull](../max-or-null) Returns the largest character or `null` if there are no characters. ``` fun CharSequence.maxOrNull(): Char? ``` **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) #### [maxWith](../max-with) Returns the first character having the largest value according to the provided [comparator](../max-with#kotlin.text%24maxWith(kotlin.CharSequence,%20kotlin.Comparator((kotlin.Char)))/comparator). ``` fun CharSequence.maxWith(     comparator: Comparator<in Char> ): Char ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxWithOrNull](../max-with-or-null) Returns the first character having the largest value according to the provided [comparator](../max-with-or-null#kotlin.text%24maxWithOrNull(kotlin.CharSequence,%20kotlin.Comparator((kotlin.Char)))/comparator) or `null` if there are no characters. ``` fun CharSequence.maxWithOrNull(     comparator: Comparator<in Char> ): Char? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minByOrNull](../min-by-or-null) Returns the first character yielding the smallest value of the given function or `null` if there are no characters. ``` fun <R : Comparable<R>> CharSequence.minByOrNull(     selector: (Char) -> R ): Char? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minOf](../min-of) Returns the smallest value among all values produced by [selector](../min-of#kotlin.text%24minOf(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Double)))/selector) function applied to each character in the char sequence. ``` fun <R : Comparable<R>> any_iterable<R>.minOf(     selector: (Char) -> R ): R ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minOfOrNull](../min-of-or-null) Returns the smallest value among all values produced by [selector](../min-of-or-null#kotlin.text%24minOfOrNull(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Double)))/selector) function applied to each character in the char sequence or `null` if there are no characters. ``` fun <R : Comparable<R>> any_iterable<R>.minOfOrNull(     selector: (Char) -> R ): R? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minOfWith](../min-of-with) Returns the smallest value according to the provided [comparator](../min-of-with#kotlin.text%24minOfWith(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.minOfWith.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.minOfWith.R)))/comparator) among all values produced by [selector](../min-of-with#kotlin.text%24minOfWith(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.minOfWith.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.minOfWith.R)))/selector) function applied to each character in the char sequence. ``` fun <R> CharSequence.minOfWith(     comparator: Comparator<in R>,     selector: (Char) -> R ): R ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minOfWithOrNull](../min-of-with-or-null) Returns the smallest value according to the provided [comparator](../min-of-with-or-null#kotlin.text%24minOfWithOrNull(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.minOfWithOrNull.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.minOfWithOrNull.R)))/comparator) among all values produced by [selector](../min-of-with-or-null#kotlin.text%24minOfWithOrNull(kotlin.CharSequence,%20kotlin.Comparator((kotlin.text.minOfWithOrNull.R)),%20kotlin.Function1((kotlin.Char,%20kotlin.text.minOfWithOrNull.R)))/selector) function applied to each character in the char sequence or `null` if there are no characters. ``` fun <R> CharSequence.minOfWithOrNull(     comparator: Comparator<in R>,     selector: (Char) -> R ): R? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minOrNull](../min-or-null) Returns the smallest character or `null` if there are no characters. ``` fun CharSequence.minOrNull(): Char? ``` **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) #### [minWith](../min-with) Returns the first character having the smallest value according to the provided [comparator](../min-with#kotlin.text%24minWith(kotlin.CharSequence,%20kotlin.Comparator((kotlin.Char)))/comparator). ``` fun CharSequence.minWith(     comparator: Comparator<in Char> ): Char ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minWithOrNull](../min-with-or-null) Returns the first character having the smallest value according to the provided [comparator](../min-with-or-null#kotlin.text%24minWithOrNull(kotlin.CharSequence,%20kotlin.Comparator((kotlin.Char)))/comparator) or `null` if there are no characters. ``` fun CharSequence.minWithOrNull(     comparator: Comparator<in Char> ): Char? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [none](../none) Returns `true` if the char sequence has no characters. ``` fun CharSequence.none(): Boolean ``` Returns `true` if no characters match the given [predicate](../none#kotlin.text%24none(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` fun CharSequence.none(predicate: (Char) -> Boolean): Boolean ``` **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) #### [onEach](../on-each) Performs the given [action](../on-each#kotlin.text%24onEach(kotlin.text.onEach.S,%20kotlin.Function1((kotlin.Char,%20kotlin.Unit)))/action) on each character and returns the char sequence itself afterwards. ``` fun <S : CharSequence> S.onEach(action: (Char) -> Unit): S ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [onEachIndexed](../on-each-indexed) Performs the given [action](../on-each-indexed#kotlin.text%24onEachIndexed(kotlin.text.onEachIndexed.S,%20kotlin.Function2((kotlin.Int,%20kotlin.Char,%20kotlin.Unit)))/action) on each character, providing sequential index with the character, and returns the char sequence itself afterwards. ``` fun <S : CharSequence> S.onEachIndexed(     action: (index: Int, Char) -> Unit ): S ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [padEnd](../pad-end) Returns a char sequence with content of this char sequence padded at the end to the specified [length](../pad-end#kotlin.text%24padEnd(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Char)/length) with the specified character or space. ``` fun CharSequence.padEnd(     length: Int,     padChar: Char = ' ' ): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [padStart](../pad-start) Returns a char sequence with content of this char sequence padded at the beginning to the specified [length](../pad-start#kotlin.text%24padStart(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Char)/length) with the specified character or space. ``` fun CharSequence.padStart(     length: Int,     padChar: Char = ' ' ): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [partition](../partition) Splits the original char sequence into pair of char sequences, where *first* char sequence contains characters for which [predicate](../partition#kotlin.text%24partition(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate) yielded `true`, while *second* char sequence contains characters for which [predicate](../partition#kotlin.text%24partition(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate) yielded `false`. ``` fun CharSequence.partition(     predicate: (Char) -> Boolean ): Pair<CharSequence, CharSequence> ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [random](../random) Returns a random character from this char sequence. ``` fun CharSequence.random(): Char ``` Returns a random character from this char sequence using the specified source of randomness. ``` fun CharSequence.random(random: Random): Char ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [randomOrNull](../random-or-null) Returns a random character from this char sequence, or `null` if this char sequence is empty. ``` fun CharSequence.randomOrNull(): Char? ``` Returns a random character from this char sequence using the specified source of randomness, or `null` if this char sequence is empty. ``` fun CharSequence.randomOrNull(random: Random): Char? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [reduce](../reduce) Accumulates value starting with the first character and applying [operation](../reduce#kotlin.text%24reduce(kotlin.CharSequence,%20kotlin.Function2((kotlin.Char,%20,%20)))/operation) from left to right to current accumulator value and each character. ``` fun CharSequence.reduce(     operation: (acc: Char, Char) -> Char ): Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [reduceIndexed](../reduce-indexed) Accumulates value starting with the first character and applying [operation](../reduce-indexed#kotlin.text%24reduceIndexed(kotlin.CharSequence,%20kotlin.Function3((kotlin.Int,%20kotlin.Char,%20,%20)))/operation) from left to right to current accumulator value and each character with its index in the original char sequence. ``` fun CharSequence.reduceIndexed(     operation: (index: Int, acc: Char, Char) -> Char ): Char ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [reduceIndexedOrNull](../reduce-indexed-or-null) Accumulates value starting with the first character and applying [operation](../reduce-indexed-or-null#kotlin.text%24reduceIndexedOrNull(kotlin.CharSequence,%20kotlin.Function3((kotlin.Int,%20kotlin.Char,%20,%20)))/operation) from left to right to current accumulator value and each character with its index in the original char sequence. ``` fun CharSequence.reduceIndexedOrNull(     operation: (index: Int, acc: Char, Char) -> Char ): Char? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [reduceOrNull](../reduce-or-null) Accumulates value starting with the first character and applying [operation](../reduce-or-null#kotlin.text%24reduceOrNull(kotlin.CharSequence,%20kotlin.Function2((kotlin.Char,%20,%20)))/operation) from left to right to current accumulator value and each character. ``` fun CharSequence.reduceOrNull(     operation: (acc: Char, Char) -> Char ): Char? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [reduceRight](../reduce-right) Accumulates value starting with the last character and applying [operation](../reduce-right#kotlin.text%24reduceRight(kotlin.CharSequence,%20kotlin.Function2((kotlin.Char,%20,%20)))/operation) from right to left to each character and current accumulator value. ``` fun CharSequence.reduceRight(     operation: (Char, acc: Char) -> Char ): Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [reduceRightIndexed](../reduce-right-indexed) Accumulates value starting with the last character and applying [operation](../reduce-right-indexed#kotlin.text%24reduceRightIndexed(kotlin.CharSequence,%20kotlin.Function3((kotlin.Int,%20kotlin.Char,%20,%20)))/operation) from right to left to each character with its index in the original char sequence and current accumulator value. ``` fun CharSequence.reduceRightIndexed(     operation: (index: Int, Char, acc: Char) -> Char ): Char ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [reduceRightIndexedOrNull](../reduce-right-indexed-or-null) Accumulates value starting with the last character and applying [operation](../reduce-right-indexed-or-null#kotlin.text%24reduceRightIndexedOrNull(kotlin.CharSequence,%20kotlin.Function3((kotlin.Int,%20kotlin.Char,%20,%20)))/operation) from right to left to each character with its index in the original char sequence and current accumulator value. ``` fun CharSequence.reduceRightIndexedOrNull(     operation: (index: Int, Char, acc: Char) -> Char ): Char? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [reduceRightOrNull](../reduce-right-or-null) Accumulates value starting with the last character and applying [operation](../reduce-right-or-null#kotlin.text%24reduceRightOrNull(kotlin.CharSequence,%20kotlin.Function2((kotlin.Char,%20,%20)))/operation) from right to left to each character and current accumulator value. ``` fun CharSequence.reduceRightOrNull(     operation: (Char, acc: Char) -> Char ): Char? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [removePrefix](../remove-prefix) If this char sequence starts with the given [prefix](../remove-prefix#kotlin.text%24removePrefix(kotlin.CharSequence,%20kotlin.CharSequence)/prefix), returns a new char sequence with the prefix removed. Otherwise, returns a new char sequence with the same characters. ``` fun CharSequence.removePrefix(     prefix: CharSequence ): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [removeRange](../remove-range) Returns a char sequence with content of this char sequence where its part at the given range is removed. ``` fun CharSequence.removeRange(     startIndex: Int,     endIndex: Int ): CharSequence ``` Returns a char sequence with content of this char sequence where its part at the given [range](../remove-range#kotlin.text%24removeRange(kotlin.CharSequence,%20kotlin.ranges.IntRange)/range) is removed. ``` fun CharSequence.removeRange(range: IntRange): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [removeSuffix](../remove-suffix) If this char sequence ends with the given [suffix](../remove-suffix#kotlin.text%24removeSuffix(kotlin.CharSequence,%20kotlin.CharSequence)/suffix), returns a new char sequence with the suffix removed. Otherwise, returns a new char sequence with the same characters. ``` fun CharSequence.removeSuffix(     suffix: CharSequence ): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [removeSurrounding](../remove-surrounding) When this char sequence starts with the given [prefix](../remove-surrounding#kotlin.text%24removeSurrounding(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence)/prefix) and ends with the given [suffix](../remove-surrounding#kotlin.text%24removeSurrounding(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence)/suffix), returns a new char sequence having both the given [prefix](../remove-surrounding#kotlin.text%24removeSurrounding(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence)/prefix) and [suffix](../remove-surrounding#kotlin.text%24removeSurrounding(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence)/suffix) removed. Otherwise returns a new char sequence with the same characters. ``` fun CharSequence.removeSurrounding(     prefix: CharSequence,     suffix: CharSequence ): CharSequence ``` When this char sequence starts with and ends with the given [delimiter](../remove-surrounding#kotlin.text%24removeSurrounding(kotlin.CharSequence,%20kotlin.CharSequence)/delimiter), returns a new char sequence having this [delimiter](../remove-surrounding#kotlin.text%24removeSurrounding(kotlin.CharSequence,%20kotlin.CharSequence)/delimiter) removed both from the start and end. Otherwise returns a new char sequence with the same characters. ``` fun CharSequence.removeSurrounding(     delimiter: CharSequence ): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [replace](../replace) Returns a new string obtained by replacing each substring of this char sequence that matches the given regular expression with the given [replacement](../replace#kotlin.text%24replace(kotlin.CharSequence,%20kotlin.text.Regex,%20kotlin.String)/replacement). ``` fun CharSequence.replace(     regex: Regex,     replacement: String ): String ``` Returns a new string obtained by replacing each substring of this char sequence that matches the given regular expression with the result of the given function [transform](../replace#kotlin.text%24replace(kotlin.CharSequence,%20kotlin.text.Regex,%20kotlin.Function1((kotlin.text.MatchResult,%20kotlin.CharSequence)))/transform) that takes [MatchResult](../-match-result/index) and returns a string to be used as a replacement for that match. ``` fun CharSequence.replace(     regex: Regex,     transform: (MatchResult) -> CharSequence ): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [replaceFirst](../replace-first) Replaces the first occurrence of the given regular expression [regex](../replace-first#kotlin.text%24replaceFirst(kotlin.CharSequence,%20kotlin.text.Regex,%20kotlin.String)/regex) in this char sequence with specified [replacement](../replace-first#kotlin.text%24replaceFirst(kotlin.CharSequence,%20kotlin.text.Regex,%20kotlin.String)/replacement) expression. ``` fun CharSequence.replaceFirst(     regex: Regex,     replacement: String ): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [replaceRange](../replace-range) Returns a char sequence with content of this char sequence where its part at the given range is replaced with the [replacement](../replace-range#kotlin.text%24replaceRange(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.CharSequence)/replacement) char sequence. ``` fun CharSequence.replaceRange(     startIndex: Int,     endIndex: Int,     replacement: CharSequence ): CharSequence ``` Returns a char sequence with content of this char sequence where its part at the given [range](../replace-range#kotlin.text%24replaceRange(kotlin.CharSequence,%20kotlin.ranges.IntRange,%20kotlin.CharSequence)/range) is replaced with the [replacement](../replace-range#kotlin.text%24replaceRange(kotlin.CharSequence,%20kotlin.ranges.IntRange,%20kotlin.CharSequence)/replacement) char sequence. ``` fun CharSequence.replaceRange(     range: IntRange,     replacement: CharSequence ): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [reversed](../reversed) Returns a char sequence with characters in reversed order. ``` fun CharSequence.reversed(): CharSequence ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [runningFold](../running-fold) Returns a list containing successive accumulation values generated by applying [operation](../running-fold#kotlin.text%24runningFold(kotlin.CharSequence,%20kotlin.text.runningFold.R,%20kotlin.Function2((kotlin.text.runningFold.R,%20kotlin.Char,%20)))/operation) from left to right to each character and current accumulator value that starts with [initial](../running-fold#kotlin.text%24runningFold(kotlin.CharSequence,%20kotlin.text.runningFold.R,%20kotlin.Function2((kotlin.text.runningFold.R,%20kotlin.Char,%20)))/initial) value. ``` fun <R> CharSequence.runningFold(     initial: R,     operation: (acc: R, Char) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [runningFoldIndexed](../running-fold-indexed) Returns a list containing successive accumulation values generated by applying [operation](../running-fold-indexed#kotlin.text%24runningFoldIndexed(kotlin.CharSequence,%20kotlin.text.runningFoldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.text.runningFoldIndexed.R,%20kotlin.Char,%20)))/operation) from left to right to each character, its index in the original char sequence and current accumulator value that starts with [initial](../running-fold-indexed#kotlin.text%24runningFoldIndexed(kotlin.CharSequence,%20kotlin.text.runningFoldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.text.runningFoldIndexed.R,%20kotlin.Char,%20)))/initial) value. ``` fun <R> CharSequence.runningFoldIndexed(     initial: R,     operation: (index: Int, acc: R, Char) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [runningReduce](../running-reduce) Returns a list containing successive accumulation values generated by applying [operation](../running-reduce#kotlin.text%24runningReduce(kotlin.CharSequence,%20kotlin.Function2((kotlin.Char,%20,%20)))/operation) from left to right to each character and current accumulator value that starts with the first character of this char sequence. ``` fun CharSequence.runningReduce(     operation: (acc: Char, Char) -> Char ): List<Char> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [runningReduceIndexed](../running-reduce-indexed) Returns a list containing successive accumulation values generated by applying [operation](../running-reduce-indexed#kotlin.text%24runningReduceIndexed(kotlin.CharSequence,%20kotlin.Function3((kotlin.Int,%20kotlin.Char,%20,%20)))/operation) from left to right to each character, its index in the original char sequence and current accumulator value that starts with the first character of this char sequence. ``` fun CharSequence.runningReduceIndexed(     operation: (index: Int, acc: Char, Char) -> Char ): List<Char> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [scan](../scan) Returns a list containing successive accumulation values generated by applying [operation](../scan#kotlin.text%24scan(kotlin.CharSequence,%20kotlin.text.scan.R,%20kotlin.Function2((kotlin.text.scan.R,%20kotlin.Char,%20)))/operation) from left to right to each character and current accumulator value that starts with [initial](../scan#kotlin.text%24scan(kotlin.CharSequence,%20kotlin.text.scan.R,%20kotlin.Function2((kotlin.text.scan.R,%20kotlin.Char,%20)))/initial) value. ``` fun <R> CharSequence.scan(     initial: R,     operation: (acc: R, Char) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [scanIndexed](../scan-indexed) Returns a list containing successive accumulation values generated by applying [operation](../scan-indexed#kotlin.text%24scanIndexed(kotlin.CharSequence,%20kotlin.text.scanIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.text.scanIndexed.R,%20kotlin.Char,%20)))/operation) from left to right to each character, its index in the original char sequence and current accumulator value that starts with [initial](../scan-indexed#kotlin.text%24scanIndexed(kotlin.CharSequence,%20kotlin.text.scanIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.text.scanIndexed.R,%20kotlin.Char,%20)))/initial) value. ``` fun <R> CharSequence.scanIndexed(     initial: R,     operation: (index: Int, acc: R, Char) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [single](../single) Returns the single character, or throws an exception if the char sequence is empty or has more than one character. ``` fun CharSequence.single(): Char ``` Returns the single character matching the given [predicate](../single#kotlin.text%24single(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate), or throws exception if there is no or more than one matching character. ``` fun CharSequence.single(predicate: (Char) -> Boolean): Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [singleOrNull](../single-or-null) Returns single character, or `null` if the char sequence is empty or has more than one character. ``` fun CharSequence.singleOrNull(): Char? ``` Returns the single character matching the given [predicate](../single-or-null#kotlin.text%24singleOrNull(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate), or `null` if character was not found or more than one character was found. ``` fun CharSequence.singleOrNull(     predicate: (Char) -> Boolean ): Char? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [slice](../slice) Returns a char sequence containing characters of the original char sequence at the specified range of [indices](../slice#kotlin.text%24slice(kotlin.CharSequence,%20kotlin.ranges.IntRange)/indices). ``` fun CharSequence.slice(indices: IntRange): CharSequence ``` Returns a char sequence containing characters of the original char sequence at specified [indices](../slice#kotlin.text%24slice(kotlin.CharSequence,%20kotlin.collections.Iterable((kotlin.Int)))/indices). ``` fun CharSequence.slice(indices: Iterable<Int>): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [split](../split) Splits this char sequence to a list of strings around occurrences of the specified [delimiters](../split#kotlin.text%24split(kotlin.CharSequence,%20kotlin.Array((kotlin.String)),%20kotlin.Boolean,%20kotlin.Int)/delimiters). ``` fun CharSequence.split(     vararg delimiters: String,     ignoreCase: Boolean = false,     limit: Int = 0 ): List<String> ``` ``` fun CharSequence.split(     vararg delimiters: Char,     ignoreCase: Boolean = false,     limit: Int = 0 ): List<String> ``` Splits this char sequence to a list of strings around matches of the given regular expression. ``` fun CharSequence.split(     regex: Regex,     limit: Int = 0 ): List<String> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [splitToSequence](../split-to-sequence) Splits this char sequence to a sequence of strings around occurrences of the specified [delimiters](../split-to-sequence#kotlin.text%24splitToSequence(kotlin.CharSequence,%20kotlin.Array((kotlin.String)),%20kotlin.Boolean,%20kotlin.Int)/delimiters). ``` fun CharSequence.splitToSequence(     vararg delimiters: String,     ignoreCase: Boolean = false,     limit: Int = 0 ): Sequence<String> ``` ``` fun CharSequence.splitToSequence(     vararg delimiters: Char,     ignoreCase: Boolean = false,     limit: Int = 0 ): Sequence<String> ``` Splits this char sequence to a sequence of strings around matches of the given regular expression. ``` fun CharSequence.splitToSequence(     regex: Regex,     limit: Int = 0 ): Sequence<String> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [startsWith](../starts-with) Returns `true` if this char sequence starts with the specified character. ``` fun CharSequence.startsWith(     char: Char,     ignoreCase: Boolean = false ): Boolean ``` Returns `true` if this char sequence starts with the specified prefix. ``` fun CharSequence.startsWith(     prefix: CharSequence,     ignoreCase: Boolean = false ): Boolean ``` Returns `true` if a substring of this char sequence starting at the specified offset [startIndex](../starts-with#kotlin.text%24startsWith(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Boolean)/startIndex) starts with the specified prefix. ``` fun CharSequence.startsWith(     prefix: CharSequence,     startIndex: Int,     ignoreCase: Boolean = false ): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [subSequence](../sub-sequence) Returns a subsequence of this char sequence specified by the given [range](../sub-sequence#kotlin.text%24subSequence(kotlin.CharSequence,%20kotlin.ranges.IntRange)/range) of indices. ``` fun CharSequence.subSequence(range: IntRange): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [substring](../substring) Returns a substring of chars from a range of this char sequence starting at the [startIndex](../substring#kotlin.text%24substring(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/startIndex) and ending right before the [endIndex](../substring#kotlin.text%24substring(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/endIndex). ``` fun CharSequence.substring(     startIndex: Int,     endIndex: Int = length ): String ``` Returns a substring of chars at indices from the specified [range](../substring#kotlin.text%24substring(kotlin.CharSequence,%20kotlin.ranges.IntRange)/range) of this char sequence. ``` fun CharSequence.substring(range: IntRange): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [sumBy](../sum-by) Returns the sum of all values produced by [selector](../sum-by#kotlin.text%24sumBy(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Int)))/selector) function applied to each character in the char sequence. ``` fun CharSequence.sumBy(selector: (Char) -> Int): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [sumByDouble](../sum-by-double) Returns the sum of all values produced by [selector](../sum-by-double#kotlin.text%24sumByDouble(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Double)))/selector) function applied to each character in the char sequence. ``` fun CharSequence.sumByDouble(     selector: (Char) -> Double ): Double ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [sumOf](../sum-of) Returns the sum of all values produced by [selector](../sum-of#kotlin.text%24sumOf(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Double)))/selector) function applied to each character in the char sequence. ``` fun CharSequence.sumOf(selector: (Char) -> Double): Double ``` ``` fun CharSequence.sumOf(selector: (Char) -> Int): Int ``` ``` fun CharSequence.sumOf(selector: (Char) -> Long): Long ``` ``` fun CharSequence.sumOf(selector: (Char) -> UInt): UInt ``` ``` fun CharSequence.sumOf(selector: (Char) -> ULong): ULong ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [take](../take) Returns a subsequence of this char sequence containing the first [n](../take#kotlin.text%24take(kotlin.CharSequence,%20kotlin.Int)/n) characters from this char sequence, or the entire char sequence if this char sequence is shorter. ``` fun CharSequence.take(n: Int): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [takeLast](../take-last) Returns a subsequence of this char sequence containing the last [n](../take-last#kotlin.text%24takeLast(kotlin.CharSequence,%20kotlin.Int)/n) characters from this char sequence, or the entire char sequence if this char sequence is shorter. ``` fun CharSequence.takeLast(n: Int): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [takeLastWhile](../take-last-while) Returns a subsequence of this char sequence containing last characters that satisfy the given [predicate](../take-last-while#kotlin.text%24takeLastWhile(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` fun CharSequence.takeLastWhile(     predicate: (Char) -> Boolean ): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [takeWhile](../take-while) Returns a subsequence of this char sequence containing the first characters that satisfy the given [predicate](../take-while#kotlin.text%24takeWhile(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate). ``` fun CharSequence.takeWhile(     predicate: (Char) -> Boolean ): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toCollection](../to-collection) Appends all characters to the given [destination](../to-collection#kotlin.text%24toCollection(kotlin.CharSequence,%20kotlin.text.toCollection.C)/destination) collection. ``` fun <C : MutableCollection<in Char>> CharSequence.toCollection(     destination: C ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toHashSet](../to-hash-set) Returns a new [HashSet](../../kotlin.collections/-hash-set/index#kotlin.collections.HashSet) of all characters. ``` fun CharSequence.toHashSet(): HashSet<Char> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toList](../to-list) Returns a [List](../../kotlin.collections/-list/index#kotlin.collections.List) containing all characters. ``` fun CharSequence.toList(): List<Char> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toMutableList](../to-mutable-list) Returns a new [MutableList](../../kotlin.collections/-mutable-list/index#kotlin.collections.MutableList) filled with all characters of this char sequence. ``` fun CharSequence.toMutableList(): MutableList<Char> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toSet](../to-set) Returns a [Set](../../kotlin.collections/-set/index#kotlin.collections.Set) of all characters. ``` fun CharSequence.toSet(): Set<Char> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [trim](../trim) Returns a sub sequence of this char sequence having leading and trailing characters matching the [predicate](../trim#kotlin.text%24trim(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate) removed. ``` fun CharSequence.trim(     predicate: (Char) -> Boolean ): CharSequence ``` Returns a sub sequence of this char sequence having leading and trailing characters from the [chars](../trim#kotlin.text%24trim(kotlin.CharSequence,%20kotlin.CharArray)/chars) array removed. ``` fun CharSequence.trim(vararg chars: Char): CharSequence ``` Returns a sub sequence of this char sequence having leading and trailing whitespace removed. ``` fun CharSequence.trim(): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [trimEnd](../trim-end) Returns a sub sequence of this char sequence having trailing characters matching the [predicate](../trim-end#kotlin.text%24trimEnd(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate) removed. ``` fun CharSequence.trimEnd(     predicate: (Char) -> Boolean ): CharSequence ``` Returns a sub sequence of this char sequence having trailing characters from the [chars](../trim-end#kotlin.text%24trimEnd(kotlin.CharSequence,%20kotlin.CharArray)/chars) array removed. ``` fun CharSequence.trimEnd(vararg chars: Char): CharSequence ``` Returns a sub sequence of this char sequence having trailing whitespace removed. ``` fun CharSequence.trimEnd(): CharSequence ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [trimStart](../trim-start) Returns a sub sequence of this char sequence having leading characters matching the [predicate](../trim-start#kotlin.text%24trimStart(kotlin.CharSequence,%20kotlin.Function1((kotlin.Char,%20kotlin.Boolean)))/predicate) removed. ``` fun CharSequence.trimStart(     predicate: (Char) -> Boolean ): CharSequence ``` Returns a sub sequence of this char sequence having leading characters from the [chars](../trim-start#kotlin.text%24trimStart(kotlin.CharSequence,%20kotlin.CharArray)/chars) array removed. ``` fun CharSequence.trimStart(vararg chars: Char): CharSequence ``` Returns a sub sequence of this char sequence having leading whitespace removed. ``` fun CharSequence.trimStart(): CharSequence ``` **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) #### [windowed](../windowed) Returns a list of snapshots of the window of the given [size](../windowed#kotlin.text%24windowed(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/size) sliding along this char sequence with the given [step](../windowed#kotlin.text%24windowed(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/step), where each snapshot is a string. ``` fun CharSequence.windowed(     size: Int,     step: Int = 1,     partialWindows: Boolean = false ): List<String> ``` Returns a list of results of applying the given [transform](../windowed#kotlin.text%24windowed(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.windowed.R)))/transform) function to an each char sequence representing a view over the window of the given [size](../windowed#kotlin.text%24windowed(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.windowed.R)))/size) sliding along this char sequence with the given [step](../windowed#kotlin.text%24windowed(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.windowed.R)))/step). ``` fun <R> CharSequence.windowed(     size: Int,     step: Int = 1,     partialWindows: Boolean = false,     transform: (CharSequence) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) #### [windowedSequence](../windowed-sequence) Returns a sequence of snapshots of the window of the given [size](../windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/size) sliding along this char sequence with the given [step](../windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/step), where each snapshot is a string. ``` fun CharSequence.windowedSequence(     size: Int,     step: Int = 1,     partialWindows: Boolean = false ): Sequence<String> ``` Returns a sequence of results of applying the given [transform](../windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.windowedSequence.R)))/transform) function to an each char sequence representing a view over the window of the given [size](../windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.windowedSequence.R)))/size) sliding along this char sequence with the given [step](../windowed-sequence#kotlin.text%24windowedSequence(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.CharSequence,%20kotlin.text.windowedSequence.R)))/step). ``` fun <R> CharSequence.windowedSequence(     size: Int,     step: Int = 1,     partialWindows: Boolean = false,     transform: (CharSequence) -> R ): Sequence<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [withIndex](../with-index) Returns a lazy [Iterable](../../kotlin.collections/-iterable/index#kotlin.collections.Iterable) that wraps each character of the original char sequence into an [IndexedValue](../../kotlin.collections/-indexed-value/index) containing the index of that character and the character itself. ``` fun CharSequence.withIndex(): Iterable<IndexedValue<Char>> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [zip](../zip) Returns a list of pairs built from the characters of `this` and the [other](../zip#kotlin.text%24zip(kotlin.CharSequence,%20kotlin.CharSequence)/other) char sequences with the same index The returned list has length of the shortest char sequence. ``` infix fun CharSequence.zip(     other: CharSequence ): List<Pair<Char, Char>> ``` Returns a list of values built from the characters of `this` and the [other](../zip#kotlin.text%24zip(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Function2((kotlin.Char,%20,%20kotlin.text.zip.V)))/other) char sequences with the same index using the provided [transform](../zip#kotlin.text%24zip(kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Function2((kotlin.Char,%20,%20kotlin.text.zip.V)))/transform) function applied to each pair of characters. The returned list has length of the shortest char sequence. ``` fun <V> CharSequence.zip(     other: CharSequence,     transform: (a: Char, b: Char) -> V ): List<V> ``` **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) #### [zipWithNext](../zip-with-next) Returns a list of pairs of each two adjacent characters in this char sequence. ``` fun CharSequence.zipWithNext(): List<Pair<Char, Char>> ``` Returns a list containing the results of applying the given [transform](../zip-with-next#kotlin.text%24zipWithNext(kotlin.CharSequence,%20kotlin.Function2((kotlin.Char,%20,%20kotlin.text.zipWithNext.R)))/transform) function to an each pair of two adjacent characters in this char sequence. ``` fun <R> CharSequence.zipWithNext(     transform: (a: Char, b: Char) -> R ): List<R> ```
programming_docs
kotlin trimToSize trimToSize ========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [trimToSize](trim-to-size) **Platform and version requirements:** JS (1.4) ``` fun trimToSize() ``` ##### For Common Attempts to reduce storage used for this string builder. If the backing storage of this string builder is larger than necessary to hold its current contents, then it may be resized to become more space efficient. Calling this method may, but is not required to, affect the value of the [capacity](capacity#kotlin.text.StringBuilder%24capacity()) property. ##### For JS Attempts to reduce storage used for this string builder. If the backing storage of this string builder is larger than necessary to hold its current contents, then it may be resized to become more space efficient. Calling this method may, but is not required to, affect the value of the [capacity](capacity#kotlin.text.StringBuilder%24capacity()) property. In Kotlin/JS implementation of StringBuilder the size of the backing storage is always equal to the length of the string builder. kotlin insertRange insertRange =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [insertRange](insert-range) **Platform and version requirements:** JS (1.4) ``` fun insertRange(     index: Int,     value: CharArray,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Inserts characters in a subarray of the specified character array [value](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) into this string builder at the specified [index](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/index) and returns this instance. The inserted characters go in same order as in the [value](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) array, starting at [index](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/index). Parameters ---------- `index` - the position in this string builder to insert at. `value` - the array from which characters are inserted. `startIndex` - the beginning (inclusive) of the subarray to insert. `endIndex` - the end (exclusive) of the subarray to insert. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/endIndex) is out of range of the [value](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) array indices or when `startIndex > endIndex`. `IndexOutOfBoundsException` - if [index](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/index) is less than zero or greater than the length of this string builder. **Platform and version requirements:** JS (1.4) ``` fun insertRange(     index: Int,     value: CharSequence,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Inserts characters in a subsequence of the specified character sequence [value](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) into this string builder at the specified [index](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/index) and returns this instance. The inserted characters go in the same order as in the [value](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) character sequence, starting at [index](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/index). Parameters ---------- `index` - the position in this string builder to insert at. `value` - the character sequence from which a subsequence is inserted. `startIndex` - the beginning (inclusive) of the subsequence to insert. `endIndex` - the end (exclusive) of the subsequence to insert. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/endIndex) is out of range of the [value](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) character sequence indices or when `startIndex > endIndex`. `IndexOutOfBoundsException` - if [index](insert-range#kotlin.text.StringBuilder%24insertRange(kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/index) is less than zero or greater than the length of this string builder. kotlin reverse reverse ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / <reverse> **Platform and version requirements:** JS (1.1) ``` fun reverse(): StringBuilder ``` Reverses the contents of this string builder and returns this instance. Surrogate pairs included in this string builder are treated as single characters. Therefore, the order of the high-low surrogates is never reversed. Note that the reverse operation may produce new surrogate pairs that were unpaired low-surrogates and high-surrogates before the operation. For example, reversing `"\uDC00\uD800"` produces `"\uD800\uDC00"` which is a valid surrogate pair. kotlin append append ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / <append> **Platform and version requirements:** JS (1.0) ``` fun append(value: Char): StringBuilder ``` Appends the specified character [value](../-appendable/append#kotlin.text.Appendable%24append(kotlin.Char)/value) to this Appendable and returns this instance. Parameters ---------- `value` - the character to append. **Platform and version requirements:** JS (1.0) ``` fun append(value: CharSequence?): StringBuilder ``` Appends the specified character sequence [value](../-appendable/append#kotlin.text.Appendable%24append(kotlin.CharSequence?)/value) to this Appendable and returns this instance. Parameters ---------- `value` - the character sequence to append. If [value](../-appendable/append#kotlin.text.Appendable%24append(kotlin.CharSequence?)/value) is `null`, then the four characters `"null"` are appended to this Appendable. **Platform and version requirements:** JS (1.0) ``` fun append(     value: CharSequence?,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Appends a subsequence of the specified character sequence [value](../-appendable/append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/value) to this Appendable and returns this instance. Parameters ---------- `value` - the character sequence from which a subsequence is appended. If [value](../-appendable/append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/value) is `null`, then characters are appended as if [value](../-appendable/append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/value) contained the four characters `"null"`. `startIndex` - the beginning (inclusive) of the subsequence to append. `endIndex` - the end (exclusive) of the subsequence to append. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](../-appendable/append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](../-appendable/append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/endIndex) is out of range of the [value](../-appendable/append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/value) character sequence indices or when `startIndex > endIndex`. **Platform and version requirements:** JS (1.0) ``` fun append(value: Any?): StringBuilder ``` Appends the string representation of the specified object [value](append#kotlin.text.StringBuilder%24append(kotlin.Any?)/value) to this string builder and returns this instance. The overall effect is exactly as if the [value](append#kotlin.text.StringBuilder%24append(kotlin.Any?)/value) were converted to a string by the `value.toString()` method, and then that string was appended to this string builder. **Platform and version requirements:** JS (1.3) ``` fun append(value: Boolean): StringBuilder ``` Appends the string representation of the specified boolean [value](append#kotlin.text.StringBuilder%24append(kotlin.Boolean)/value) to this string builder and returns this instance. The overall effect is exactly as if the [value](append#kotlin.text.StringBuilder%24append(kotlin.Boolean)/value) were converted to a string by the `value.toString()` method, and then that string was appended to this string builder. **Platform and version requirements:** JS (1.4) ``` fun append(value: CharArray): StringBuilder ``` Appends characters in the specified character array [value](append#kotlin.text.StringBuilder%24append(kotlin.CharArray)/value) to this string builder and returns this instance. Characters are appended in order, starting at the index 0. **Platform and version requirements:** JS (1.3) ``` fun append(value: String?): StringBuilder ``` Appends the specified string [value](append#kotlin.text.StringBuilder%24append(kotlin.String?)/value) to this string builder and returns this instance. If [value](append#kotlin.text.StringBuilder%24append(kotlin.String?)/value) is `null`, then the four characters `"null"` are appended. kotlin lastIndexOf lastIndexOf =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [lastIndexOf](last-index-of) **Platform and version requirements:** JS (1.4) ``` fun lastIndexOf(string: String): Int ``` Returns the index within this string builder of the last occurrence of the specified [string](last-index-of#kotlin.text.StringBuilder%24lastIndexOf(kotlin.String)/string). The last occurrence of empty string `""` is considered to be at the index equal to `this.length`. Returns `-1` if the specified [string](last-index-of#kotlin.text.StringBuilder%24lastIndexOf(kotlin.String)/string) does not occur in this string builder. **Platform and version requirements:** JS (1.4) ``` fun lastIndexOf(string: String, startIndex: Int): Int ``` Returns the index within this string builder of the last occurrence of the specified [string](last-index-of#kotlin.text.StringBuilder%24lastIndexOf(kotlin.String,%20kotlin.Int)/string), starting from the specified [startIndex](last-index-of#kotlin.text.StringBuilder%24lastIndexOf(kotlin.String,%20kotlin.Int)/startIndex) toward the beginning. Returns `-1` if the specified [string](last-index-of#kotlin.text.StringBuilder%24lastIndexOf(kotlin.String,%20kotlin.Int)/string) does not occur in this string builder starting at the specified [startIndex](last-index-of#kotlin.text.StringBuilder%24lastIndexOf(kotlin.String,%20kotlin.Int)/startIndex). kotlin setRange setRange ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [setRange](set-range) **Platform and version requirements:** JS (1.4) ``` fun setRange(     startIndex: Int,     endIndex: Int,     value: String ): StringBuilder ``` Replaces characters in the specified range of this string builder with characters in the specified string [value](set-range#kotlin.text.StringBuilder%24setRange(kotlin.Int,%20kotlin.Int,%20kotlin.String)/value) and returns this instance. Parameters ---------- `startIndex` - the beginning (inclusive) of the range to replace. `endIndex` - the end (exclusive) of the range to replace. `value` - the string to replace with. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) if [startIndex](set-range#kotlin.text.StringBuilder%24setRange(kotlin.Int,%20kotlin.Int,%20kotlin.String)/startIndex) is less than zero, greater than the length of this string builder, or `startIndex > endIndex`. kotlin appendRange appendRange =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [appendRange](append-range) **Platform and version requirements:** JS (1.4) ``` fun appendRange(     value: CharArray,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Appends characters in a subarray of the specified character array [value](append-range#kotlin.text.StringBuilder%24appendRange(kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) to this string builder and returns this instance. Characters are appended in order, starting at specified [startIndex](append-range#kotlin.text.StringBuilder%24appendRange(kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/startIndex). Parameters ---------- `value` - the array from which characters are appended. `startIndex` - the beginning (inclusive) of the subarray to append. `endIndex` - the end (exclusive) of the subarray to append. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](append-range#kotlin.text.StringBuilder%24appendRange(kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](append-range#kotlin.text.StringBuilder%24appendRange(kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/endIndex) is out of range of the [value](append-range#kotlin.text.StringBuilder%24appendRange(kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) array indices or when `startIndex > endIndex`. **Platform and version requirements:** JS (1.4) ``` fun appendRange(     value: CharSequence,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Appends a subsequence of the specified character sequence [value](append-range#kotlin.text.StringBuilder%24appendRange(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) to this string builder and returns this instance. Parameters ---------- `value` - the character sequence from which a subsequence is appended. `startIndex` - the beginning (inclusive) of the subsequence to append. `endIndex` - the end (exclusive) of the subsequence to append. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](append-range#kotlin.text.StringBuilder%24appendRange(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](append-range#kotlin.text.StringBuilder%24appendRange(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/endIndex) is out of range of the [value](append-range#kotlin.text.StringBuilder%24appendRange(kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) character sequence indices or when `startIndex > endIndex`. kotlin length length ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / <length> **Platform and version requirements:** JS (1.1) ``` val length: Int ``` Returns the length of this character sequence. kotlin toString toString ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [toString](to-string) **Platform and version requirements:** JS (1.1) ``` fun toString(): String ``` kotlin capacity capacity ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / <capacity> **Platform and version requirements:** JS (1.3) ``` fun capacity(): Int ``` **Deprecated:** Obtaining StringBuilder capacity is not supported in JS and common code. ##### For Common Returns the current capacity of this string builder. The capacity is the maximum length this string builder can have before an allocation occurs. ##### For JS Returns the current capacity of this string builder. The capacity is the maximum length this string builder can have before an allocation occurs. In Kotlin/JS implementation of StringBuilder the value returned from this method may not indicate the actual size of the backing storage. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [<init>](-init-) **Platform and version requirements:** JS (1.0) ``` <init>() ``` Constructs an empty string builder. **Platform and version requirements:** JS (1.0) ``` <init>(capacity: Int) ``` ##### For Common Constructs an empty string builder with the specified initial capacity. ##### For JS Constructs an empty string builder with the specified initial capacity. In Kotlin/JS implementation of StringBuilder the initial capacity has no effect on the further performance of operations. **Platform and version requirements:** JS (1.0) ``` <init>(content: CharSequence) ``` Constructs a string builder that contains the same characters as the specified content char sequence. **Platform and version requirements:** JS (1.0) ``` <init>(content: String) ``` ##### For Common Constructs a string builder that contains the same characters as the specified content string. ##### For JS A mutable sequence of characters. String builder can be used to efficiently perform multiple string manipulation operations. kotlin deleteRange deleteRange =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [deleteRange](delete-range) **Platform and version requirements:** JS (1.4) ``` fun deleteRange(     startIndex: Int,     endIndex: Int ): StringBuilder ``` Removes characters in the specified range from this string builder and returns this instance. Parameters ---------- `startIndex` - the beginning (inclusive) of the range to remove. `endIndex` - the end (exclusive) of the range to remove. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](delete-range#kotlin.text.StringBuilder%24deleteRange(kotlin.Int,%20kotlin.Int)/startIndex) is out of range of this string builder indices or when `startIndex > endIndex`. kotlin subSequence subSequence =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [subSequence](sub-sequence) **Platform and version requirements:** JS (1.1) ``` fun subSequence(startIndex: Int, endIndex: Int): CharSequence ``` Returns a new character sequence that is a subsequence of this character sequence, starting at the specified [startIndex](../../kotlin/-char-sequence/sub-sequence#kotlin.CharSequence%24subSequence(kotlin.Int,%20kotlin.Int)/startIndex) and ending right before the specified [endIndex](../../kotlin/-char-sequence/sub-sequence#kotlin.CharSequence%24subSequence(kotlin.Int,%20kotlin.Int)/endIndex). Parameters ---------- `startIndex` - the start index (inclusive). `endIndex` - the end index (exclusive).
programming_docs
kotlin clear clear ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / <clear> **Platform and version requirements:** JS (1.3) ``` fun clear(): StringBuilder ``` Clears the content of this string builder making it empty and returns this instance. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val builder = StringBuilder() builder.append("content").append(1) println(builder) // content1 builder.clear() println(builder) // //sampleEnd } ``` kotlin deleteAt deleteAt ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [deleteAt](delete-at) **Platform and version requirements:** JS (1.4) ``` fun deleteAt(index: Int): StringBuilder ``` Removes the character at the specified [index](delete-at#kotlin.text.StringBuilder%24deleteAt(kotlin.Int)/index) from this string builder and returns this instance. If the `Char` at the specified [index](delete-at#kotlin.text.StringBuilder%24deleteAt(kotlin.Int)/index) is part of a supplementary code point, this method does not remove the entire supplementary character. Parameters ---------- `index` - the index of `Char` to remove. Exceptions ---------- `IndexOutOfBoundsException` - if [index](delete-at#kotlin.text.StringBuilder%24deleteAt(kotlin.Int)/index) is out of bounds of this string builder. kotlin indexOf indexOf ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [indexOf](index-of) **Platform and version requirements:** JS (1.4) ``` fun indexOf(string: String): Int ``` Returns the index within this string builder of the first occurrence of the specified [string](index-of#kotlin.text.StringBuilder%24indexOf(kotlin.String)/string). Returns `-1` if the specified [string](index-of#kotlin.text.StringBuilder%24indexOf(kotlin.String)/string) does not occur in this string builder. **Platform and version requirements:** JS (1.4) ``` fun indexOf(string: String, startIndex: Int): Int ``` Returns the index within this string builder of the first occurrence of the specified [string](index-of#kotlin.text.StringBuilder%24indexOf(kotlin.String,%20kotlin.Int)/string), starting at the specified [startIndex](index-of#kotlin.text.StringBuilder%24indexOf(kotlin.String,%20kotlin.Int)/startIndex). Returns `-1` if the specified [string](index-of#kotlin.text.StringBuilder%24indexOf(kotlin.String,%20kotlin.Int)/string) does not occur in this string builder starting at the specified [startIndex](index-of#kotlin.text.StringBuilder%24indexOf(kotlin.String,%20kotlin.Int)/startIndex). kotlin toCharArray toCharArray =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [toCharArray](to-char-array) **Platform and version requirements:** JS (1.4) ``` fun toCharArray(     destination: CharArray,     destinationOffset: Int = 0,     startIndex: Int = 0,     endIndex: Int = this.length) ``` Copies characters from this string builder into the [destination](to-char-array#kotlin.text.StringBuilder%24toCharArray(kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destination) character array. Parameters ---------- `destination` - the array to copy to. `destinationOffset` - the position in the array to copy to, 0 by default. `startIndex` - the beginning (inclusive) of the range to copy, 0 by default. `endIndex` - the end (exclusive) of the range to copy, length of this string builder by default. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](to-char-array#kotlin.text.StringBuilder%24toCharArray(kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](to-char-array#kotlin.text.StringBuilder%24toCharArray(kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/endIndex) is out of range of this string builder indices or when `startIndex > endIndex`. `IndexOutOfBoundsException` - when the subrange doesn't fit into the [destination](to-char-array#kotlin.text.StringBuilder%24toCharArray(kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destination) array starting at the specified [destinationOffset](to-char-array#kotlin.text.StringBuilder%24toCharArray(kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destinationOffset), or when that index is out of the [destination](to-char-array#kotlin.text.StringBuilder%24toCharArray(kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destination) array indices range. kotlin set set === [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / <set> **Platform and version requirements:** JS (1.4) ``` operator fun set(index: Int, value: Char) ``` Sets the character at the specified [index](set#kotlin.text.StringBuilder%24set(kotlin.Int,%20kotlin.Char)/index) to the specified [value](set#kotlin.text.StringBuilder%24set(kotlin.Int,%20kotlin.Char)/value). Exceptions ---------- `IndexOutOfBoundsException` - if [index](set#kotlin.text.StringBuilder%24set(kotlin.Int,%20kotlin.Char)/index) is out of bounds of this string builder. kotlin ensureCapacity ensureCapacity ============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [ensureCapacity](ensure-capacity) **Platform and version requirements:** JS (1.4) ``` fun ensureCapacity(minimumCapacity: Int) ``` ##### For Common Ensures that the capacity of this string builder is at least equal to the specified [minimumCapacity](ensure-capacity#kotlin.text.StringBuilder%24ensureCapacity(kotlin.Int)/minimumCapacity). If the current capacity is less than the [minimumCapacity](ensure-capacity#kotlin.text.StringBuilder%24ensureCapacity(kotlin.Int)/minimumCapacity), a new backing storage is allocated with greater capacity. Otherwise, this method takes no action and simply returns. ##### For JS Ensures that the capacity of this string builder is at least equal to the specified [minimumCapacity](ensure-capacity#kotlin.text.StringBuilder%24ensureCapacity(kotlin.Int)/minimumCapacity). If the current capacity is less than the [minimumCapacity](ensure-capacity#kotlin.text.StringBuilder%24ensureCapacity(kotlin.Int)/minimumCapacity), a new backing storage is allocated with greater capacity. Otherwise, this method takes no action and simply returns. In Kotlin/JS implementation of StringBuilder the size of the backing storage is not extended to comply the given [minimumCapacity](ensure-capacity#kotlin.text.StringBuilder%24ensureCapacity(kotlin.Int)/minimumCapacity), thus calling this method has no effect on the further performance of operations. kotlin setLength setLength ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / [setLength](set-length) **Platform and version requirements:** JS (1.4) ``` fun setLength(newLength: Int) ``` Sets the length of this string builder to the specified [newLength](set-length#kotlin.text.StringBuilder%24setLength(kotlin.Int)/newLength). If the [newLength](set-length#kotlin.text.StringBuilder%24setLength(kotlin.Int)/newLength) is less than the current length, it is changed to the specified [newLength](set-length#kotlin.text.StringBuilder%24setLength(kotlin.Int)/newLength). Otherwise, null characters '\u0000' are appended to this string builder until its length is less than the [newLength](set-length#kotlin.text.StringBuilder%24setLength(kotlin.Int)/newLength). Note that in Kotlin/JS [set](../set#kotlin.text%24set(kotlin.text.StringBuilder,%20kotlin.Int,%20kotlin.Char)) operator function has non-constant execution time complexity. Therefore, increasing length of this string builder and then updating each character by index may slow down your program. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) if [newLength](set-length#kotlin.text.StringBuilder%24setLength(kotlin.Int)/newLength) is less than zero. kotlin get get === [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / <get> **Platform and version requirements:** ``` operator fun get(index: Int): Char ``` **Platform and version requirements:** JS (1.1) ``` fun get(index: Int): Char ``` Returns the character at the specified [index](../../kotlin/-char-sequence/get#kotlin.CharSequence%24get(kotlin.Int)/index) in this character sequence. Exceptions ---------- `IndexOutOfBoundsException` - if the [index](../../kotlin/-char-sequence/get#kotlin.CharSequence%24get(kotlin.Int)/index) is out of bounds of this character sequence. Note that the String implementation of this interface in Kotlin/JS has unspecified behavior if the [index](../../kotlin/-char-sequence/get#kotlin.CharSequence%24get(kotlin.Int)/index) is out of its bounds. kotlin substring substring ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [StringBuilder](index) / <substring> **Platform and version requirements:** JS (1.4) ``` fun substring(startIndex: Int): String ``` Returns a new [String](../../kotlin/-string/index#kotlin.String) that contains characters in this string builder at [startIndex](substring#kotlin.text.StringBuilder%24substring(kotlin.Int)/startIndex) (inclusive) and up to the [length](length#kotlin.text.StringBuilder%24length) (exclusive). Exceptions ---------- `IndexOutOfBoundsException` - if [startIndex](substring#kotlin.text.StringBuilder%24substring(kotlin.Int)/startIndex) is less than zero or greater than the length of this string builder. **Platform and version requirements:** JS (1.4) ``` fun substring(startIndex: Int, endIndex: Int): String ``` Returns a new [String](../../kotlin/-string/index#kotlin.String) that contains characters in this string builder at [startIndex](substring#kotlin.text.StringBuilder%24substring(kotlin.Int,%20kotlin.Int)/startIndex) (inclusive) and up to the [endIndex](substring#kotlin.text.StringBuilder%24substring(kotlin.Int,%20kotlin.Int)/endIndex) (exclusive). Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](substring#kotlin.text.StringBuilder%24substring(kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](substring#kotlin.text.StringBuilder%24substring(kotlin.Int,%20kotlin.Int)/endIndex) is out of range of this string builder indices or when `startIndex > endIndex`. kotlin RegexOption RegexOption =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [RegexOption](index) **Platform and version requirements:** JS (1.1) ``` enum class RegexOption ``` **Platform and version requirements:** JVM (1.0) ``` enum class RegexOption : FlagEnum ``` Provides enumeration values to use to set regular expression options. Enum Values ----------- **Platform and version requirements:** JVM (1.0) #### [LITERAL](-l-i-t-e-r-a-l) Enables literal parsing of the pattern. **Platform and version requirements:** JVM (1.0) #### [UNIX\_LINES](-u-n-i-x_-l-i-n-e-s) Enables Unix lines mode. In this mode, only the `'\n'` is recognized as a line terminator. **Platform and version requirements:** JVM (1.0) #### [COMMENTS](-c-o-m-m-e-n-t-s) Permits whitespace and comments in pattern. **Platform and version requirements:** JVM (1.0) #### [DOT\_MATCHES\_ALL](-d-o-t_-m-a-t-c-h-e-s_-a-l-l) Enables the mode, when the expression `.` matches any character, including a line terminator. **Platform and version requirements:** JVM (1.0) #### [CANON\_EQ](-c-a-n-o-n_-e-q) Enables equivalence by canonical decomposition. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [IGNORE\_CASE](-i-g-n-o-r-e_-c-a-s-e) Enables case-insensitive matching. Case comparison is Unicode-aware. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [MULTILINE](-m-u-l-t-i-l-i-n-e) Enables multiline mode. Properties ---------- **Platform and version requirements:** JVM (1.0) #### <mask> ``` val mask: Int ``` #### <value> **Platform and version requirements:** JVM (1.0) ``` val value: Int ``` **Platform and version requirements:** JS (1.1) ``` val value: String ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.7) #### [declaringJavaClass](../../kotlin.jvm/declaring-java-class) Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance of the enum the given constant belongs to. ``` val <E : Enum<E>> Enum<E>.declaringJavaClass: Class<E> ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceAtLeast](../../kotlin.ranges/coerce-at-least) Ensures that this value is not less than the specified [minimumValue](../../kotlin.ranges/coerce-at-least#kotlin.ranges%24coerceAtLeast(kotlin.ranges.coerceAtLeast.T,%20kotlin.ranges.coerceAtLeast.T)/minimumValue). ``` fun <T : Comparable<T>> T.coerceAtLeast(minimumValue: T): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceAtMost](../../kotlin.ranges/coerce-at-most) Ensures that this value is not greater than the specified [maximumValue](../../kotlin.ranges/coerce-at-most#kotlin.ranges%24coerceAtMost(kotlin.ranges.coerceAtMost.T,%20kotlin.ranges.coerceAtMost.T)/maximumValue). ``` fun <T : Comparable<T>> T.coerceAtMost(maximumValue: T): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceIn](../../kotlin.ranges/coerce-in) Ensures that this value lies in the specified range [minimumValue](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.coerceIn.T?,%20kotlin.ranges.coerceIn.T?)/minimumValue)..[maximumValue](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.coerceIn.T?,%20kotlin.ranges.coerceIn.T?)/maximumValue). ``` fun <T : Comparable<T>> T.coerceIn(     minimumValue: T?,     maximumValue: T? ): T ``` Ensures that this value lies in the specified [range](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.ClosedFloatingPointRange((kotlin.ranges.coerceIn.T)))/range). ``` fun <T : Comparable<T>> T.coerceIn(     range: ClosedFloatingPointRange<T> ): T ``` ``` fun <T : Comparable<T>> T.coerceIn(range: ClosedRange<T>): T ``` **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) #### [compareTo](../../kotlin/compare-to) Compares this object with the specified object for order. Returns zero if this object is equal to the specified [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other) object, a negative number if it's less than [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other), or a positive number if it's greater than [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other). ``` infix fun <T> Comparable<T>.compareTo(other: T): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [rangeTo](../../kotlin.ranges/range-to) Creates a range from this [Comparable](../../kotlin/-comparable/index#kotlin.Comparable) value to the specified [that](../../kotlin.ranges/range-to#kotlin.ranges%24rangeTo(kotlin.ranges.rangeTo.T,%20kotlin.ranges.rangeTo.T)/that) value. ``` operator fun <T : Comparable<T>> T.rangeTo(     that: T ): ClosedRange<T> ``` **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) #### [rangeUntil](../../kotlin.ranges/range-until) Creates an open-ended range from this [Comparable](../../kotlin/-comparable/index#kotlin.Comparable) value to the specified [that](../../kotlin.ranges/range-until#kotlin.ranges%24rangeUntil(kotlin.ranges.rangeUntil.T,%20kotlin.ranges.rangeUntil.T)/that) value. ``` operator fun <T : Comparable<T>> T.rangeUntil(     that: T ): OpenEndRange<T> ``` Inheritors ---------- **Platform and version requirements:** JVM (1.0), JS (1.0) #### [IGNORE\_CASE](-i-g-n-o-r-e_-c-a-s-e) Enables case-insensitive matching. Case comparison is Unicode-aware. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [MULTILINE](-m-u-l-t-i-l-i-n-e) Enables multiline mode. kotlin UNIX_LINES UNIX\_LINES =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [RegexOption](index) / [UNIX\_LINES](-u-n-i-x_-l-i-n-e-s) **Platform and version requirements:** JVM (1.0) ``` UNIX_LINES ``` Enables Unix lines mode. In this mode, only the `'\n'` is recognized as a line terminator. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <mask> ``` val mask: Int ``` kotlin mask mask ==== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [RegexOption](index) / <mask> **Platform and version requirements:** JVM (1.0) ``` val mask: Int ``` kotlin IGNORE_CASE IGNORE\_CASE ============ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [RegexOption](index) / [IGNORE\_CASE](-i-g-n-o-r-e_-c-a-s-e) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` IGNORE_CASE ``` ##### For JVM Enables case-insensitive matching. Case comparison is Unicode-aware. ##### For JS Enables case-insensitive matching. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <mask> ``` val mask: Int ``` kotlin COMMENTS COMMENTS ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [RegexOption](index) / [COMMENTS](-c-o-m-m-e-n-t-s) **Platform and version requirements:** JVM (1.0) ``` COMMENTS ``` Permits whitespace and comments in pattern. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <mask> ``` val mask: Int ``` kotlin LITERAL LITERAL ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [RegexOption](index) / [LITERAL](-l-i-t-e-r-a-l) **Platform and version requirements:** JVM (1.0) ``` LITERAL ``` Enables literal parsing of the pattern. Metacharacters or escape sequences in the input sequence will be given no special meaning. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <mask> ``` val mask: Int ``` kotlin DOT_MATCHES_ALL DOT\_MATCHES\_ALL ================= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [RegexOption](index) / [DOT\_MATCHES\_ALL](-d-o-t_-m-a-t-c-h-e-s_-a-l-l) **Platform and version requirements:** JVM (1.0) ``` DOT_MATCHES_ALL ``` Enables the mode, when the expression `.` matches any character, including a line terminator. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <mask> ``` val mask: Int ``` kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [RegexOption](index) / <value> **Platform and version requirements:** JVM (1.0) ``` val value: Int ``` **Platform and version requirements:** JS (1.1) ``` val value: String ``` kotlin MULTILINE MULTILINE ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [RegexOption](index) / [MULTILINE](-m-u-l-t-i-l-i-n-e) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` MULTILINE ``` Enables multiline mode. In multiline mode the expressions `^` and `$` match just after or just before, respectively, a line terminator or the end of the input sequence. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <mask> ``` val mask: Int ```
programming_docs
kotlin CANON_EQ CANON\_EQ ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [RegexOption](index) / [CANON\_EQ](-c-a-n-o-n_-e-q) **Platform and version requirements:** JVM (1.0) ``` CANON_EQ ``` Enables equivalence by canonical decomposition. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <mask> ``` val mask: Int ``` kotlin PARAGRAPH_SEPARATOR PARAGRAPH\_SEPARATOR ==================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [PARAGRAPH\_SEPARATOR](-p-a-r-a-g-r-a-p-h_-s-e-p-a-r-a-t-o-r) **Platform and version requirements:** JVM (1.0) ``` PARAGRAPH_SEPARATOR ``` Neutral bidirectional character type "B" in the Unicode specification. kotlin CharDirectionality CharDirectionality ================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) **Platform and version requirements:** JVM (1.0) ``` enum class CharDirectionality ``` Represents the Unicode directionality of a character. Character directionality is used to calculate the visual ordering of text. Enum Values ----------- **Platform and version requirements:** JVM (1.0) #### [UNDEFINED](-u-n-d-e-f-i-n-e-d) Undefined bidirectional character type. Undefined `char` values have undefined directionality in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [LEFT\_TO\_RIGHT](-l-e-f-t_-t-o_-r-i-g-h-t) Strong bidirectional character type "L" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [RIGHT\_TO\_LEFT](-r-i-g-h-t_-t-o_-l-e-f-t) Strong bidirectional character type "R" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [RIGHT\_TO\_LEFT\_ARABIC](-r-i-g-h-t_-t-o_-l-e-f-t_-a-r-a-b-i-c) Strong bidirectional character type "AL" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [EUROPEAN\_NUMBER](-e-u-r-o-p-e-a-n_-n-u-m-b-e-r) Weak bidirectional character type "EN" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [EUROPEAN\_NUMBER\_SEPARATOR](-e-u-r-o-p-e-a-n_-n-u-m-b-e-r_-s-e-p-a-r-a-t-o-r) Weak bidirectional character type "ES" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [EUROPEAN\_NUMBER\_TERMINATOR](-e-u-r-o-p-e-a-n_-n-u-m-b-e-r_-t-e-r-m-i-n-a-t-o-r) Weak bidirectional character type "ET" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [ARABIC\_NUMBER](-a-r-a-b-i-c_-n-u-m-b-e-r) Weak bidirectional character type "AN" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [COMMON\_NUMBER\_SEPARATOR](-c-o-m-m-o-n_-n-u-m-b-e-r_-s-e-p-a-r-a-t-o-r) Weak bidirectional character type "CS" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [NONSPACING\_MARK](-n-o-n-s-p-a-c-i-n-g_-m-a-r-k) Weak bidirectional character type "NSM" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [BOUNDARY\_NEUTRAL](-b-o-u-n-d-a-r-y_-n-e-u-t-r-a-l) Weak bidirectional character type "BN" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [PARAGRAPH\_SEPARATOR](-p-a-r-a-g-r-a-p-h_-s-e-p-a-r-a-t-o-r) Neutral bidirectional character type "B" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [SEGMENT\_SEPARATOR](-s-e-g-m-e-n-t_-s-e-p-a-r-a-t-o-r) Neutral bidirectional character type "S" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [WHITESPACE](-w-h-i-t-e-s-p-a-c-e) Neutral bidirectional character type "WS" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [OTHER\_NEUTRALS](-o-t-h-e-r_-n-e-u-t-r-a-l-s) Neutral bidirectional character type "ON" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [LEFT\_TO\_RIGHT\_EMBEDDING](-l-e-f-t_-t-o_-r-i-g-h-t_-e-m-b-e-d-d-i-n-g) Strong bidirectional character type "LRE" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [LEFT\_TO\_RIGHT\_OVERRIDE](-l-e-f-t_-t-o_-r-i-g-h-t_-o-v-e-r-r-i-d-e) Strong bidirectional character type "LRO" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [RIGHT\_TO\_LEFT\_EMBEDDING](-r-i-g-h-t_-t-o_-l-e-f-t_-e-m-b-e-d-d-i-n-g) Strong bidirectional character type "RLE" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [RIGHT\_TO\_LEFT\_OVERRIDE](-r-i-g-h-t_-t-o_-l-e-f-t_-o-v-e-r-r-i-d-e) Strong bidirectional character type "RLO" in the Unicode specification. **Platform and version requirements:** JVM (1.0) #### [POP\_DIRECTIONAL\_FORMAT](-p-o-p_-d-i-r-e-c-t-i-o-n-a-l_-f-o-r-m-a-t) Weak bidirectional character type "PDF" in the Unicode specification. Properties ---------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` Companion Object Functions -------------------------- **Platform and version requirements:** JVM (1.0) #### [valueOf](value-of) ``` fun valueOf(directionality: Int): CharDirectionality ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.7) #### [declaringJavaClass](../../kotlin.jvm/declaring-java-class) Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance of the enum the given constant belongs to. ``` val <E : Enum<E>> Enum<E>.declaringJavaClass: Class<E> ``` kotlin ARABIC_NUMBER ARABIC\_NUMBER ============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [ARABIC\_NUMBER](-a-r-a-b-i-c_-n-u-m-b-e-r) **Platform and version requirements:** JVM (1.0) ``` ARABIC_NUMBER ``` Weak bidirectional character type "AN" in the Unicode specification. kotlin OTHER_NEUTRALS OTHER\_NEUTRALS =============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [OTHER\_NEUTRALS](-o-t-h-e-r_-n-e-u-t-r-a-l-s) **Platform and version requirements:** JVM (1.0) ``` OTHER_NEUTRALS ``` Neutral bidirectional character type "ON" in the Unicode specification. kotlin RIGHT_TO_LEFT_EMBEDDING RIGHT\_TO\_LEFT\_EMBEDDING ========================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [RIGHT\_TO\_LEFT\_EMBEDDING](-r-i-g-h-t_-t-o_-l-e-f-t_-e-m-b-e-d-d-i-n-g) **Platform and version requirements:** JVM (1.0) ``` RIGHT_TO_LEFT_EMBEDDING ``` Strong bidirectional character type "RLE" in the Unicode specification. kotlin BOUNDARY_NEUTRAL BOUNDARY\_NEUTRAL ================= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [BOUNDARY\_NEUTRAL](-b-o-u-n-d-a-r-y_-n-e-u-t-r-a-l) **Platform and version requirements:** JVM (1.0) ``` BOUNDARY_NEUTRAL ``` Weak bidirectional character type "BN" in the Unicode specification. kotlin LEFT_TO_RIGHT_OVERRIDE LEFT\_TO\_RIGHT\_OVERRIDE ========================= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [LEFT\_TO\_RIGHT\_OVERRIDE](-l-e-f-t_-t-o_-r-i-g-h-t_-o-v-e-r-r-i-d-e) **Platform and version requirements:** JVM (1.0) ``` LEFT_TO_RIGHT_OVERRIDE ``` Strong bidirectional character type "LRO" in the Unicode specification. kotlin SEGMENT_SEPARATOR SEGMENT\_SEPARATOR ================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [SEGMENT\_SEPARATOR](-s-e-g-m-e-n-t_-s-e-p-a-r-a-t-o-r) **Platform and version requirements:** JVM (1.0) ``` SEGMENT_SEPARATOR ``` Neutral bidirectional character type "S" in the Unicode specification. kotlin COMMON_NUMBER_SEPARATOR COMMON\_NUMBER\_SEPARATOR ========================= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [COMMON\_NUMBER\_SEPARATOR](-c-o-m-m-o-n_-n-u-m-b-e-r_-s-e-p-a-r-a-t-o-r) **Platform and version requirements:** JVM (1.0) ``` COMMON_NUMBER_SEPARATOR ``` Weak bidirectional character type "CS" in the Unicode specification. kotlin EUROPEAN_NUMBER EUROPEAN\_NUMBER ================ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [EUROPEAN\_NUMBER](-e-u-r-o-p-e-a-n_-n-u-m-b-e-r) **Platform and version requirements:** JVM (1.0) ``` EUROPEAN_NUMBER ``` Weak bidirectional character type "EN" in the Unicode specification. kotlin UNDEFINED UNDEFINED ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [UNDEFINED](-u-n-d-e-f-i-n-e-d) **Platform and version requirements:** JVM (1.0) ``` UNDEFINED ``` Undefined bidirectional character type. Undefined `char` values have undefined directionality in the Unicode specification. kotlin WHITESPACE WHITESPACE ========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [WHITESPACE](-w-h-i-t-e-s-p-a-c-e) **Platform and version requirements:** JVM (1.0) ``` WHITESPACE ``` Neutral bidirectional character type "WS" in the Unicode specification. kotlin RIGHT_TO_LEFT_ARABIC RIGHT\_TO\_LEFT\_ARABIC ======================= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [RIGHT\_TO\_LEFT\_ARABIC](-r-i-g-h-t_-t-o_-l-e-f-t_-a-r-a-b-i-c) **Platform and version requirements:** JVM (1.0) ``` RIGHT_TO_LEFT_ARABIC ``` Strong bidirectional character type "AL" in the Unicode specification. kotlin valueOf valueOf ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [valueOf](value-of) **Platform and version requirements:** JVM (1.0) ``` fun valueOf(directionality: Int): CharDirectionality ``` kotlin EUROPEAN_NUMBER_TERMINATOR EUROPEAN\_NUMBER\_TERMINATOR ============================ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [EUROPEAN\_NUMBER\_TERMINATOR](-e-u-r-o-p-e-a-n_-n-u-m-b-e-r_-t-e-r-m-i-n-a-t-o-r) **Platform and version requirements:** JVM (1.0) ``` EUROPEAN_NUMBER_TERMINATOR ``` Weak bidirectional character type "ET" in the Unicode specification. kotlin LEFT_TO_RIGHT_EMBEDDING LEFT\_TO\_RIGHT\_EMBEDDING ========================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [LEFT\_TO\_RIGHT\_EMBEDDING](-l-e-f-t_-t-o_-r-i-g-h-t_-e-m-b-e-d-d-i-n-g) **Platform and version requirements:** JVM (1.0) ``` LEFT_TO_RIGHT_EMBEDDING ``` Strong bidirectional character type "LRE" in the Unicode specification. kotlin POP_DIRECTIONAL_FORMAT POP\_DIRECTIONAL\_FORMAT ======================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [POP\_DIRECTIONAL\_FORMAT](-p-o-p_-d-i-r-e-c-t-i-o-n-a-l_-f-o-r-m-a-t) **Platform and version requirements:** JVM (1.0) ``` POP_DIRECTIONAL_FORMAT ``` Weak bidirectional character type "PDF" in the Unicode specification. kotlin EUROPEAN_NUMBER_SEPARATOR EUROPEAN\_NUMBER\_SEPARATOR =========================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [EUROPEAN\_NUMBER\_SEPARATOR](-e-u-r-o-p-e-a-n_-n-u-m-b-e-r_-s-e-p-a-r-a-t-o-r) **Platform and version requirements:** JVM (1.0) ``` EUROPEAN_NUMBER_SEPARATOR ``` Weak bidirectional character type "ES" in the Unicode specification. kotlin RIGHT_TO_LEFT_OVERRIDE RIGHT\_TO\_LEFT\_OVERRIDE ========================= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [RIGHT\_TO\_LEFT\_OVERRIDE](-r-i-g-h-t_-t-o_-l-e-f-t_-o-v-e-r-r-i-d-e) **Platform and version requirements:** JVM (1.0) ``` RIGHT_TO_LEFT_OVERRIDE ``` Strong bidirectional character type "RLO" in the Unicode specification. kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / <value> **Platform and version requirements:** JVM (1.0) ``` val value: Int ``` kotlin LEFT_TO_RIGHT LEFT\_TO\_RIGHT =============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [LEFT\_TO\_RIGHT](-l-e-f-t_-t-o_-r-i-g-h-t) **Platform and version requirements:** JVM (1.0) ``` LEFT_TO_RIGHT ``` Strong bidirectional character type "L" in the Unicode specification. kotlin NONSPACING_MARK NONSPACING\_MARK ================ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [NONSPACING\_MARK](-n-o-n-s-p-a-c-i-n-g_-m-a-r-k) **Platform and version requirements:** JVM (1.0) ``` NONSPACING_MARK ``` Weak bidirectional character type "NSM" in the Unicode specification. kotlin RIGHT_TO_LEFT RIGHT\_TO\_LEFT =============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharDirectionality](index) / [RIGHT\_TO\_LEFT](-r-i-g-h-t_-t-o_-l-e-f-t) **Platform and version requirements:** JVM (1.0) ``` RIGHT_TO_LEFT ``` Strong bidirectional character type "R" in the Unicode specification. kotlin fromLiteral fromLiteral =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / [fromLiteral](from-literal) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` fun fromLiteral(literal: String): Regex ``` Returns a regular expression that matches the specified [literal](from-literal#kotlin.text.Regex.Companion%24fromLiteral(kotlin.String)/literal) string literally. No characters of that string will have special meaning when searching for an occurrence of the regular expression. kotlin Regex Regex ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) **Platform and version requirements:** JS (1.1) ``` class Regex ``` **Platform and version requirements:** JVM (1.0) ``` class Regex : Serializable ``` ##### For JVM Represents a compiled regular expression. Provides functions to match strings in text with a pattern, replace the found occurrences and split text around matches. For pattern syntax reference see [Pattern](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html). ##### For JS Represents a compiled regular expression. Provides functions to match strings in text with a pattern, replace the found occurrences and split text around matches. For pattern syntax reference see [MDN RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Special_characters_meaning_in_regular_expressions) and [http://www.w3schools.com/jsref/jsref\_obj\_regexp.asp](https://www.w3schools.com/jsref/jsref_obj_regexp.asp). Note that `RegExp` objects under the hood are constructed with [the "u" flag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) that enables Unicode-related features in regular expressions. This also makes the pattern syntax more strict, for example, prohibiting unnecessary escape sequences. Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0) #### [<init>](-init-) Creates a regular expression from the specified pattern string and the default options. ``` <init>(pattern: String) ``` Creates a regular expression from the specified pattern string and the specified single option. ``` <init>(pattern: String, option: RegexOption) ``` Creates a regular expression from the specified pattern string and the specified set of options. ``` <init>(pattern: String, options: Set<RegexOption>) ``` Properties ---------- **Platform and version requirements:** JVM (1.0), JS (1.0) #### <options> The set of options that were used to create this regular expression. ``` val options: Set<RegexOption> ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### <pattern> The pattern string of this regular expression. ``` val pattern: String ``` Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0) #### [containsMatchIn](contains-match-in) Indicates whether the regular expression can find at least one match in the specified [input](contains-match-in#kotlin.text.Regex%24containsMatchIn(kotlin.CharSequence)/input). ``` fun containsMatchIn(input: CharSequence): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### <find> Returns the first match of a regular expression in the [input](find#kotlin.text.Regex%24find(kotlin.CharSequence,%20kotlin.Int)/input), beginning at the specified [startIndex](find#kotlin.text.Regex%24find(kotlin.CharSequence,%20kotlin.Int)/startIndex). ``` fun find(     input: CharSequence,     startIndex: Int = 0 ): MatchResult? ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### [findAll](find-all) Returns a sequence of all occurrences of a regular expression within the [input](find-all#kotlin.text.Regex%24findAll(kotlin.CharSequence,%20kotlin.Int)/input) string, beginning at the specified [startIndex](find-all#kotlin.text.Regex%24findAll(kotlin.CharSequence,%20kotlin.Int)/startIndex). ``` fun findAll(     input: CharSequence,     startIndex: Int = 0 ): Sequence<MatchResult> ``` **Platform and version requirements:** JVM (1.7), JS (1.7) #### [matchAt](match-at) Attempts to match a regular expression exactly at the specified [index](match-at#kotlin.text.Regex%24matchAt(kotlin.CharSequence,%20kotlin.Int)/index) in the [input](match-at#kotlin.text.Regex%24matchAt(kotlin.CharSequence,%20kotlin.Int)/input) char sequence. ``` fun matchAt(input: CharSequence, index: Int): MatchResult? ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### [matchEntire](match-entire) Attempts to match the entire [input](match-entire#kotlin.text.Regex%24matchEntire(kotlin.CharSequence)/input) CharSequence against the pattern. ``` fun matchEntire(input: CharSequence): MatchResult? ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### <matches> Indicates whether the regular expression matches the entire [input](matches#kotlin.text.Regex%24matches(kotlin.CharSequence)/input). ``` infix fun matches(input: CharSequence): Boolean ``` **Platform and version requirements:** JVM (1.7), JS (1.7) #### [matchesAt](matches-at) Checks if a regular expression matches a part of the specified [input](matches-at#kotlin.text.Regex%24matchesAt(kotlin.CharSequence,%20kotlin.Int)/input) char sequence exactly at the specified [index](matches-at#kotlin.text.Regex%24matchesAt(kotlin.CharSequence,%20kotlin.Int)/index). ``` fun matchesAt(input: CharSequence, index: Int): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### <replace> Replaces all occurrences of this regular expression in the specified [input](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/input) string with specified [replacement](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/replacement) expression. ``` fun replace(input: CharSequence, replacement: String): String ``` Replaces all occurrences of this regular expression in the specified [input](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.Function1((kotlin.text.MatchResult,%20kotlin.CharSequence)))/input) string with the result of the given function [transform](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.Function1((kotlin.text.MatchResult,%20kotlin.CharSequence)))/transform) that takes MatchResult and returns a string to be used as a replacement for that match. ``` fun replace(     input: CharSequence,     transform: (MatchResult) -> CharSequence ): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### [replaceFirst](replace-first) Replaces the first occurrence of this regular expression in the specified [input](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/input) string with specified [replacement](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/replacement) expression. ``` fun replaceFirst(     input: CharSequence,     replacement: String ): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### <split> Splits the [input](split#kotlin.text.Regex%24split(kotlin.CharSequence,%20kotlin.Int)/input) CharSequence to a list of strings around matches of this regular expression. ``` fun split(input: CharSequence, limit: Int = 0): List<String> ``` **Platform and version requirements:** JVM (1.6), JS (1.6) #### [splitToSequence](split-to-sequence) Splits the [input](split-to-sequence#kotlin.text.Regex%24splitToSequence(kotlin.CharSequence,%20kotlin.Int)/input) CharSequence to a sequence of strings around matches of this regular expression. ``` fun splitToSequence(     input: CharSequence,     limit: Int = 0 ): Sequence<String> ``` **Platform and version requirements:** JVM (1.0) #### [toPattern](to-pattern) Returns an instance of [Pattern](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) with the same pattern string and options as this instance of [Regex](index#kotlin.text.Regex) has. ``` fun toPattern(): Pattern ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### [toString](to-string) Returns the string representation of this regular expression, namely the [pattern](pattern#kotlin.text.Regex%24pattern) of this regular expression. ``` fun toString(): String ``` Companion Object Functions -------------------------- **Platform and version requirements:** JVM (1.0), JS (1.0) #### <escape> Returns a regular expression pattern string that matches the specified [literal](escape#kotlin.text.Regex.Companion%24escape(kotlin.String)/literal) string literally. No characters of that string will have special meaning when searching for an occurrence of the regular expression. ``` fun escape(literal: String): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### [escapeReplacement](escape-replacement) Returns a literal replacement expression for the specified [literal](escape-replacement#kotlin.text.Regex.Companion%24escapeReplacement(kotlin.String)/literal) string. No characters of that string will have special meaning when it is used as a replacement string in [Regex.replace](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)) function. ``` fun escapeReplacement(literal: String): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### [fromLiteral](from-literal) Returns a regular expression that matches the specified [literal](from-literal#kotlin.text.Regex.Companion%24fromLiteral(kotlin.String)/literal) string literally. No characters of that string will have special meaning when searching for an occurrence of the regular expression. ``` fun fromLiteral(literal: String): Regex ```
programming_docs
kotlin matches matches ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / <matches> **Platform and version requirements:** JVM (1.0), JS (1.1) ``` infix fun matches(input: CharSequence): Boolean ``` Indicates whether the regular expression matches the entire [input](matches#kotlin.text.Regex%24matches(kotlin.CharSequence)/input). kotlin findAll findAll ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / [findAll](find-all) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` fun findAll(     input: CharSequence,     startIndex: Int = 0 ): Sequence<MatchResult> ``` Returns a sequence of all occurrences of a regular expression within the [input](find-all#kotlin.text.Regex%24findAll(kotlin.CharSequence,%20kotlin.Int)/input) string, beginning at the specified [startIndex](find-all#kotlin.text.Regex%24findAll(kotlin.CharSequence,%20kotlin.Int)/startIndex). ``` fun main(args: Array<String>) { //sampleStart val text = "Hello Alice. Hello Bob. Hello Eve." val regex = Regex("Hello (.*?)[.]") val matches = regex.findAll(text) val names = matches.map { it.groupValues[1] }.joinToString() println(names) // Alice, Bob, Eve //sampleEnd } ``` Exceptions ---------- `IndexOutOfBoundsException` - if [startIndex](find-all#kotlin.text.Regex%24findAll(kotlin.CharSequence,%20kotlin.Int)/startIndex) is less than zero or greater than the length of the [input](find-all#kotlin.text.Regex%24findAll(kotlin.CharSequence,%20kotlin.Int)/input) char sequence. kotlin split split ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / <split> **Platform and version requirements:** JVM (1.0), JS (1.1) ``` fun split(input: CharSequence, limit: Int = 0): List<String> ``` Splits the [input](split#kotlin.text.Regex%24split(kotlin.CharSequence,%20kotlin.Int)/input) CharSequence to a list of strings around matches of this regular expression. Parameters ---------- `limit` - Non-negative value specifying the maximum number of substrings the string can be split to. Zero by default means no limit is set. kotlin pattern pattern ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / <pattern> **Platform and version requirements:** JVM (1.0), JS (1.1) ``` val pattern: String ``` The pattern string of this regular expression. kotlin replace replace ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / <replace> **Platform and version requirements:** JVM (1.0), JS (1.0) ``` fun replace(input: CharSequence, replacement: String): String ``` ##### For JVM Replaces all occurrences of this regular expression in the specified [input](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/input) string with specified [replacement](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/replacement) expression. The replacement string may contain references to the captured groups during a match. Occurrences of `${name}` or `$index` in the replacement string will be substituted with the subsequences corresponding to the captured groups with the specified name or index. In case of `$index`, the first digit after '$' is always treated as a part of group reference. Subsequent digits are incorporated into `index` only if they would form a valid group reference. Only the digits '0'..'9' are considered as potential components of the group reference. Note that indexes of captured groups start from 1, and the group with index 0 is the whole match. In case of `${name}`, the `name` can consist of latin letters 'a'..'z' and 'A'..'Z', or digits '0'..'9'. The first character must be a letter. Backslash character '\' can be used to include the succeeding character as a literal in the replacement string, e.g, `\$` or `\\`. [Regex.escapeReplacement](escape-replacement#kotlin.text.Regex.Companion%24escapeReplacement(kotlin.String)) can be used if [replacement](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/replacement) have to be treated as a literal string. Note that named capturing groups are supported in Java 7 or later. Parameters ---------- `input` - the char sequence to find matches of this regular expression in `replacement` - the expression to replace found matches with Exceptions ---------- `RuntimeException` - if [replacement](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/replacement) expression is malformed, or capturing group with specified `name` or `index` does not exist **Return** the result of replacing each occurrence of this regular expression in [input](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/input) with the result of evaluating the [replacement](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/replacement) expression ##### For JS Replaces all occurrences of this regular expression in the specified [input](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/input) string with specified [replacement](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/replacement) expression. The replacement string may contain references to the captured groups during a match. Occurrences of `${name}` or `$index` in the replacement string will be substituted with the subsequences corresponding to the captured groups with the specified name or index. In case of `$index`, the first digit after '$' is always treated as a part of group reference. Subsequent digits are incorporated into `index` only if they would form a valid group reference. Only the digits '0'..'9' are considered as potential components of the group reference. Note that indexes of captured groups start from 1, and the group with index 0 is the whole match. In case of `${name}`, the `name` can consist of latin letters 'a'..'z' and 'A'..'Z', or digits '0'..'9'. The first character must be a letter. Backslash character '\' can be used to include the succeeding character as a literal in the replacement string, e.g, `\$` or `\\`. [Regex.escapeReplacement](escape-replacement#kotlin.text.Regex.Companion%24escapeReplacement(kotlin.String)) can be used if [replacement](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/replacement) have to be treated as a literal string. Parameters ---------- `input` - the char sequence to find matches of this regular expression in `replacement` - the expression to replace found matches with Exceptions ---------- `RuntimeException` - if [replacement](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/replacement) expression is malformed, or capturing group with specified `name` or `index` does not exist **Return** the result of replacing each occurrence of this regular expression in [input](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/input) with the result of evaluating the [replacement](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)/replacement) expression **Platform and version requirements:** JVM (1.0), JS (1.0) ``` fun replace(     input: CharSequence,     transform: (MatchResult) -> CharSequence ): String ``` Replaces all occurrences of this regular expression in the specified [input](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.Function1((kotlin.text.MatchResult,%20kotlin.CharSequence)))/input) string with the result of the given function [transform](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.Function1((kotlin.text.MatchResult,%20kotlin.CharSequence)))/transform) that takes MatchResult and returns a string to be used as a replacement for that match. kotlin replaceFirst replaceFirst ============ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / [replaceFirst](replace-first) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` fun replaceFirst(     input: CharSequence,     replacement: String ): String ``` ##### For JVM Replaces the first occurrence of this regular expression in the specified [input](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/input) string with specified [replacement](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/replacement) expression. The replacement string may contain references to the captured groups during a match. Occurrences of `${name}` or `$index` in the replacement string will be substituted with the subsequences corresponding to the captured groups with the specified name or index. In case of `$index`, the first digit after '$' is always treated as a part of group reference. Subsequent digits are incorporated into `index` only if they would form a valid group reference. Only the digits '0'..'9' are considered as potential components of the group reference. Note that indexes of captured groups start from 1, and the group with index 0 is the whole match. In case of `${name}`, the `name` can consist of latin letters 'a'..'z' and 'A'..'Z', or digits '0'..'9'. The first character must be a letter. Backslash character '\' can be used to include the succeeding character as a literal in the replacement string, e.g, `\$` or `\\`. [Regex.escapeReplacement](escape-replacement#kotlin.text.Regex.Companion%24escapeReplacement(kotlin.String)) can be used if [replacement](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/replacement) have to be treated as a literal string. Note that named capturing groups are supported in Java 7 or later. Parameters ---------- `input` - the char sequence to find a match of this regular expression in `replacement` - the expression to replace the found match with Exceptions ---------- `RuntimeException` - if [replacement](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/replacement) expression is malformed, or capturing group with specified `name` or `index` does not exist **Return** the result of replacing the first occurrence of this regular expression in [input](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/input) with the result of evaluating the [replacement](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/replacement) expression ##### For JS Replaces the first occurrence of this regular expression in the specified [input](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/input) string with specified [replacement](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/replacement) expression. The replacement string may contain references to the captured groups during a match. Occurrences of `${name}` or `$index` in the replacement string will be substituted with the subsequences corresponding to the captured groups with the specified name or index. In case of `$index`, the first digit after '$' is always treated as a part of group reference. Subsequent digits are incorporated into `index` only if they would form a valid group reference. Only the digits '0'..'9' are considered as potential components of the group reference. Note that indexes of captured groups start from 1, and the group with index 0 is the whole match. In case of `${name}`, the `name` can consist of latin letters 'a'..'z' and 'A'..'Z', or digits '0'..'9'. The first character must be a letter. Backslash character '\' can be used to include the succeeding character as a literal in the replacement string, e.g, `\$` or `\\`. [Regex.escapeReplacement](escape-replacement#kotlin.text.Regex.Companion%24escapeReplacement(kotlin.String)) can be used if [replacement](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/replacement) have to be treated as a literal string. Parameters ---------- `input` - the char sequence to find a match of this regular expression in `replacement` - the expression to replace the found match with Exceptions ---------- `RuntimeException` - if [replacement](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/replacement) expression is malformed, or capturing group with specified `name` or `index` does not exist **Return** the result of replacing the first occurrence of this regular expression in [input](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/input) with the result of evaluating the [replacement](replace-first#kotlin.text.Regex%24replaceFirst(kotlin.CharSequence,%20kotlin.String)/replacement) expression kotlin matchEntire matchEntire =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / [matchEntire](match-entire) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` fun matchEntire(input: CharSequence): MatchResult? ``` Attempts to match the entire [input](match-entire#kotlin.text.Regex%24matchEntire(kotlin.CharSequence)/input) CharSequence against the pattern. **Return** An instance of MatchResult if the entire input matches or `null` otherwise. kotlin find find ==== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / <find> **Platform and version requirements:** JVM (1.0), JS (1.1) ``` fun find(     input: CharSequence,     startIndex: Int = 0 ): MatchResult? ``` Returns the first match of a regular expression in the [input](find#kotlin.text.Regex%24find(kotlin.CharSequence,%20kotlin.Int)/input), beginning at the specified [startIndex](find#kotlin.text.Regex%24find(kotlin.CharSequence,%20kotlin.Int)/startIndex). ``` fun main(args: Array<String>) { //sampleStart val inputString = "to be or not to be" val regex = "to \\w{2}".toRegex() // If there is matching string, then find method returns non-null MatchResult val match = regex.find(inputString)!! println(match.value) // to be println(match.range) // 0..4 val nextMatch = match.next()!! println(nextMatch.range) // 13..17 val regex2 = "this".toRegex() // If there is no matching string, then find method returns null println(regex2.find(inputString)) // null val regex3 = regex // to be or not to be // ^^^^^ // Because the search starts from the index 2, it finds the last "to be". println(regex3.find(inputString, 2)!!.range) // 13..17 //sampleEnd } ``` Parameters ---------- `startIndex` - An index to start search with, by default 0. Must be not less than zero and not greater than `input.length()` Exceptions ---------- `IndexOutOfBoundsException` - if [startIndex](find#kotlin.text.Regex%24find(kotlin.CharSequence,%20kotlin.Int)/startIndex) is less than zero or greater than the length of the [input](find#kotlin.text.Regex%24find(kotlin.CharSequence,%20kotlin.Int)/input) char sequence. **Return** An instance of [MatchResult](../-match-result/index) if match was found or `null` otherwise. kotlin toString toString ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / [toString](to-string) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` fun toString(): String ``` Returns the string representation of this regular expression, namely the [pattern](pattern#kotlin.text.Regex%24pattern) of this regular expression. Note that another regular expression constructed from the same pattern string may have different [options](options#kotlin.text.Regex%24options) and may match strings differently. kotlin matchesAt matchesAt ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / [matchesAt](matches-at) **Platform and version requirements:** JVM (1.7), JS (1.7) ``` fun matchesAt(input: CharSequence, index: Int): Boolean ``` Checks if a regular expression matches a part of the specified [input](matches-at#kotlin.text.Regex%24matchesAt(kotlin.CharSequence,%20kotlin.Int)/input) char sequence exactly at the specified [index](matches-at#kotlin.text.Regex%24matchesAt(kotlin.CharSequence,%20kotlin.Int)/index). Unlike [matches](matches#kotlin.text.Regex%24matches(kotlin.CharSequence)) function, it doesn't require the match to span to the end of [input](matches-at#kotlin.text.Regex%24matchesAt(kotlin.CharSequence,%20kotlin.Int)/input). ``` fun main(args: Array<String>) { //sampleStart val releaseText = "Kotlin 1.5.30 is released!" val versionRegex = "\\d[.]\\d[.]\\d+".toRegex() println(versionRegex.matchesAt(releaseText, 0)) // false println(versionRegex.matchesAt(releaseText, 7)) // true //sampleEnd } ``` Exceptions ---------- `IndexOutOfBoundsException` - if [index](matches-at#kotlin.text.Regex%24matchesAt(kotlin.CharSequence,%20kotlin.Int)/index) is less than zero or greater than the length of the [input](matches-at#kotlin.text.Regex%24matchesAt(kotlin.CharSequence,%20kotlin.Int)/input) char sequence. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.0) ``` <init>(pattern: String) ``` Creates a regular expression from the specified pattern string and the default options. **Platform and version requirements:** JVM (1.0), JS (1.0) ``` <init>(pattern: String, option: RegexOption) ``` Creates a regular expression from the specified pattern string and the specified single option. **Platform and version requirements:** JVM (1.0), JS (1.0) ``` <init>(pattern: String, options: Set<RegexOption>) ``` ##### For JVM Creates a regular expression from the specified pattern string and the specified set of options. ##### For JS Creates a regular expression from the specified [pattern](pattern#kotlin.text.Regex%24pattern) string and the specified set of [options](options#kotlin.text.Regex%24options). **Constructor** Creates a regular expression from the specified [pattern](pattern#kotlin.text.Regex%24pattern) string and the specified set of [options](options#kotlin.text.Regex%24options). kotlin options options ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / <options> **Platform and version requirements:** JVM (1.0), JS (1.1) ``` val options: Set<RegexOption> ``` The set of options that were used to create this regular expression. kotlin splitToSequence splitToSequence =============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / [splitToSequence](split-to-sequence) **Platform and version requirements:** JVM (1.6), JS (1.6) ``` fun splitToSequence(     input: CharSequence,     limit: Int = 0 ): Sequence<String> ``` Splits the [input](split-to-sequence#kotlin.text.Regex%24splitToSequence(kotlin.CharSequence,%20kotlin.Int)/input) CharSequence to a sequence of strings around matches of this regular expression. ``` fun main(args: Array<String>) { //sampleStart val colors = "green, red , brown&blue, orange, pink&green" val regex = "[,\\s]+".toRegex() val mixedColor = regex.splitToSequence(colors) .onEach { println(it) } .firstOrNull { it.contains('&') } println(mixedColor) // brown&blue //sampleEnd } ``` Parameters ---------- `limit` - Non-negative value specifying the maximum number of substrings the string can be split to. Zero by default means no limit is set. kotlin containsMatchIn containsMatchIn =============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / [containsMatchIn](contains-match-in) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` fun containsMatchIn(input: CharSequence): Boolean ``` Indicates whether the regular expression can find at least one match in the specified [input](contains-match-in#kotlin.text.Regex%24containsMatchIn(kotlin.CharSequence)/input).
programming_docs
kotlin escape escape ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / <escape> **Platform and version requirements:** JVM (1.0), JS (1.1) ``` fun escape(literal: String): String ``` Returns a regular expression pattern string that matches the specified [literal](escape#kotlin.text.Regex.Companion%24escape(kotlin.String)/literal) string literally. No characters of that string will have special meaning when searching for an occurrence of the regular expression. kotlin toPattern toPattern ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / [toPattern](to-pattern) **Platform and version requirements:** JVM (1.0) ``` fun toPattern(): Pattern ``` Returns an instance of [Pattern](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) with the same pattern string and options as this instance of [Regex](index#kotlin.text.Regex) has. Provides the way to use [Regex](index#kotlin.text.Regex) where [Pattern](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) is required. kotlin matchAt matchAt ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / [matchAt](match-at) **Platform and version requirements:** JVM (1.7), JS (1.7) ``` fun matchAt(input: CharSequence, index: Int): MatchResult? ``` Attempts to match a regular expression exactly at the specified [index](match-at#kotlin.text.Regex%24matchAt(kotlin.CharSequence,%20kotlin.Int)/index) in the [input](match-at#kotlin.text.Regex%24matchAt(kotlin.CharSequence,%20kotlin.Int)/input) char sequence. Unlike [matchEntire](match-entire#kotlin.text.Regex%24matchEntire(kotlin.CharSequence)) function, it doesn't require the match to span to the end of [input](match-at#kotlin.text.Regex%24matchAt(kotlin.CharSequence,%20kotlin.Int)/input). ``` fun main(args: Array<String>) { //sampleStart val releaseText = "Kotlin 1.5.30 is released!" val versionRegex = "\\d[.]\\d[.]\\d+".toRegex() println(versionRegex.matchAt(releaseText, 0)) // null println(versionRegex.matchAt(releaseText, 7)?.value) // 1.5.30 //sampleEnd } ``` Exceptions ---------- `IndexOutOfBoundsException` - if [index](match-at#kotlin.text.Regex%24matchAt(kotlin.CharSequence,%20kotlin.Int)/index) is less than zero or greater than the length of the [input](match-at#kotlin.text.Regex%24matchAt(kotlin.CharSequence,%20kotlin.Int)/input) char sequence. **Return** An instance of [MatchResult](../-match-result/index) if the input matches this [Regex](index#kotlin.text.Regex) at the specified [index](match-at#kotlin.text.Regex%24matchAt(kotlin.CharSequence,%20kotlin.Int)/index) or `null` otherwise. kotlin escapeReplacement escapeReplacement ================= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Regex](index) / [escapeReplacement](escape-replacement) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` fun escapeReplacement(literal: String): String ``` Returns a literal replacement expression for the specified [literal](escape-replacement#kotlin.text.Regex.Companion%24escapeReplacement(kotlin.String)/literal) string. No characters of that string will have special meaning when it is used as a replacement string in [Regex.replace](replace#kotlin.text.Regex%24replace(kotlin.CharSequence,%20kotlin.String)) function. kotlin appendln appendln ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.lang.StringBuilder](index) / <appendln> **Platform and version requirements:** JVM (1.0) ``` fun StringBuilder.appendln(): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. Appends a line separator to this StringBuilder. **Platform and version requirements:** JVM (1.0) ``` fun StringBuilder.appendln(     value: StringBuffer? ): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun StringBuilder.appendln(     value: CharSequence? ): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun StringBuilder.appendln(value: String?): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun StringBuilder.appendln(value: Any?): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun StringBuilder.appendln(     value: StringBuilder? ): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun StringBuilder.appendln(value: CharArray): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun StringBuilder.appendln(value: Char): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun StringBuilder.appendln(value: Boolean): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun StringBuilder.appendln(value: Int): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun StringBuilder.appendln(value: Short): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun StringBuilder.appendln(value: Byte): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun StringBuilder.appendln(value: Long): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun StringBuilder.appendln(value: Float): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun StringBuilder.appendln(value: Double): StringBuilder ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. Appends [value](appendln#kotlin.text%24appendln(java.lang.StringBuilder,%20java.lang.StringBuffer?)/value) to this [StringBuilder](../-string-builder/index#kotlin.text.StringBuilder), followed by a line separator. kotlin Extensions for java.lang.StringBuilder Extensions for java.lang.StringBuilder ====================================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.lang.StringBuilder](index) **Platform and version requirements:** JVM (1.4) #### [appendLine](append-line) Appends [value](append-line#kotlin.text%24appendLine(java.lang.StringBuilder,%20java.lang.StringBuffer?)/value) to this [StringBuilder](../-string-builder/index#kotlin.text.StringBuilder), followed by a line feed character (`\n`). ``` fun StringBuilder.appendLine(     value: StringBuffer? ): StringBuilder ``` ``` fun StringBuilder.appendLine(     value: StringBuilder? ): StringBuilder ``` ``` fun StringBuilder.appendLine(value: Int): StringBuilder ``` ``` fun StringBuilder.appendLine(value: Short): StringBuilder ``` ``` fun StringBuilder.appendLine(value: Byte): StringBuilder ``` ``` fun StringBuilder.appendLine(value: Long): StringBuilder ``` ``` fun StringBuilder.appendLine(value: Float): StringBuilder ``` ``` fun StringBuilder.appendLine(value: Double): StringBuilder ``` **Platform and version requirements:** JVM (1.0) #### <appendln> Appends a line separator to this StringBuilder. ``` fun StringBuilder.appendln(): StringBuilder ``` Appends [value](appendln#kotlin.text%24appendln(java.lang.StringBuilder,%20java.lang.StringBuffer?)/value) to this [StringBuilder](../-string-builder/index#kotlin.text.StringBuilder), followed by a line separator. ``` fun StringBuilder.appendln(     value: StringBuffer? ): StringBuilder ``` ``` fun StringBuilder.appendln(     value: CharSequence? ): StringBuilder ``` ``` fun StringBuilder.appendln(value: String?): StringBuilder ``` ``` fun StringBuilder.appendln(value: Any?): StringBuilder ``` ``` fun StringBuilder.appendln(     value: StringBuilder? ): StringBuilder ``` ``` fun StringBuilder.appendln(value: CharArray): StringBuilder ``` ``` fun StringBuilder.appendln(value: Char): StringBuilder ``` ``` fun StringBuilder.appendln(value: Boolean): StringBuilder ``` ``` fun StringBuilder.appendln(value: Int): StringBuilder ``` ``` fun StringBuilder.appendln(value: Short): StringBuilder ``` ``` fun StringBuilder.appendln(value: Byte): StringBuilder ``` ``` fun StringBuilder.appendln(value: Long): StringBuilder ``` ``` fun StringBuilder.appendln(value: Float): StringBuilder ``` ``` fun StringBuilder.appendln(value: Double): StringBuilder ``` **Platform and version requirements:** JVM (1.4) #### [appendRange](append-range) Appends characters in a subarray of the specified character array [value](append-range#kotlin.text%24appendRange(java.lang.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) to this string builder and returns this instance. ``` fun StringBuilder.appendRange(     value: CharArray,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Appends a subsequence of the specified character sequence [value](append-range#kotlin.text%24appendRange(java.lang.StringBuilder,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) to this string builder and returns this instance. ``` fun StringBuilder.appendRange(     value: CharSequence,     startIndex: Int,     endIndex: Int ): StringBuilder ``` **Platform and version requirements:** JVM (1.3) #### <clear> Clears the content of this string builder making it empty and returns this instance. ``` fun StringBuilder.clear(): StringBuilder ``` **Platform and version requirements:** JVM (1.4) #### [deleteAt](delete-at) Removes the character at the specified [index](delete-at#kotlin.text%24deleteAt(java.lang.StringBuilder,%20kotlin.Int)/index) from this string builder and returns this instance. ``` fun StringBuilder.deleteAt(index: Int): StringBuilder ``` **Platform and version requirements:** JVM (1.4) #### [deleteRange](delete-range) Removes characters in the specified range from this string builder and returns this instance. ``` fun StringBuilder.deleteRange(     startIndex: Int,     endIndex: Int ): StringBuilder ``` **Platform and version requirements:** JVM (1.4) #### [insertRange](insert-range) Inserts characters in a subarray of the specified character array [value](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) into this string builder at the specified [index](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/index) and returns this instance. ``` fun StringBuilder.insertRange(     index: Int,     value: CharArray,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Inserts characters in a subsequence of the specified character sequence [value](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) into this string builder at the specified [index](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/index) and returns this instance. ``` fun StringBuilder.insertRange(     index: Int,     value: CharSequence,     startIndex: Int,     endIndex: Int ): StringBuilder ``` **Platform and version requirements:** JVM (1.0) #### <set> Sets the character at the specified [index](set#kotlin.text%24set(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.Char)/index) to the specified [value](set#kotlin.text%24set(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.Char)/value). ``` operator fun StringBuilder.set(index: Int, value: Char) ``` **Platform and version requirements:** JVM (1.4) #### [setRange](set-range) Replaces characters in the specified range of this string builder with characters in the specified string [value](set-range#kotlin.text%24setRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.Int,%20kotlin.String)/value) and returns this instance. ``` fun StringBuilder.setRange(     startIndex: Int,     endIndex: Int,     value: String ): StringBuilder ``` **Platform and version requirements:** JVM (1.4) #### [toCharArray](to-char-array) Copies characters from this string builder into the [destination](to-char-array#kotlin.text%24toCharArray(java.lang.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destination) character array. ``` fun StringBuilder.toCharArray(     destination: CharArray,     destinationOffset: Int = 0,     startIndex: Int = 0,     endIndex: Int = this.length) ``` kotlin insertRange insertRange =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.lang.StringBuilder](index) / [insertRange](insert-range) **Platform and version requirements:** JVM (1.4) ``` fun StringBuilder.insertRange(     index: Int,     value: CharArray,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Inserts characters in a subarray of the specified character array [value](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) into this string builder at the specified [index](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/index) and returns this instance. The inserted characters go in same order as in the [value](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) array, starting at [index](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/index). Parameters ---------- `index` - the position in this string builder to insert at. `value` - the array from which characters are inserted. `startIndex` - the beginning (inclusive) of the subarray to insert. `endIndex` - the end (exclusive) of the subarray to insert. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/endIndex) is out of range of the [value](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) array indices or when `startIndex > endIndex`. `IndexOutOfBoundsException` - if [index](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/index) is less than zero or greater than the length of this string builder. **Platform and version requirements:** JVM (1.4) ``` fun StringBuilder.insertRange(     index: Int,     value: CharSequence,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Inserts characters in a subsequence of the specified character sequence [value](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) into this string builder at the specified [index](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/index) and returns this instance. The inserted characters go in the same order as in the [value](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) character sequence, starting at [index](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/index). Parameters ---------- `index` - the position in this string builder to insert at. `value` - the character sequence from which a subsequence is inserted. `startIndex` - the beginning (inclusive) of the subsequence to insert. `endIndex` - the end (exclusive) of the subsequence to insert. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/endIndex) is out of range of the [value](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) character sequence indices or when `startIndex > endIndex`. `IndexOutOfBoundsException` - if [index](insert-range#kotlin.text%24insertRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/index) is less than zero or greater than the length of this string builder. kotlin setRange setRange ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.lang.StringBuilder](index) / [setRange](set-range) **Platform and version requirements:** JVM (1.4) ``` fun StringBuilder.setRange(     startIndex: Int,     endIndex: Int,     value: String ): StringBuilder ``` Replaces characters in the specified range of this string builder with characters in the specified string [value](set-range#kotlin.text%24setRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.Int,%20kotlin.String)/value) and returns this instance. Parameters ---------- `startIndex` - the beginning (inclusive) of the range to replace. `endIndex` - the end (exclusive) of the range to replace. `value` - the string to replace with. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) if [startIndex](set-range#kotlin.text%24setRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.Int,%20kotlin.String)/startIndex) is less than zero, greater than the length of this string builder, or `startIndex > endIndex`. kotlin appendRange appendRange =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.lang.StringBuilder](index) / [appendRange](append-range) **Platform and version requirements:** JVM (1.4) ``` fun StringBuilder.appendRange(     value: CharArray,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Appends characters in a subarray of the specified character array [value](append-range#kotlin.text%24appendRange(java.lang.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) to this string builder and returns this instance. Characters are appended in order, starting at specified [startIndex](append-range#kotlin.text%24appendRange(java.lang.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/startIndex). Parameters ---------- `value` - the array from which characters are appended. `startIndex` - the beginning (inclusive) of the subarray to append. `endIndex` - the end (exclusive) of the subarray to append. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](append-range#kotlin.text%24appendRange(java.lang.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](append-range#kotlin.text%24appendRange(java.lang.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/endIndex) is out of range of the [value](append-range#kotlin.text%24appendRange(java.lang.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int)/value) array indices or when `startIndex > endIndex`. **Platform and version requirements:** JVM (1.4) ``` fun StringBuilder.appendRange(     value: CharSequence,     startIndex: Int,     endIndex: Int ): StringBuilder ``` Appends a subsequence of the specified character sequence [value](append-range#kotlin.text%24appendRange(java.lang.StringBuilder,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) to this string builder and returns this instance. Parameters ---------- `value` - the character sequence from which a subsequence is appended. `startIndex` - the beginning (inclusive) of the subsequence to append. `endIndex` - the end (exclusive) of the subsequence to append. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](append-range#kotlin.text%24appendRange(java.lang.StringBuilder,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](append-range#kotlin.text%24appendRange(java.lang.StringBuilder,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/endIndex) is out of range of the [value](append-range#kotlin.text%24appendRange(java.lang.StringBuilder,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) character sequence indices or when `startIndex > endIndex`.
programming_docs
kotlin appendLine appendLine ========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.lang.StringBuilder](index) / [appendLine](append-line) **Platform and version requirements:** JVM (1.4) ``` fun StringBuilder.appendLine(     value: StringBuffer? ): StringBuilder ``` ``` fun StringBuilder.appendLine(     value: StringBuilder? ): StringBuilder ``` ``` fun StringBuilder.appendLine(value: Int): StringBuilder ``` ``` fun StringBuilder.appendLine(value: Short): StringBuilder ``` ``` fun StringBuilder.appendLine(value: Byte): StringBuilder ``` ``` fun StringBuilder.appendLine(value: Long): StringBuilder ``` ``` fun StringBuilder.appendLine(value: Float): StringBuilder ``` ``` fun StringBuilder.appendLine(value: Double): StringBuilder ``` Appends [value](append-line#kotlin.text%24appendLine(java.lang.StringBuilder,%20java.lang.StringBuffer?)/value) to this [StringBuilder](../-string-builder/index#kotlin.text.StringBuilder), followed by a line feed character (`\n`). kotlin deleteRange deleteRange =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.lang.StringBuilder](index) / [deleteRange](delete-range) **Platform and version requirements:** JVM (1.4) ``` fun StringBuilder.deleteRange(     startIndex: Int,     endIndex: Int ): StringBuilder ``` Removes characters in the specified range from this string builder and returns this instance. Parameters ---------- `startIndex` - the beginning (inclusive) of the range to remove. `endIndex` - the end (exclusive) of the range to remove. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](delete-range#kotlin.text%24deleteRange(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.Int)/startIndex) is out of range of this string builder indices or when `startIndex > endIndex`. kotlin clear clear ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.lang.StringBuilder](index) / <clear> **Platform and version requirements:** JVM (1.3) ``` fun StringBuilder.clear(): StringBuilder ``` Clears the content of this string builder making it empty and returns this instance. ``` import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val builder = StringBuilder() builder.append("content").append(1) println(builder) // content1 builder.clear() println(builder) // //sampleEnd } ``` kotlin deleteAt deleteAt ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.lang.StringBuilder](index) / [deleteAt](delete-at) **Platform and version requirements:** JVM (1.4) ``` fun StringBuilder.deleteAt(index: Int): StringBuilder ``` Removes the character at the specified [index](delete-at#kotlin.text%24deleteAt(java.lang.StringBuilder,%20kotlin.Int)/index) from this string builder and returns this instance. If the `Char` at the specified [index](delete-at#kotlin.text%24deleteAt(java.lang.StringBuilder,%20kotlin.Int)/index) is part of a supplementary code point, this method does not remove the entire supplementary character. Parameters ---------- `index` - the index of `Char` to remove. Exceptions ---------- `IndexOutOfBoundsException` - if [index](delete-at#kotlin.text%24deleteAt(java.lang.StringBuilder,%20kotlin.Int)/index) is out of bounds of this string builder. kotlin toCharArray toCharArray =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.lang.StringBuilder](index) / [toCharArray](to-char-array) **Platform and version requirements:** JVM (1.4) ``` fun StringBuilder.toCharArray(     destination: CharArray,     destinationOffset: Int = 0,     startIndex: Int = 0,     endIndex: Int = this.length) ``` Copies characters from this string builder into the [destination](to-char-array#kotlin.text%24toCharArray(java.lang.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destination) character array. Parameters ---------- `destination` - the array to copy to. `destinationOffset` - the position in the array to copy to, 0 by default. `startIndex` - the beginning (inclusive) of the range to copy, 0 by default. `endIndex` - the end (exclusive) of the range to copy, length of this string builder by default. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](to-char-array#kotlin.text%24toCharArray(java.lang.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](to-char-array#kotlin.text%24toCharArray(java.lang.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/endIndex) is out of range of this string builder indices or when `startIndex > endIndex`. `IndexOutOfBoundsException` - when the subrange doesn't fit into the [destination](to-char-array#kotlin.text%24toCharArray(java.lang.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destination) array starting at the specified [destinationOffset](to-char-array#kotlin.text%24toCharArray(java.lang.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destinationOffset), or when that index is out of the [destination](to-char-array#kotlin.text%24toCharArray(java.lang.StringBuilder,%20kotlin.CharArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Int)/destination) array indices range. kotlin set set === [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.lang.StringBuilder](index) / <set> **Platform and version requirements:** JVM (1.0) ``` operator fun StringBuilder.set(index: Int, value: Char) ``` Sets the character at the specified [index](set#kotlin.text%24set(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.Char)/index) to the specified [value](set#kotlin.text%24set(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.Char)/value). Exceptions ---------- `IndexOutOfBoundsException` - if [index](set#kotlin.text%24set(java.lang.StringBuilder,%20kotlin.Int,%20kotlin.Char)/index) is out of bounds of this string builder. kotlin Extensions for java.util.regex.Pattern Extensions for java.util.regex.Pattern ====================================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.util.regex.Pattern](index) **Platform and version requirements:** JVM (1.0) #### [toRegex](to-regex) Converts this [java.util.regex.Pattern](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) to an instance of [Regex](../-regex/index#kotlin.text.Regex). ``` fun Pattern.toRegex(): Regex ``` kotlin toRegex toRegex ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.util.regex.Pattern](index) / [toRegex](to-regex) **Platform and version requirements:** JVM (1.0) ``` fun Pattern.toRegex(): Regex ``` Converts this [java.util.regex.Pattern](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) to an instance of [Regex](../-regex/index#kotlin.text.Regex). Provides the way to use Regex API on the instances of [java.util.regex.Pattern](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html). kotlin MatchGroupCollection MatchGroupCollection ==================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchGroupCollection](index) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` interface MatchGroupCollection : Collection<MatchGroup?> ``` Represents a collection of captured groups in a single match of a regular expression. This collection has size of `groupCount + 1` where `groupCount` is the count of groups in the regular expression. Groups are indexed from 1 to `groupCount` and group with the index 0 corresponds to the entire match. An element of the collection at the particular index can be `null`, if the corresponding group in the regular expression is optional and there was no match captured by that group. Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <get> Returns a group with the specified [index](get#kotlin.text.MatchGroupCollection%24get(kotlin.Int)/index). ``` abstract operator fun get(index: Int): MatchGroup? ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [indices](../../kotlin.collections/indices) Returns an [IntRange](../../kotlin.ranges/-int-range/index) of the valid indices for this collection. ``` val Collection<*>.indices: IntRange ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [all](../../kotlin.collections/all) Returns `true` if all elements match the given [predicate](../../kotlin.collections/all#kotlin.collections%24all(kotlin.collections.Iterable((kotlin.collections.all.T)),%20kotlin.Function1((kotlin.collections.all.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [any](../../kotlin.collections/any) Returns `true` if collection has at least one element. ``` fun <T> Iterable<T>.any(): Boolean ``` Returns `true` if at least one element matches the given [predicate](../../kotlin.collections/any#kotlin.collections%24any(kotlin.collections.Iterable((kotlin.collections.any.T)),%20kotlin.Function1((kotlin.collections.any.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [asIterable](../../kotlin.collections/as-iterable) Returns this collection as an [Iterable](../../kotlin.collections/-iterable/index#kotlin.collections.Iterable). ``` fun <T> Iterable<T>.asIterable(): Iterable<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [asSequence](../../kotlin.collections/as-sequence) Creates a [Sequence](../../kotlin.sequences/-sequence/index) instance that wraps the original collection returning its elements when being iterated. ``` fun <T> Iterable<T>.asSequence(): Sequence<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [associate](../../kotlin.collections/associate) Returns a [Map](../../kotlin.collections/-map/index#kotlin.collections.Map) containing key-value pairs provided by [transform](../../kotlin.collections/associate#kotlin.collections%24associate(kotlin.collections.Iterable((kotlin.collections.associate.T)),%20kotlin.Function1((kotlin.collections.associate.T,%20kotlin.Pair((kotlin.collections.associate.K,%20kotlin.collections.associate.V)))))/transform) function applied to elements of the given collection. ``` fun <T, K, V> Iterable<T>.associate(     transform: (T) -> Pair<K, V> ): Map<K, V> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [associateBy](../../kotlin.collections/associate-by) Returns a [Map](../../kotlin.collections/-map/index#kotlin.collections.Map) containing the elements from the given collection indexed by the key returned from [keySelector](../../kotlin.collections/associate-by#kotlin.collections%24associateBy(kotlin.collections.Iterable((kotlin.collections.associateBy.T)),%20kotlin.Function1((kotlin.collections.associateBy.T,%20kotlin.collections.associateBy.K)))/keySelector) function applied to each element. ``` fun <T, K> Iterable<T>.associateBy(     keySelector: (T) -> K ): Map<K, T> ``` Returns a [Map](../../kotlin.collections/-map/index#kotlin.collections.Map) containing the values provided by [valueTransform](../../kotlin.collections/associate-by#kotlin.collections%24associateBy(kotlin.collections.Iterable((kotlin.collections.associateBy.T)),%20kotlin.Function1((kotlin.collections.associateBy.T,%20kotlin.collections.associateBy.K)),%20kotlin.Function1((kotlin.collections.associateBy.T,%20kotlin.collections.associateBy.V)))/valueTransform) and indexed by [keySelector](../../kotlin.collections/associate-by#kotlin.collections%24associateBy(kotlin.collections.Iterable((kotlin.collections.associateBy.T)),%20kotlin.Function1((kotlin.collections.associateBy.T,%20kotlin.collections.associateBy.K)),%20kotlin.Function1((kotlin.collections.associateBy.T,%20kotlin.collections.associateBy.V)))/keySelector) functions applied to elements of the given collection. ``` fun <T, K, V> Iterable<T>.associateBy(     keySelector: (T) -> K,     valueTransform: (T) -> V ): Map<K, V> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [associateByTo](../../kotlin.collections/associate-by-to) Populates and returns the [destination](../../kotlin.collections/associate-by-to#kotlin.collections%24associateByTo(kotlin.collections.Iterable((kotlin.collections.associateByTo.T)),%20kotlin.collections.associateByTo.M,%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.K)))/destination) mutable map with key-value pairs, where key is provided by the [keySelector](../../kotlin.collections/associate-by-to#kotlin.collections%24associateByTo(kotlin.collections.Iterable((kotlin.collections.associateByTo.T)),%20kotlin.collections.associateByTo.M,%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.K)))/keySelector) function applied to each element of the given collection and value is the element itself. ``` fun <T, K, M : MutableMap<in K, in T>> Iterable<T>.associateByTo(     destination: M,     keySelector: (T) -> K ): M ``` Populates and returns the [destination](../../kotlin.collections/associate-by-to#kotlin.collections%24associateByTo(kotlin.collections.Iterable((kotlin.collections.associateByTo.T)),%20kotlin.collections.associateByTo.M,%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.K)),%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.V)))/destination) mutable map with key-value pairs, where key is provided by the [keySelector](../../kotlin.collections/associate-by-to#kotlin.collections%24associateByTo(kotlin.collections.Iterable((kotlin.collections.associateByTo.T)),%20kotlin.collections.associateByTo.M,%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.K)),%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.V)))/keySelector) function and and value is provided by the [valueTransform](../../kotlin.collections/associate-by-to#kotlin.collections%24associateByTo(kotlin.collections.Iterable((kotlin.collections.associateByTo.T)),%20kotlin.collections.associateByTo.M,%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.K)),%20kotlin.Function1((kotlin.collections.associateByTo.T,%20kotlin.collections.associateByTo.V)))/valueTransform) function applied to elements of the given collection. ``` fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.associateByTo(     destination: M,     keySelector: (T) -> K,     valueTransform: (T) -> V ): M ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [associateTo](../../kotlin.collections/associate-to) Populates and returns the [destination](../../kotlin.collections/associate-to#kotlin.collections%24associateTo(kotlin.collections.Iterable((kotlin.collections.associateTo.T)),%20kotlin.collections.associateTo.M,%20kotlin.Function1((kotlin.collections.associateTo.T,%20kotlin.Pair((kotlin.collections.associateTo.K,%20kotlin.collections.associateTo.V)))))/destination) mutable map with key-value pairs provided by [transform](../../kotlin.collections/associate-to#kotlin.collections%24associateTo(kotlin.collections.Iterable((kotlin.collections.associateTo.T)),%20kotlin.collections.associateTo.M,%20kotlin.Function1((kotlin.collections.associateTo.T,%20kotlin.Pair((kotlin.collections.associateTo.K,%20kotlin.collections.associateTo.V)))))/transform) function applied to each element of the given collection. ``` fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.associateTo(     destination: M,     transform: (T) -> Pair<K, V> ): M ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [associateWith](../../kotlin.collections/associate-with) Returns a [Map](../../kotlin.collections/-map/index#kotlin.collections.Map) where keys are elements from the given collection and values are produced by the [valueSelector](../../kotlin.collections/associate-with#kotlin.collections%24associateWith(kotlin.collections.Iterable((kotlin.collections.associateWith.K)),%20kotlin.Function1((kotlin.collections.associateWith.K,%20kotlin.collections.associateWith.V)))/valueSelector) function applied to each element. ``` fun <K, V> Iterable<K>.associateWith(     valueSelector: (K) -> V ): Map<K, V> ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [associateWithTo](../../kotlin.collections/associate-with-to) Populates and returns the [destination](../../kotlin.collections/associate-with-to#kotlin.collections%24associateWithTo(kotlin.collections.Iterable((kotlin.collections.associateWithTo.K)),%20kotlin.collections.associateWithTo.M,%20kotlin.Function1((kotlin.collections.associateWithTo.K,%20kotlin.collections.associateWithTo.V)))/destination) mutable map with key-value pairs for each element of the given collection, where key is the element itself and value is provided by the [valueSelector](../../kotlin.collections/associate-with-to#kotlin.collections%24associateWithTo(kotlin.collections.Iterable((kotlin.collections.associateWithTo.K)),%20kotlin.collections.associateWithTo.M,%20kotlin.Function1((kotlin.collections.associateWithTo.K,%20kotlin.collections.associateWithTo.V)))/valueSelector) function applied to that key. ``` fun <K, V, M : MutableMap<in K, in V>> Iterable<K>.associateWithTo(     destination: M,     valueSelector: (K) -> V ): M ``` **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) #### [chunked](../../kotlin.collections/chunked) Splits this collection into a list of lists each not exceeding the given [size](../../kotlin.collections/chunked#kotlin.collections%24chunked(kotlin.collections.Iterable((kotlin.collections.chunked.T)),%20kotlin.Int)/size). ``` fun <T> Iterable<T>.chunked(size: Int): List<List<T>> ``` Splits this collection into several lists each not exceeding the given [size](../../kotlin.collections/chunked#kotlin.collections%24chunked(kotlin.collections.Iterable((kotlin.collections.chunked.T)),%20kotlin.Int,%20kotlin.Function1((kotlin.collections.List((kotlin.collections.chunked.T)),%20kotlin.collections.chunked.R)))/size) and applies the given [transform](../../kotlin.collections/chunked#kotlin.collections%24chunked(kotlin.collections.Iterable((kotlin.collections.chunked.T)),%20kotlin.Int,%20kotlin.Function1((kotlin.collections.List((kotlin.collections.chunked.T)),%20kotlin.collections.chunked.R)))/transform) function to an each. ``` fun <T, R> Iterable<T>.chunked(     size: Int,     transform: (List<T>) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [contains](../../kotlin.collections/contains) Returns `true` if [element](../../kotlin.collections/contains#kotlin.collections%24contains(kotlin.collections.Iterable((kotlin.collections.contains.T)),%20kotlin.collections.contains.T)/element) is found in the collection. ``` operator fun <T> Iterable<T>.contains(element: T): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [containsAll](../../kotlin.collections/contains-all) Checks if all elements in the specified collection are contained in this collection. ``` fun <T> Collection<T>.containsAll(     elements: Collection<T> ): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [count](../../kotlin.collections/count) Returns the number of elements matching the given [predicate](../../kotlin.collections/count#kotlin.collections%24count(kotlin.collections.Iterable((kotlin.collections.count.T)),%20kotlin.Function1((kotlin.collections.count.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.count(predicate: (T) -> Boolean): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [distinct](../../kotlin.collections/distinct) Returns a list containing only distinct elements from the given collection. ``` fun <T> Iterable<T>.distinct(): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [distinctBy](../../kotlin.collections/distinct-by) Returns a list containing only elements from the given collection having distinct keys returned by the given [selector](../../kotlin.collections/distinct-by#kotlin.collections%24distinctBy(kotlin.collections.Iterable((kotlin.collections.distinctBy.T)),%20kotlin.Function1((kotlin.collections.distinctBy.T,%20kotlin.collections.distinctBy.K)))/selector) function. ``` fun <T, K> Iterable<T>.distinctBy(     selector: (T) -> K ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [drop](../../kotlin.collections/drop) Returns a list containing all elements except first [n](../../kotlin.collections/drop#kotlin.collections%24drop(kotlin.collections.Iterable((kotlin.collections.drop.T)),%20kotlin.Int)/n) elements. ``` fun <T> Iterable<T>.drop(n: Int): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [dropWhile](../../kotlin.collections/drop-while) Returns a list containing all elements except first elements that satisfy the given [predicate](../../kotlin.collections/drop-while#kotlin.collections%24dropWhile(kotlin.collections.Iterable((kotlin.collections.dropWhile.T)),%20kotlin.Function1((kotlin.collections.dropWhile.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.dropWhile(     predicate: (T) -> Boolean ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [elementAt](../../kotlin.collections/element-at) Returns an element at the given [index](../../kotlin.collections/element-at#kotlin.collections%24elementAt(kotlin.collections.Iterable((kotlin.collections.elementAt.T)),%20kotlin.Int)/index) or throws an [IndexOutOfBoundsException](../../kotlin/-index-out-of-bounds-exception/index#kotlin.IndexOutOfBoundsException) if the [index](../../kotlin.collections/element-at#kotlin.collections%24elementAt(kotlin.collections.Iterable((kotlin.collections.elementAt.T)),%20kotlin.Int)/index) is out of bounds of this collection. ``` fun <T> Iterable<T>.elementAt(index: Int): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [elementAtOrElse](../../kotlin.collections/element-at-or-else) Returns an element at the given [index](../../kotlin.collections/element-at-or-else#kotlin.collections%24elementAtOrElse(kotlin.collections.Iterable((kotlin.collections.elementAtOrElse.T)),%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.collections.elementAtOrElse.T)))/index) or the result of calling the [defaultValue](../../kotlin.collections/element-at-or-else#kotlin.collections%24elementAtOrElse(kotlin.collections.Iterable((kotlin.collections.elementAtOrElse.T)),%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.collections.elementAtOrElse.T)))/defaultValue) function if the [index](../../kotlin.collections/element-at-or-else#kotlin.collections%24elementAtOrElse(kotlin.collections.Iterable((kotlin.collections.elementAtOrElse.T)),%20kotlin.Int,%20kotlin.Function1((kotlin.Int,%20kotlin.collections.elementAtOrElse.T)))/index) is out of bounds of this collection. ``` fun <T> Iterable<T>.elementAtOrElse(     index: Int,     defaultValue: (Int) -> T ): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [elementAtOrNull](../../kotlin.collections/element-at-or-null) Returns an element at the given [index](../../kotlin.collections/element-at-or-null#kotlin.collections%24elementAtOrNull(kotlin.collections.Iterable((kotlin.collections.elementAtOrNull.T)),%20kotlin.Int)/index) or `null` if the [index](../../kotlin.collections/element-at-or-null#kotlin.collections%24elementAtOrNull(kotlin.collections.Iterable((kotlin.collections.elementAtOrNull.T)),%20kotlin.Int)/index) is out of bounds of this collection. ``` fun <T> Iterable<T>.elementAtOrNull(index: Int): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filter](../../kotlin.collections/filter) Returns a list containing only elements matching the given [predicate](../../kotlin.collections/filter#kotlin.collections%24filter(kotlin.collections.Iterable((kotlin.collections.filter.T)),%20kotlin.Function1((kotlin.collections.filter.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.filter(     predicate: (T) -> Boolean ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterIndexed](../../kotlin.collections/filter-indexed) Returns a list containing only elements matching the given [predicate](../../kotlin.collections/filter-indexed#kotlin.collections%24filterIndexed(kotlin.collections.Iterable((kotlin.collections.filterIndexed.T)),%20kotlin.Function2((kotlin.Int,%20kotlin.collections.filterIndexed.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.filterIndexed(     predicate: (index: Int, T) -> Boolean ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterIndexedTo](../../kotlin.collections/filter-indexed-to) Appends all elements matching the given [predicate](../../kotlin.collections/filter-indexed-to#kotlin.collections%24filterIndexedTo(kotlin.collections.Iterable((kotlin.collections.filterIndexedTo.T)),%20kotlin.collections.filterIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.filterIndexedTo.T,%20kotlin.Boolean)))/predicate) to the given [destination](../../kotlin.collections/filter-indexed-to#kotlin.collections%24filterIndexedTo(kotlin.collections.Iterable((kotlin.collections.filterIndexedTo.T)),%20kotlin.collections.filterIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.filterIndexedTo.T,%20kotlin.Boolean)))/destination). ``` fun <T, C : MutableCollection<in T>> Iterable<T>.filterIndexedTo(     destination: C,     predicate: (index: Int, T) -> Boolean ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterIsInstance](../../kotlin.collections/filter-is-instance) Returns a list containing all elements that are instances of specified type parameter R. ``` fun <R> Iterable<*>.filterIsInstance(): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterIsInstanceTo](../../kotlin.collections/filter-is-instance-to) Appends all elements that are instances of specified type parameter R to the given [destination](../../kotlin.collections/filter-is-instance-to#kotlin.collections%24filterIsInstanceTo(kotlin.collections.Iterable((kotlin.Any?)),%20kotlin.collections.filterIsInstanceTo.C)/destination). ``` fun <R, C : MutableCollection<in R>> Iterable<*>.filterIsInstanceTo(     destination: C ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterNot](../../kotlin.collections/filter-not) Returns a list containing all elements not matching the given [predicate](../../kotlin.collections/filter-not#kotlin.collections%24filterNot(kotlin.collections.Iterable((kotlin.collections.filterNot.T)),%20kotlin.Function1((kotlin.collections.filterNot.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.filterNot(     predicate: (T) -> Boolean ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterNotNull](../../kotlin.collections/filter-not-null) Returns a list containing all elements that are not `null`. ``` fun <T : Any> Iterable<T?>.filterNotNull(): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterNotNullTo](../../kotlin.collections/filter-not-null-to) Appends all elements that are not `null` to the given [destination](../../kotlin.collections/filter-not-null-to#kotlin.collections%24filterNotNullTo(kotlin.collections.Iterable((kotlin.collections.filterNotNullTo.T?)),%20kotlin.collections.filterNotNullTo.C)/destination). ``` fun <C : MutableCollection<in T>, T : Any> Iterable<T?>.filterNotNullTo(     destination: C ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterNotTo](../../kotlin.collections/filter-not-to) Appends all elements not matching the given [predicate](../../kotlin.collections/filter-not-to#kotlin.collections%24filterNotTo(kotlin.collections.Iterable((kotlin.collections.filterNotTo.T)),%20kotlin.collections.filterNotTo.C,%20kotlin.Function1((kotlin.collections.filterNotTo.T,%20kotlin.Boolean)))/predicate) to the given [destination](../../kotlin.collections/filter-not-to#kotlin.collections%24filterNotTo(kotlin.collections.Iterable((kotlin.collections.filterNotTo.T)),%20kotlin.collections.filterNotTo.C,%20kotlin.Function1((kotlin.collections.filterNotTo.T,%20kotlin.Boolean)))/destination). ``` fun <T, C : MutableCollection<in T>> Iterable<T>.filterNotTo(     destination: C,     predicate: (T) -> Boolean ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [filterTo](../../kotlin.collections/filter-to) Appends all elements matching the given [predicate](../../kotlin.collections/filter-to#kotlin.collections%24filterTo(kotlin.collections.Iterable((kotlin.collections.filterTo.T)),%20kotlin.collections.filterTo.C,%20kotlin.Function1((kotlin.collections.filterTo.T,%20kotlin.Boolean)))/predicate) to the given [destination](../../kotlin.collections/filter-to#kotlin.collections%24filterTo(kotlin.collections.Iterable((kotlin.collections.filterTo.T)),%20kotlin.collections.filterTo.C,%20kotlin.Function1((kotlin.collections.filterTo.T,%20kotlin.Boolean)))/destination). ``` fun <T, C : MutableCollection<in T>> Iterable<T>.filterTo(     destination: C,     predicate: (T) -> Boolean ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [find](../../kotlin.collections/find) Returns the first element matching the given [predicate](../../kotlin.collections/find#kotlin.collections%24find(kotlin.collections.Iterable((kotlin.collections.find.T)),%20kotlin.Function1((kotlin.collections.find.T,%20kotlin.Boolean)))/predicate), or `null` if no such element was found. ``` fun <T> Iterable<T>.find(predicate: (T) -> Boolean): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [findLast](../../kotlin.collections/find-last) Returns the last element matching the given [predicate](../../kotlin.collections/find-last#kotlin.collections%24findLast(kotlin.collections.Iterable((kotlin.collections.findLast.T)),%20kotlin.Function1((kotlin.collections.findLast.T,%20kotlin.Boolean)))/predicate), or `null` if no such element was found. ``` fun <T> Iterable<T>.findLast(predicate: (T) -> Boolean): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [first](../../kotlin.collections/first) Returns the first element. ``` fun <T> Iterable<T>.first(): T ``` Returns the first element matching the given [predicate](../../kotlin.collections/first#kotlin.collections%24first(kotlin.collections.Iterable((kotlin.collections.first.T)),%20kotlin.Function1((kotlin.collections.first.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.first(predicate: (T) -> Boolean): T ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### [firstNotNullOf](../../kotlin.collections/first-not-null-of) Returns the first non-null value produced by [transform](../../kotlin.collections/first-not-null-of#kotlin.collections%24firstNotNullOf(kotlin.collections.Iterable((kotlin.collections.firstNotNullOf.T)),%20kotlin.Function1((kotlin.collections.firstNotNullOf.T,%20kotlin.collections.firstNotNullOf.R?)))/transform) function being applied to elements of this collection in iteration order, or throws [NoSuchElementException](../../kotlin/-no-such-element-exception/index#kotlin.NoSuchElementException) if no non-null value was produced. ``` fun <T, R : Any> Iterable<T>.firstNotNullOf(     transform: (T) -> R? ): R ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### [firstNotNullOfOrNull](../../kotlin.collections/first-not-null-of-or-null) Returns the first non-null value produced by [transform](../../kotlin.collections/first-not-null-of-or-null#kotlin.collections%24firstNotNullOfOrNull(kotlin.collections.Iterable((kotlin.collections.firstNotNullOfOrNull.T)),%20kotlin.Function1((kotlin.collections.firstNotNullOfOrNull.T,%20kotlin.collections.firstNotNullOfOrNull.R?)))/transform) function being applied to elements of this collection in iteration order, or `null` if no non-null value was produced. ``` fun <T, R : Any> Iterable<T>.firstNotNullOfOrNull(     transform: (T) -> R? ): R? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [firstOrNull](../../kotlin.collections/first-or-null) Returns the first element, or `null` if the collection is empty. ``` fun <T> Iterable<T>.firstOrNull(): T? ``` Returns the first element matching the given [predicate](../../kotlin.collections/first-or-null#kotlin.collections%24firstOrNull(kotlin.collections.Iterable((kotlin.collections.firstOrNull.T)),%20kotlin.Function1((kotlin.collections.firstOrNull.T,%20kotlin.Boolean)))/predicate), or `null` if element was not found. ``` fun <T> Iterable<T>.firstOrNull(     predicate: (T) -> Boolean ): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [flatMap](../../kotlin.collections/flat-map) Returns a single list of all elements yielded from results of [transform](../../kotlin.collections/flat-map#kotlin.collections%24flatMap(kotlin.collections.Iterable((kotlin.collections.flatMap.T)),%20kotlin.Function1((kotlin.collections.flatMap.T,%20kotlin.collections.Iterable((kotlin.collections.flatMap.R)))))/transform) function being invoked on each element of original collection. ``` fun <T, R> Iterable<T>.flatMap(     transform: (T) -> Iterable<R> ): List<R> ``` ``` fun <T, R> Iterable<T>.flatMap(     transform: (T) -> Sequence<R> ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [flatMapIndexed](../../kotlin.collections/flat-map-indexed) Returns a single list of all elements yielded from results of [transform](../../kotlin.collections/flat-map-indexed#kotlin.collections%24flatMapIndexed(kotlin.collections.Iterable((kotlin.collections.flatMapIndexed.T)),%20kotlin.Function2((kotlin.Int,%20kotlin.collections.flatMapIndexed.T,%20kotlin.collections.Iterable((kotlin.collections.flatMapIndexed.R)))))/transform) function being invoked on each element and its index in the original collection. ``` fun <T, R> Iterable<T>.flatMapIndexed(     transform: (index: Int, T) -> Iterable<R> ): List<R> ``` ``` fun <T, R> Iterable<T>.flatMapIndexed(     transform: (index: Int, T) -> Sequence<R> ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [flatMapIndexedTo](../../kotlin.collections/flat-map-indexed-to) Appends all elements yielded from results of [transform](../../kotlin.collections/flat-map-indexed-to#kotlin.collections%24flatMapIndexedTo(kotlin.collections.Iterable((kotlin.collections.flatMapIndexedTo.T)),%20kotlin.collections.flatMapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.flatMapIndexedTo.T,%20kotlin.collections.Iterable((kotlin.collections.flatMapIndexedTo.R)))))/transform) function being invoked on each element and its index in the original collection, to the given [destination](../../kotlin.collections/flat-map-indexed-to#kotlin.collections%24flatMapIndexedTo(kotlin.collections.Iterable((kotlin.collections.flatMapIndexedTo.T)),%20kotlin.collections.flatMapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.flatMapIndexedTo.T,%20kotlin.collections.Iterable((kotlin.collections.flatMapIndexedTo.R)))))/destination). ``` fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapIndexedTo(     destination: C,     transform: (index: Int, T) -> Iterable<R> ): C ``` ``` fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapIndexedTo(     destination: C,     transform: (index: Int, T) -> Sequence<R> ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [flatMapTo](../../kotlin.collections/flat-map-to) Appends all elements yielded from results of [transform](../../kotlin.collections/flat-map-to#kotlin.collections%24flatMapTo(kotlin.collections.Iterable((kotlin.collections.flatMapTo.T)),%20kotlin.collections.flatMapTo.C,%20kotlin.Function1((kotlin.collections.flatMapTo.T,%20kotlin.collections.Iterable((kotlin.collections.flatMapTo.R)))))/transform) function being invoked on each element of original collection, to the given [destination](../../kotlin.collections/flat-map-to#kotlin.collections%24flatMapTo(kotlin.collections.Iterable((kotlin.collections.flatMapTo.T)),%20kotlin.collections.flatMapTo.C,%20kotlin.Function1((kotlin.collections.flatMapTo.T,%20kotlin.collections.Iterable((kotlin.collections.flatMapTo.R)))))/destination). ``` fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(     destination: C,     transform: (T) -> Iterable<R> ): C ``` ``` fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(     destination: C,     transform: (T) -> Sequence<R> ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [fold](../../kotlin.collections/fold) Accumulates value starting with [initial](../../kotlin.collections/fold#kotlin.collections%24fold(kotlin.collections.Iterable((kotlin.collections.fold.T)),%20kotlin.collections.fold.R,%20kotlin.Function2((kotlin.collections.fold.R,%20kotlin.collections.fold.T,%20)))/initial) value and applying [operation](../../kotlin.collections/fold#kotlin.collections%24fold(kotlin.collections.Iterable((kotlin.collections.fold.T)),%20kotlin.collections.fold.R,%20kotlin.Function2((kotlin.collections.fold.R,%20kotlin.collections.fold.T,%20)))/operation) from left to right to current accumulator value and each element. ``` fun <T, R> Iterable<T>.fold(     initial: R,     operation: (acc: R, T) -> R ): R ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [foldIndexed](../../kotlin.collections/fold-indexed) Accumulates value starting with [initial](../../kotlin.collections/fold-indexed#kotlin.collections%24foldIndexed(kotlin.collections.Iterable((kotlin.collections.foldIndexed.T)),%20kotlin.collections.foldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.collections.foldIndexed.R,%20kotlin.collections.foldIndexed.T,%20)))/initial) value and applying [operation](../../kotlin.collections/fold-indexed#kotlin.collections%24foldIndexed(kotlin.collections.Iterable((kotlin.collections.foldIndexed.T)),%20kotlin.collections.foldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.collections.foldIndexed.R,%20kotlin.collections.foldIndexed.T,%20)))/operation) from left to right to current accumulator value and each element with its index in the original collection. ``` fun <T, R> Iterable<T>.foldIndexed(     initial: R,     operation: (index: Int, acc: R, T) -> R ): R ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [forEach](../../kotlin.collections/for-each) Performs the given [action](../../kotlin.collections/for-each#kotlin.collections%24forEach(kotlin.collections.Iterable((kotlin.collections.forEach.T)),%20kotlin.Function1((kotlin.collections.forEach.T,%20kotlin.Unit)))/action) on each element. ``` fun <T> Iterable<T>.forEach(action: (T) -> Unit) ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [forEachIndexed](../../kotlin.collections/for-each-indexed) Performs the given [action](../../kotlin.collections/for-each-indexed#kotlin.collections%24forEachIndexed(kotlin.collections.Iterable((kotlin.collections.forEachIndexed.T)),%20kotlin.Function2((kotlin.Int,%20kotlin.collections.forEachIndexed.T,%20kotlin.Unit)))/action) on each element, providing sequential index with the element. ``` fun <T> Iterable<T>.forEachIndexed(     action: (index: Int, T) -> Unit) ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [groupBy](../../kotlin.collections/group-by) Groups elements of the original collection by the key returned by the given [keySelector](../../kotlin.collections/group-by#kotlin.collections%24groupBy(kotlin.collections.Iterable((kotlin.collections.groupBy.T)),%20kotlin.Function1((kotlin.collections.groupBy.T,%20kotlin.collections.groupBy.K)))/keySelector) function applied to each element and returns a map where each group key is associated with a list of corresponding elements. ``` fun <T, K> Iterable<T>.groupBy(     keySelector: (T) -> K ): Map<K, List<T>> ``` Groups values returned by the [valueTransform](../../kotlin.collections/group-by#kotlin.collections%24groupBy(kotlin.collections.Iterable((kotlin.collections.groupBy.T)),%20kotlin.Function1((kotlin.collections.groupBy.T,%20kotlin.collections.groupBy.K)),%20kotlin.Function1((kotlin.collections.groupBy.T,%20kotlin.collections.groupBy.V)))/valueTransform) function applied to each element of the original collection by the key returned by the given [keySelector](../../kotlin.collections/group-by#kotlin.collections%24groupBy(kotlin.collections.Iterable((kotlin.collections.groupBy.T)),%20kotlin.Function1((kotlin.collections.groupBy.T,%20kotlin.collections.groupBy.K)),%20kotlin.Function1((kotlin.collections.groupBy.T,%20kotlin.collections.groupBy.V)))/keySelector) function applied to the element and returns a map where each group key is associated with a list of corresponding values. ``` fun <T, K, V> Iterable<T>.groupBy(     keySelector: (T) -> K,     valueTransform: (T) -> V ): Map<K, List<V>> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [groupByTo](../../kotlin.collections/group-by-to) Groups elements of the original collection by the key returned by the given [keySelector](../../kotlin.collections/group-by-to#kotlin.collections%24groupByTo(kotlin.collections.Iterable((kotlin.collections.groupByTo.T)),%20kotlin.collections.groupByTo.M,%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.K)))/keySelector) function applied to each element and puts to the [destination](../../kotlin.collections/group-by-to#kotlin.collections%24groupByTo(kotlin.collections.Iterable((kotlin.collections.groupByTo.T)),%20kotlin.collections.groupByTo.M,%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.K)))/destination) map each group key associated with a list of corresponding elements. ``` fun <T, K, M : MutableMap<in K, MutableList<T>>> Iterable<T>.groupByTo(     destination: M,     keySelector: (T) -> K ): M ``` Groups values returned by the [valueTransform](../../kotlin.collections/group-by-to#kotlin.collections%24groupByTo(kotlin.collections.Iterable((kotlin.collections.groupByTo.T)),%20kotlin.collections.groupByTo.M,%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.K)),%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.V)))/valueTransform) function applied to each element of the original collection by the key returned by the given [keySelector](../../kotlin.collections/group-by-to#kotlin.collections%24groupByTo(kotlin.collections.Iterable((kotlin.collections.groupByTo.T)),%20kotlin.collections.groupByTo.M,%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.K)),%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.V)))/keySelector) function applied to the element and puts to the [destination](../../kotlin.collections/group-by-to#kotlin.collections%24groupByTo(kotlin.collections.Iterable((kotlin.collections.groupByTo.T)),%20kotlin.collections.groupByTo.M,%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.K)),%20kotlin.Function1((kotlin.collections.groupByTo.T,%20kotlin.collections.groupByTo.V)))/destination) map each group key associated with a list of corresponding values. ``` fun <T, K, V, M : MutableMap<in K, MutableList<V>>> Iterable<T>.groupByTo(     destination: M,     keySelector: (T) -> K,     valueTransform: (T) -> V ): M ``` **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) #### [groupingBy](../../kotlin.collections/grouping-by) Creates a [Grouping](../../kotlin.collections/-grouping/index) source from a collection to be used later with one of group-and-fold operations using the specified [keySelector](../../kotlin.collections/grouping-by#kotlin.collections%24groupingBy(kotlin.collections.Iterable((kotlin.collections.groupingBy.T)),%20kotlin.Function1((kotlin.collections.groupingBy.T,%20kotlin.collections.groupingBy.K)))/keySelector) function to extract a key from each element. ``` fun <T, K> Iterable<T>.groupingBy(     keySelector: (T) -> K ): Grouping<T, K> ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [ifEmpty](../../kotlin.collections/if-empty) Returns this array if it's not empty or the result of calling [defaultValue](../../kotlin.collections/if-empty#kotlin.collections%24ifEmpty(kotlin.collections.ifEmpty.C,%20kotlin.Function0((kotlin.collections.ifEmpty.R)))/defaultValue) function if the array is empty. ``` fun <C, R> C.ifEmpty(     defaultValue: () -> R ): R where C : Array<*>, C : R ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [indexOf](../../kotlin.collections/index-of) Returns first index of [element](../../kotlin.collections/index-of#kotlin.collections%24indexOf(kotlin.collections.Iterable((kotlin.collections.indexOf.T)),%20kotlin.collections.indexOf.T)/element), or -1 if the collection does not contain element. ``` fun <T> Iterable<T>.indexOf(element: T): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [indexOfFirst](../../kotlin.collections/index-of-first) Returns index of the first element matching the given [predicate](../../kotlin.collections/index-of-first#kotlin.collections%24indexOfFirst(kotlin.collections.Iterable((kotlin.collections.indexOfFirst.T)),%20kotlin.Function1((kotlin.collections.indexOfFirst.T,%20kotlin.Boolean)))/predicate), or -1 if the collection does not contain such element. ``` fun <T> Iterable<T>.indexOfFirst(     predicate: (T) -> Boolean ): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [indexOfLast](../../kotlin.collections/index-of-last) Returns index of the last element matching the given [predicate](../../kotlin.collections/index-of-last#kotlin.collections%24indexOfLast(kotlin.collections.Iterable((kotlin.collections.indexOfLast.T)),%20kotlin.Function1((kotlin.collections.indexOfLast.T,%20kotlin.Boolean)))/predicate), or -1 if the collection does not contain such element. ``` fun <T> Iterable<T>.indexOfLast(     predicate: (T) -> Boolean ): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [intersect](../../kotlin.collections/intersect) Returns a set containing all elements that are contained by both this collection and the specified collection. ``` infix fun <T> Iterable<T>.intersect(     other: Iterable<T> ): Set<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [isNotEmpty](../../kotlin.collections/is-not-empty) Returns `true` if the collection is not empty. ``` fun <T> Collection<T>.isNotEmpty(): Boolean ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [isNullOrEmpty](../../kotlin.collections/is-null-or-empty) Returns `true` if this nullable collection is either null or empty. ``` fun <T> Collection<T>?.isNullOrEmpty(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [joinTo](../../kotlin.collections/join-to) Appends the string from all the elements separated using [separator](../../kotlin.collections/join-to#kotlin.collections%24joinTo(kotlin.collections.Iterable((kotlin.collections.joinTo.T)),%20kotlin.collections.joinTo.A,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Function1?((kotlin.collections.joinTo.T,%20kotlin.CharSequence)))/separator) and using the given [prefix](../../kotlin.collections/join-to#kotlin.collections%24joinTo(kotlin.collections.Iterable((kotlin.collections.joinTo.T)),%20kotlin.collections.joinTo.A,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Function1?((kotlin.collections.joinTo.T,%20kotlin.CharSequence)))/prefix) and [postfix](../../kotlin.collections/join-to#kotlin.collections%24joinTo(kotlin.collections.Iterable((kotlin.collections.joinTo.T)),%20kotlin.collections.joinTo.A,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Function1?((kotlin.collections.joinTo.T,%20kotlin.CharSequence)))/postfix) if supplied. ``` fun <T, A : Appendable> Iterable<T>.joinTo(     buffer: A,     separator: CharSequence = ", ",     prefix: CharSequence = "",     postfix: CharSequence = "",     limit: Int = -1,     truncated: CharSequence = "...",     transform: ((T) -> CharSequence)? = null ): A ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [joinToString](../../kotlin.collections/join-to-string) Creates a string from all the elements separated using [separator](../../kotlin.collections/join-to-string#kotlin.collections%24joinToString(kotlin.collections.Iterable((kotlin.collections.joinToString.T)),%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Function1?((kotlin.collections.joinToString.T,%20kotlin.CharSequence)))/separator) and using the given [prefix](../../kotlin.collections/join-to-string#kotlin.collections%24joinToString(kotlin.collections.Iterable((kotlin.collections.joinToString.T)),%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Function1?((kotlin.collections.joinToString.T,%20kotlin.CharSequence)))/prefix) and [postfix](../../kotlin.collections/join-to-string#kotlin.collections%24joinToString(kotlin.collections.Iterable((kotlin.collections.joinToString.T)),%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.CharSequence,%20kotlin.Function1?((kotlin.collections.joinToString.T,%20kotlin.CharSequence)))/postfix) if supplied. ``` fun <T> Iterable<T>.joinToString(     separator: CharSequence = ", ",     prefix: CharSequence = "",     postfix: CharSequence = "",     limit: Int = -1,     truncated: CharSequence = "...",     transform: ((T) -> CharSequence)? = null ): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [last](../../kotlin.collections/last) Returns the last element. ``` fun <T> Iterable<T>.last(): T ``` Returns the last element matching the given [predicate](../../kotlin.collections/last#kotlin.collections%24last(kotlin.collections.Iterable((kotlin.collections.last.T)),%20kotlin.Function1((kotlin.collections.last.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.last(predicate: (T) -> Boolean): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [lastIndexOf](../../kotlin.collections/last-index-of) Returns last index of [element](../../kotlin.collections/last-index-of#kotlin.collections%24lastIndexOf(kotlin.collections.Iterable((kotlin.collections.lastIndexOf.T)),%20kotlin.collections.lastIndexOf.T)/element), or -1 if the collection does not contain element. ``` fun <T> Iterable<T>.lastIndexOf(element: T): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [lastOrNull](../../kotlin.collections/last-or-null) Returns the last element, or `null` if the collection is empty. ``` fun <T> Iterable<T>.lastOrNull(): T? ``` Returns the last element matching the given [predicate](../../kotlin.collections/last-or-null#kotlin.collections%24lastOrNull(kotlin.collections.Iterable((kotlin.collections.lastOrNull.T)),%20kotlin.Function1((kotlin.collections.lastOrNull.T,%20kotlin.Boolean)))/predicate), or `null` if no such element was found. ``` fun <T> Iterable<T>.lastOrNull(predicate: (T) -> Boolean): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [map](../../kotlin.collections/map) Returns a list containing the results of applying the given [transform](../../kotlin.collections/map#kotlin.collections%24map(kotlin.collections.Iterable((kotlin.collections.map.T)),%20kotlin.Function1((kotlin.collections.map.T,%20kotlin.collections.map.R)))/transform) function to each element in the original collection. ``` fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapIndexed](../../kotlin.collections/map-indexed) Returns a list containing the results of applying the given [transform](../../kotlin.collections/map-indexed#kotlin.collections%24mapIndexed(kotlin.collections.Iterable((kotlin.collections.mapIndexed.T)),%20kotlin.Function2((kotlin.Int,%20kotlin.collections.mapIndexed.T,%20kotlin.collections.mapIndexed.R)))/transform) function to each element and its index in the original collection. ``` fun <T, R> Iterable<T>.mapIndexed(     transform: (index: Int, T) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapIndexedNotNull](../../kotlin.collections/map-indexed-not-null) Returns a list containing only the non-null results of applying the given [transform](../../kotlin.collections/map-indexed-not-null#kotlin.collections%24mapIndexedNotNull(kotlin.collections.Iterable((kotlin.collections.mapIndexedNotNull.T)),%20kotlin.Function2((kotlin.Int,%20kotlin.collections.mapIndexedNotNull.T,%20kotlin.collections.mapIndexedNotNull.R?)))/transform) function to each element and its index in the original collection. ``` fun <T, R : Any> Iterable<T>.mapIndexedNotNull(     transform: (index: Int, T) -> R? ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapIndexedNotNullTo](../../kotlin.collections/map-indexed-not-null-to) Applies the given [transform](../../kotlin.collections/map-indexed-not-null-to#kotlin.collections%24mapIndexedNotNullTo(kotlin.collections.Iterable((kotlin.collections.mapIndexedNotNullTo.T)),%20kotlin.collections.mapIndexedNotNullTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.mapIndexedNotNullTo.T,%20kotlin.collections.mapIndexedNotNullTo.R?)))/transform) function to each element and its index in the original collection and appends only the non-null results to the given [destination](../../kotlin.collections/map-indexed-not-null-to#kotlin.collections%24mapIndexedNotNullTo(kotlin.collections.Iterable((kotlin.collections.mapIndexedNotNullTo.T)),%20kotlin.collections.mapIndexedNotNullTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.mapIndexedNotNullTo.T,%20kotlin.collections.mapIndexedNotNullTo.R?)))/destination). ``` fun <T, R : Any, C : MutableCollection<in R>> Iterable<T>.mapIndexedNotNullTo(     destination: C,     transform: (index: Int, T) -> R? ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapIndexedTo](../../kotlin.collections/map-indexed-to) Applies the given [transform](../../kotlin.collections/map-indexed-to#kotlin.collections%24mapIndexedTo(kotlin.collections.Iterable((kotlin.collections.mapIndexedTo.T)),%20kotlin.collections.mapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.mapIndexedTo.T,%20kotlin.collections.mapIndexedTo.R)))/transform) function to each element and its index in the original collection and appends the results to the given [destination](../../kotlin.collections/map-indexed-to#kotlin.collections%24mapIndexedTo(kotlin.collections.Iterable((kotlin.collections.mapIndexedTo.T)),%20kotlin.collections.mapIndexedTo.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.mapIndexedTo.T,%20kotlin.collections.mapIndexedTo.R)))/destination). ``` fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapIndexedTo(     destination: C,     transform: (index: Int, T) -> R ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapNotNull](../../kotlin.collections/map-not-null) Returns a list containing only the non-null results of applying the given [transform](../../kotlin.collections/map-not-null#kotlin.collections%24mapNotNull(kotlin.collections.Iterable((kotlin.collections.mapNotNull.T)),%20kotlin.Function1((kotlin.collections.mapNotNull.T,%20kotlin.collections.mapNotNull.R?)))/transform) function to each element in the original collection. ``` fun <T, R : Any> Iterable<T>.mapNotNull(     transform: (T) -> R? ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapNotNullTo](../../kotlin.collections/map-not-null-to) Applies the given [transform](../../kotlin.collections/map-not-null-to#kotlin.collections%24mapNotNullTo(kotlin.collections.Iterable((kotlin.collections.mapNotNullTo.T)),%20kotlin.collections.mapNotNullTo.C,%20kotlin.Function1((kotlin.collections.mapNotNullTo.T,%20kotlin.collections.mapNotNullTo.R?)))/transform) function to each element in the original collection and appends only the non-null results to the given [destination](../../kotlin.collections/map-not-null-to#kotlin.collections%24mapNotNullTo(kotlin.collections.Iterable((kotlin.collections.mapNotNullTo.T)),%20kotlin.collections.mapNotNullTo.C,%20kotlin.Function1((kotlin.collections.mapNotNullTo.T,%20kotlin.collections.mapNotNullTo.R?)))/destination). ``` fun <T, R : Any, C : MutableCollection<in R>> Iterable<T>.mapNotNullTo(     destination: C,     transform: (T) -> R? ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [mapTo](../../kotlin.collections/map-to) Applies the given [transform](../../kotlin.collections/map-to#kotlin.collections%24mapTo(kotlin.collections.Iterable((kotlin.collections.mapTo.T)),%20kotlin.collections.mapTo.C,%20kotlin.Function1((kotlin.collections.mapTo.T,%20kotlin.collections.mapTo.R)))/transform) function to each element of the original collection and appends the results to the given [destination](../../kotlin.collections/map-to#kotlin.collections%24mapTo(kotlin.collections.Iterable((kotlin.collections.mapTo.T)),%20kotlin.collections.mapTo.C,%20kotlin.Function1((kotlin.collections.mapTo.T,%20kotlin.collections.mapTo.R)))/destination). ``` fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(     destination: C,     transform: (T) -> R ): C ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxByOrNull](../../kotlin.collections/max-by-or-null) Returns the first element yielding the largest value of the given function or `null` if there are no elements. ``` fun <T, R : Comparable<R>> Iterable<T>.maxByOrNull(     selector: (T) -> R ): T? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxOf](../../kotlin.collections/max-of) Returns the largest value among all values produced by [selector](../../kotlin.collections/max-of#kotlin.collections%24maxOf(kotlin.collections.Iterable((kotlin.collections.maxOf.T)),%20kotlin.Function1((kotlin.collections.maxOf.T,%20kotlin.Double)))/selector) function applied to each element in the collection. ``` fun <T> Iterable<T>.maxOf(selector: (T) -> Double): Double ``` ``` fun <T> Iterable<T>.maxOf(selector: (T) -> Float): Float ``` ``` fun <T, R : Comparable<R>> Iterable<T>.maxOf(     selector: (T) -> R ): R ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxOfOrNull](../../kotlin.collections/max-of-or-null) Returns the largest value among all values produced by [selector](../../kotlin.collections/max-of-or-null#kotlin.collections%24maxOfOrNull(kotlin.collections.Iterable((kotlin.collections.maxOfOrNull.T)),%20kotlin.Function1((kotlin.collections.maxOfOrNull.T,%20kotlin.Double)))/selector) function applied to each element in the collection or `null` if there are no elements. ``` fun <T> Iterable<T>.maxOfOrNull(     selector: (T) -> Double ): Double? ``` ``` fun <T> Iterable<T>.maxOfOrNull(     selector: (T) -> Float ): Float? ``` ``` fun <T, R : Comparable<R>> Iterable<T>.maxOfOrNull(     selector: (T) -> R ): R? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxOfWith](../../kotlin.collections/max-of-with) Returns the largest value according to the provided [comparator](../../kotlin.collections/max-of-with#kotlin.collections%24maxOfWith(kotlin.collections.Iterable((kotlin.collections.maxOfWith.T)),%20kotlin.Comparator((kotlin.collections.maxOfWith.R)),%20kotlin.Function1((kotlin.collections.maxOfWith.T,%20kotlin.collections.maxOfWith.R)))/comparator) among all values produced by [selector](../../kotlin.collections/max-of-with#kotlin.collections%24maxOfWith(kotlin.collections.Iterable((kotlin.collections.maxOfWith.T)),%20kotlin.Comparator((kotlin.collections.maxOfWith.R)),%20kotlin.Function1((kotlin.collections.maxOfWith.T,%20kotlin.collections.maxOfWith.R)))/selector) function applied to each element in the collection. ``` fun <T, R> Iterable<T>.maxOfWith(     comparator: Comparator<in R>,     selector: (T) -> R ): R ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxOfWithOrNull](../../kotlin.collections/max-of-with-or-null) Returns the largest value according to the provided [comparator](../../kotlin.collections/max-of-with-or-null#kotlin.collections%24maxOfWithOrNull(kotlin.collections.Iterable((kotlin.collections.maxOfWithOrNull.T)),%20kotlin.Comparator((kotlin.collections.maxOfWithOrNull.R)),%20kotlin.Function1((kotlin.collections.maxOfWithOrNull.T,%20kotlin.collections.maxOfWithOrNull.R)))/comparator) among all values produced by [selector](../../kotlin.collections/max-of-with-or-null#kotlin.collections%24maxOfWithOrNull(kotlin.collections.Iterable((kotlin.collections.maxOfWithOrNull.T)),%20kotlin.Comparator((kotlin.collections.maxOfWithOrNull.R)),%20kotlin.Function1((kotlin.collections.maxOfWithOrNull.T,%20kotlin.collections.maxOfWithOrNull.R)))/selector) function applied to each element in the collection or `null` if there are no elements. ``` fun <T, R> Iterable<T>.maxOfWithOrNull(     comparator: Comparator<in R>,     selector: (T) -> R ): R? ``` **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) #### [maxWith](../../kotlin.collections/max-with) Returns the first element having the largest value according to the provided [comparator](../../kotlin.collections/max-with#kotlin.collections%24maxWith(kotlin.collections.Iterable((kotlin.collections.maxWith.T)),%20kotlin.Comparator((kotlin.collections.maxWith.T)))/comparator). ``` fun <T> Iterable<T>.maxWith(comparator: Comparator<in T>): T ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [maxWithOrNull](../../kotlin.collections/max-with-or-null) Returns the first element having the largest value according to the provided [comparator](../../kotlin.collections/max-with-or-null#kotlin.collections%24maxWithOrNull(kotlin.collections.Iterable((kotlin.collections.maxWithOrNull.T)),%20kotlin.Comparator((kotlin.collections.maxWithOrNull.T)))/comparator) or `null` if there are no elements. ``` fun <T> Iterable<T>.maxWithOrNull(     comparator: Comparator<in T> ): T? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minByOrNull](../../kotlin.collections/min-by-or-null) Returns the first element yielding the smallest value of the given function or `null` if there are no elements. ``` fun <T, R : Comparable<R>> Iterable<T>.minByOrNull(     selector: (T) -> R ): T? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minOf](../../kotlin.collections/min-of) Returns the smallest value among all values produced by [selector](../../kotlin.collections/min-of#kotlin.collections%24minOf(kotlin.collections.Iterable((kotlin.collections.minOf.T)),%20kotlin.Function1((kotlin.collections.minOf.T,%20kotlin.Double)))/selector) function applied to each element in the collection. ``` fun <T> Iterable<T>.minOf(selector: (T) -> Double): Double ``` ``` fun <T> Iterable<T>.minOf(selector: (T) -> Float): Float ``` ``` fun <T, R : Comparable<R>> Iterable<T>.minOf(     selector: (T) -> R ): R ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minOfOrNull](../../kotlin.collections/min-of-or-null) Returns the smallest value among all values produced by [selector](../../kotlin.collections/min-of-or-null#kotlin.collections%24minOfOrNull(kotlin.collections.Iterable((kotlin.collections.minOfOrNull.T)),%20kotlin.Function1((kotlin.collections.minOfOrNull.T,%20kotlin.Double)))/selector) function applied to each element in the collection or `null` if there are no elements. ``` fun <T> Iterable<T>.minOfOrNull(     selector: (T) -> Double ): Double? ``` ``` fun <T> Iterable<T>.minOfOrNull(     selector: (T) -> Float ): Float? ``` ``` fun <T, R : Comparable<R>> Iterable<T>.minOfOrNull(     selector: (T) -> R ): R? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minOfWith](../../kotlin.collections/min-of-with) Returns the smallest value according to the provided [comparator](../../kotlin.collections/min-of-with#kotlin.collections%24minOfWith(kotlin.collections.Iterable((kotlin.collections.minOfWith.T)),%20kotlin.Comparator((kotlin.collections.minOfWith.R)),%20kotlin.Function1((kotlin.collections.minOfWith.T,%20kotlin.collections.minOfWith.R)))/comparator) among all values produced by [selector](../../kotlin.collections/min-of-with#kotlin.collections%24minOfWith(kotlin.collections.Iterable((kotlin.collections.minOfWith.T)),%20kotlin.Comparator((kotlin.collections.minOfWith.R)),%20kotlin.Function1((kotlin.collections.minOfWith.T,%20kotlin.collections.minOfWith.R)))/selector) function applied to each element in the collection. ``` fun <T, R> Iterable<T>.minOfWith(     comparator: Comparator<in R>,     selector: (T) -> R ): R ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minOfWithOrNull](../../kotlin.collections/min-of-with-or-null) Returns the smallest value according to the provided [comparator](../../kotlin.collections/min-of-with-or-null#kotlin.collections%24minOfWithOrNull(kotlin.collections.Iterable((kotlin.collections.minOfWithOrNull.T)),%20kotlin.Comparator((kotlin.collections.minOfWithOrNull.R)),%20kotlin.Function1((kotlin.collections.minOfWithOrNull.T,%20kotlin.collections.minOfWithOrNull.R)))/comparator) among all values produced by [selector](../../kotlin.collections/min-of-with-or-null#kotlin.collections%24minOfWithOrNull(kotlin.collections.Iterable((kotlin.collections.minOfWithOrNull.T)),%20kotlin.Comparator((kotlin.collections.minOfWithOrNull.R)),%20kotlin.Function1((kotlin.collections.minOfWithOrNull.T,%20kotlin.collections.minOfWithOrNull.R)))/selector) function applied to each element in the collection or `null` if there are no elements. ``` fun <T, R> Iterable<T>.minOfWithOrNull(     comparator: Comparator<in R>,     selector: (T) -> R ): R? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [minus](../../kotlin.collections/minus) Returns a list containing all elements of the original collection without the first occurrence of the given [element](../../kotlin.collections/minus#kotlin.collections%24minus(kotlin.collections.Iterable((kotlin.collections.minus.T)),%20kotlin.collections.minus.T)/element). ``` operator fun <T> Iterable<T>.minus(element: T): List<T> ``` Returns a list containing all elements of the original collection except the elements contained in the given [elements](../../kotlin.collections/minus#kotlin.collections%24minus(kotlin.collections.Iterable((kotlin.collections.minus.T)),%20kotlin.Array((kotlin.collections.minus.T)))/elements) array. ``` operator fun <T> Iterable<T>.minus(     elements: Array<out T> ): List<T> ``` Returns a list containing all elements of the original collection except the elements contained in the given [elements](../../kotlin.collections/minus#kotlin.collections%24minus(kotlin.collections.Iterable((kotlin.collections.minus.T)),%20kotlin.collections.Iterable((kotlin.collections.minus.T)))/elements) collection. ``` operator fun <T> Iterable<T>.minus(     elements: Iterable<T> ): List<T> ``` Returns a list containing all elements of the original collection except the elements contained in the given [elements](../../kotlin.collections/minus#kotlin.collections%24minus(kotlin.collections.Iterable((kotlin.collections.minus.T)),%20kotlin.sequences.Sequence((kotlin.collections.minus.T)))/elements) sequence. ``` operator fun <T> Iterable<T>.minus(     elements: Sequence<T> ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [minusElement](../../kotlin.collections/minus-element) Returns a list containing all elements of the original collection without the first occurrence of the given [element](../../kotlin.collections/minus-element#kotlin.collections%24minusElement(kotlin.collections.Iterable((kotlin.collections.minusElement.T)),%20kotlin.collections.minusElement.T)/element). ``` fun <T> Iterable<T>.minusElement(element: T): List<T> ``` **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) #### [minWith](../../kotlin.collections/min-with) Returns the first element having the smallest value according to the provided [comparator](../../kotlin.collections/min-with#kotlin.collections%24minWith(kotlin.collections.Iterable((kotlin.collections.minWith.T)),%20kotlin.Comparator((kotlin.collections.minWith.T)))/comparator). ``` fun <T> Iterable<T>.minWith(comparator: Comparator<in T>): T ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [minWithOrNull](../../kotlin.collections/min-with-or-null) Returns the first element having the smallest value according to the provided [comparator](../../kotlin.collections/min-with-or-null#kotlin.collections%24minWithOrNull(kotlin.collections.Iterable((kotlin.collections.minWithOrNull.T)),%20kotlin.Comparator((kotlin.collections.minWithOrNull.T)))/comparator) or `null` if there are no elements. ``` fun <T> Iterable<T>.minWithOrNull(     comparator: Comparator<in T> ): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [none](../../kotlin.collections/none) Returns `true` if the collection has no elements. ``` fun <T> Iterable<T>.none(): Boolean ``` Returns `true` if no elements match the given [predicate](../../kotlin.collections/none#kotlin.collections%24none(kotlin.collections.Iterable((kotlin.collections.none.T)),%20kotlin.Function1((kotlin.collections.none.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.none(predicate: (T) -> Boolean): Boolean ``` **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) #### [onEach](../../kotlin.collections/on-each) Performs the given [action](../../kotlin.collections/on-each#kotlin.collections%24onEach(kotlin.collections.onEach.C,%20kotlin.Function1((kotlin.collections.onEach.T,%20kotlin.Unit)))/action) on each element and returns the collection itself afterwards. ``` fun <T, C : Iterable<T>> C.onEach(action: (T) -> Unit): C ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [onEachIndexed](../../kotlin.collections/on-each-indexed) Performs the given [action](../../kotlin.collections/on-each-indexed#kotlin.collections%24onEachIndexed(kotlin.collections.onEachIndexed.C,%20kotlin.Function2((kotlin.Int,%20kotlin.collections.onEachIndexed.T,%20kotlin.Unit)))/action) on each element, providing sequential index with the element, and returns the collection itself afterwards. ``` fun <T, C : Iterable<T>> C.onEachIndexed(     action: (index: Int, T) -> Unit ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [orEmpty](../../kotlin.collections/or-empty) Returns this Collection if it's not `null` and the empty list otherwise. ``` fun <T> Collection<T>?.orEmpty(): Collection<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [partition](../../kotlin.collections/partition) Splits the original collection into pair of lists, where *first* list contains elements for which [predicate](../../kotlin.collections/partition#kotlin.collections%24partition(kotlin.collections.Iterable((kotlin.collections.partition.T)),%20kotlin.Function1((kotlin.collections.partition.T,%20kotlin.Boolean)))/predicate) yielded `true`, while *second* list contains elements for which [predicate](../../kotlin.collections/partition#kotlin.collections%24partition(kotlin.collections.Iterable((kotlin.collections.partition.T)),%20kotlin.Function1((kotlin.collections.partition.T,%20kotlin.Boolean)))/predicate) yielded `false`. ``` fun <T> Iterable<T>.partition(     predicate: (T) -> Boolean ): Pair<List<T>, List<T>> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [plus](../../kotlin.collections/plus) Returns a list containing all elements of the original collection and then the given [element](../../kotlin.collections/plus#kotlin.collections%24plus(kotlin.collections.Iterable((kotlin.collections.plus.T)),%20kotlin.collections.plus.T)/element). ``` operator fun <T> Iterable<T>.plus(element: T): List<T> ``` ``` operator fun <T> Collection<T>.plus(element: T): List<T> ``` Returns a list containing all elements of the original collection and then all elements of the given [elements](../../kotlin.collections/plus#kotlin.collections%24plus(kotlin.collections.Iterable((kotlin.collections.plus.T)),%20kotlin.Array((kotlin.collections.plus.T)))/elements) array. ``` operator fun <T> Iterable<T>.plus(     elements: Array<out T> ): List<T> ``` ``` operator fun <T> Collection<T>.plus(     elements: Array<out T> ): List<T> ``` Returns a list containing all elements of the original collection and then all elements of the given [elements](../../kotlin.collections/plus#kotlin.collections%24plus(kotlin.collections.Iterable((kotlin.collections.plus.T)),%20kotlin.collections.Iterable((kotlin.collections.plus.T)))/elements) collection. ``` operator fun <T> Iterable<T>.plus(     elements: Iterable<T> ): List<T> ``` ``` operator fun <T> Collection<T>.plus(     elements: Iterable<T> ): List<T> ``` Returns a list containing all elements of the original collection and then all elements of the given [elements](../../kotlin.collections/plus#kotlin.collections%24plus(kotlin.collections.Iterable((kotlin.collections.plus.T)),%20kotlin.sequences.Sequence((kotlin.collections.plus.T)))/elements) sequence. ``` operator fun <T> Iterable<T>.plus(     elements: Sequence<T> ): List<T> ``` ``` operator fun <T> Collection<T>.plus(     elements: Sequence<T> ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [plusElement](../../kotlin.collections/plus-element) Returns a list containing all elements of the original collection and then the given [element](../../kotlin.collections/plus-element#kotlin.collections%24plusElement(kotlin.collections.Iterable((kotlin.collections.plusElement.T)),%20kotlin.collections.plusElement.T)/element). ``` fun <T> Iterable<T>.plusElement(element: T): List<T> ``` ``` fun <T> Collection<T>.plusElement(element: T): List<T> ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [random](../../kotlin.collections/random) Returns a random element from this collection. ``` fun <T> Collection<T>.random(): T ``` Returns a random element from this collection using the specified source of randomness. ``` fun <T> Collection<T>.random(random: Random): T ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [randomOrNull](../../kotlin.collections/random-or-null) Returns a random element from this collection, or `null` if this collection is empty. ``` fun <T> Collection<T>.randomOrNull(): T? ``` Returns a random element from this collection using the specified source of randomness, or `null` if this collection is empty. ``` fun <T> Collection<T>.randomOrNull(random: Random): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [reduce](../../kotlin.collections/reduce) Accumulates value starting with the first element and applying [operation](../../kotlin.collections/reduce#kotlin.collections%24reduce(kotlin.collections.Iterable((kotlin.collections.reduce.T)),%20kotlin.Function2((kotlin.collections.reduce.S,%20kotlin.collections.reduce.T,%20)))/operation) from left to right to current accumulator value and each element. ``` fun <S, T : S> Iterable<T>.reduce(     operation: (acc: S, T) -> S ): S ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [reduceIndexed](../../kotlin.collections/reduce-indexed) Accumulates value starting with the first element and applying [operation](../../kotlin.collections/reduce-indexed#kotlin.collections%24reduceIndexed(kotlin.collections.Iterable((kotlin.collections.reduceIndexed.T)),%20kotlin.Function3((kotlin.Int,%20kotlin.collections.reduceIndexed.S,%20kotlin.collections.reduceIndexed.T,%20)))/operation) from left to right to current accumulator value and each element with its index in the original collection. ``` fun <S, T : S> Iterable<T>.reduceIndexed(     operation: (index: Int, acc: S, T) -> S ): S ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [reduceIndexedOrNull](../../kotlin.collections/reduce-indexed-or-null) Accumulates value starting with the first element and applying [operation](../../kotlin.collections/reduce-indexed-or-null#kotlin.collections%24reduceIndexedOrNull(kotlin.collections.Iterable((kotlin.collections.reduceIndexedOrNull.T)),%20kotlin.Function3((kotlin.Int,%20kotlin.collections.reduceIndexedOrNull.S,%20kotlin.collections.reduceIndexedOrNull.T,%20)))/operation) from left to right to current accumulator value and each element with its index in the original collection. ``` fun <S, T : S> Iterable<T>.reduceIndexedOrNull(     operation: (index: Int, acc: S, T) -> S ): S? ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [reduceOrNull](../../kotlin.collections/reduce-or-null) Accumulates value starting with the first element and applying [operation](../../kotlin.collections/reduce-or-null#kotlin.collections%24reduceOrNull(kotlin.collections.Iterable((kotlin.collections.reduceOrNull.T)),%20kotlin.Function2((kotlin.collections.reduceOrNull.S,%20kotlin.collections.reduceOrNull.T,%20)))/operation) from left to right to current accumulator value and each element. ``` fun <S, T : S> Iterable<T>.reduceOrNull(     operation: (acc: S, T) -> S ): S? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [requireNoNulls](../../kotlin.collections/require-no-nulls) Returns an original collection containing all the non-`null` elements, throwing an [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) if there are any `null` elements. ``` fun <T : Any> Iterable<T?>.requireNoNulls(): Iterable<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [reversed](../../kotlin.collections/reversed) Returns a list with elements in reversed order. ``` fun <T> Iterable<T>.reversed(): List<T> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [runningFold](../../kotlin.collections/running-fold) Returns a list containing successive accumulation values generated by applying [operation](../../kotlin.collections/running-fold#kotlin.collections%24runningFold(kotlin.collections.Iterable((kotlin.collections.runningFold.T)),%20kotlin.collections.runningFold.R,%20kotlin.Function2((kotlin.collections.runningFold.R,%20kotlin.collections.runningFold.T,%20)))/operation) from left to right to each element and current accumulator value that starts with [initial](../../kotlin.collections/running-fold#kotlin.collections%24runningFold(kotlin.collections.Iterable((kotlin.collections.runningFold.T)),%20kotlin.collections.runningFold.R,%20kotlin.Function2((kotlin.collections.runningFold.R,%20kotlin.collections.runningFold.T,%20)))/initial) value. ``` fun <T, R> Iterable<T>.runningFold(     initial: R,     operation: (acc: R, T) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [runningFoldIndexed](../../kotlin.collections/running-fold-indexed) Returns a list containing successive accumulation values generated by applying [operation](../../kotlin.collections/running-fold-indexed#kotlin.collections%24runningFoldIndexed(kotlin.collections.Iterable((kotlin.collections.runningFoldIndexed.T)),%20kotlin.collections.runningFoldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.collections.runningFoldIndexed.R,%20kotlin.collections.runningFoldIndexed.T,%20)))/operation) from left to right to each element, its index in the original collection and current accumulator value that starts with [initial](../../kotlin.collections/running-fold-indexed#kotlin.collections%24runningFoldIndexed(kotlin.collections.Iterable((kotlin.collections.runningFoldIndexed.T)),%20kotlin.collections.runningFoldIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.collections.runningFoldIndexed.R,%20kotlin.collections.runningFoldIndexed.T,%20)))/initial) value. ``` fun <T, R> Iterable<T>.runningFoldIndexed(     initial: R,     operation: (index: Int, acc: R, T) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [runningReduce](../../kotlin.collections/running-reduce) Returns a list containing successive accumulation values generated by applying [operation](../../kotlin.collections/running-reduce#kotlin.collections%24runningReduce(kotlin.collections.Iterable((kotlin.collections.runningReduce.T)),%20kotlin.Function2((kotlin.collections.runningReduce.S,%20kotlin.collections.runningReduce.T,%20)))/operation) from left to right to each element and current accumulator value that starts with the first element of this collection. ``` fun <S, T : S> Iterable<T>.runningReduce(     operation: (acc: S, T) -> S ): List<S> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [runningReduceIndexed](../../kotlin.collections/running-reduce-indexed) Returns a list containing successive accumulation values generated by applying [operation](../../kotlin.collections/running-reduce-indexed#kotlin.collections%24runningReduceIndexed(kotlin.collections.Iterable((kotlin.collections.runningReduceIndexed.T)),%20kotlin.Function3((kotlin.Int,%20kotlin.collections.runningReduceIndexed.S,%20kotlin.collections.runningReduceIndexed.T,%20)))/operation) from left to right to each element, its index in the original collection and current accumulator value that starts with the first element of this collection. ``` fun <S, T : S> Iterable<T>.runningReduceIndexed(     operation: (index: Int, acc: S, T) -> S ): List<S> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [scan](../../kotlin.collections/scan) Returns a list containing successive accumulation values generated by applying [operation](../../kotlin.collections/scan#kotlin.collections%24scan(kotlin.collections.Iterable((kotlin.collections.scan.T)),%20kotlin.collections.scan.R,%20kotlin.Function2((kotlin.collections.scan.R,%20kotlin.collections.scan.T,%20)))/operation) from left to right to each element and current accumulator value that starts with [initial](../../kotlin.collections/scan#kotlin.collections%24scan(kotlin.collections.Iterable((kotlin.collections.scan.T)),%20kotlin.collections.scan.R,%20kotlin.Function2((kotlin.collections.scan.R,%20kotlin.collections.scan.T,%20)))/initial) value. ``` fun <T, R> Iterable<T>.scan(     initial: R,     operation: (acc: R, T) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [scanIndexed](../../kotlin.collections/scan-indexed) Returns a list containing successive accumulation values generated by applying [operation](../../kotlin.collections/scan-indexed#kotlin.collections%24scanIndexed(kotlin.collections.Iterable((kotlin.collections.scanIndexed.T)),%20kotlin.collections.scanIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.collections.scanIndexed.R,%20kotlin.collections.scanIndexed.T,%20)))/operation) from left to right to each element, its index in the original collection and current accumulator value that starts with [initial](../../kotlin.collections/scan-indexed#kotlin.collections%24scanIndexed(kotlin.collections.Iterable((kotlin.collections.scanIndexed.T)),%20kotlin.collections.scanIndexed.R,%20kotlin.Function3((kotlin.Int,%20kotlin.collections.scanIndexed.R,%20kotlin.collections.scanIndexed.T,%20)))/initial) value. ``` fun <T, R> Iterable<T>.scanIndexed(     initial: R,     operation: (index: Int, acc: R, T) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [shuffled](../../kotlin.collections/shuffled) Returns a new list with the elements of this list randomly shuffled using the specified [random](../../kotlin.collections/shuffled#kotlin.collections%24shuffled(kotlin.collections.Iterable((kotlin.collections.shuffled.T)),%20kotlin.random.Random)/random) instance as the source of randomness. ``` fun <T> Iterable<T>.shuffled(random: Random): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [single](../../kotlin.collections/single) Returns the single element, or throws an exception if the collection is empty or has more than one element. ``` fun <T> Iterable<T>.single(): T ``` Returns the single element matching the given [predicate](../../kotlin.collections/single#kotlin.collections%24single(kotlin.collections.Iterable((kotlin.collections.single.T)),%20kotlin.Function1((kotlin.collections.single.T,%20kotlin.Boolean)))/predicate), or throws exception if there is no or more than one matching element. ``` fun <T> Iterable<T>.single(predicate: (T) -> Boolean): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [singleOrNull](../../kotlin.collections/single-or-null) Returns single element, or `null` if the collection is empty or has more than one element. ``` fun <T> Iterable<T>.singleOrNull(): T? ``` Returns the single element matching the given [predicate](../../kotlin.collections/single-or-null#kotlin.collections%24singleOrNull(kotlin.collections.Iterable((kotlin.collections.singleOrNull.T)),%20kotlin.Function1((kotlin.collections.singleOrNull.T,%20kotlin.Boolean)))/predicate), or `null` if element was not found or more than one element was found. ``` fun <T> Iterable<T>.singleOrNull(     predicate: (T) -> Boolean ): T? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [sortedBy](../../kotlin.collections/sorted-by) Returns a list of all elements sorted according to natural sort order of the value returned by specified [selector](../../kotlin.collections/sorted-by#kotlin.collections%24sortedBy(kotlin.collections.Iterable((kotlin.collections.sortedBy.T)),%20kotlin.Function1((kotlin.collections.sortedBy.T,%20kotlin.collections.sortedBy.R?)))/selector) function. ``` fun <T, R : Comparable<R>> Iterable<T>.sortedBy(     selector: (T) -> R? ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [sortedByDescending](../../kotlin.collections/sorted-by-descending) Returns a list of all elements sorted descending according to natural sort order of the value returned by specified [selector](../../kotlin.collections/sorted-by-descending#kotlin.collections%24sortedByDescending(kotlin.collections.Iterable((kotlin.collections.sortedByDescending.T)),%20kotlin.Function1((kotlin.collections.sortedByDescending.T,%20kotlin.collections.sortedByDescending.R?)))/selector) function. ``` fun <T, R : Comparable<R>> Iterable<T>.sortedByDescending(     selector: (T) -> R? ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [sortedWith](../../kotlin.collections/sorted-with) Returns a list of all elements sorted according to the specified [comparator](../../kotlin.collections/sorted-with#kotlin.collections%24sortedWith(kotlin.collections.Iterable((kotlin.collections.sortedWith.T)),%20kotlin.Comparator((kotlin.collections.sortedWith.T)))/comparator). ``` fun <T> Iterable<T>.sortedWith(     comparator: Comparator<in T> ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [subtract](../../kotlin.collections/subtract) Returns a set containing all elements that are contained by this collection and not contained by the specified collection. ``` infix fun <T> Iterable<T>.subtract(     other: Iterable<T> ): Set<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [sumBy](../../kotlin.collections/sum-by) Returns the sum of all values produced by [selector](../../kotlin.collections/sum-by#kotlin.collections%24sumBy(kotlin.collections.Iterable((kotlin.collections.sumBy.T)),%20kotlin.Function1((kotlin.collections.sumBy.T,%20kotlin.Int)))/selector) function applied to each element in the collection. ``` fun <T> Iterable<T>.sumBy(selector: (T) -> Int): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [sumByDouble](../../kotlin.collections/sum-by-double) Returns the sum of all values produced by [selector](../../kotlin.collections/sum-by-double#kotlin.collections%24sumByDouble(kotlin.collections.Iterable((kotlin.collections.sumByDouble.T)),%20kotlin.Function1((kotlin.collections.sumByDouble.T,%20kotlin.Double)))/selector) function applied to each element in the collection. ``` fun <T> Iterable<T>.sumByDouble(     selector: (T) -> Double ): Double ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [sumOf](../../kotlin.collections/sum-of) Returns the sum of all values produced by [selector](../../kotlin.collections/sum-of#kotlin.collections%24sumOf(kotlin.collections.Iterable((kotlin.collections.sumOf.T)),%20kotlin.Function1((kotlin.collections.sumOf.T,%20kotlin.Double)))/selector) function applied to each element in the collection. ``` fun <T> Iterable<T>.sumOf(selector: (T) -> Double): Double ``` ``` fun <T> Iterable<T>.sumOf(selector: (T) -> Int): Int ``` ``` fun <T> Iterable<T>.sumOf(selector: (T) -> Long): Long ``` ``` fun <T> Iterable<T>.sumOf(selector: (T) -> UInt): UInt ``` ``` fun <T> Iterable<T>.sumOf(selector: (T) -> ULong): ULong ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [take](../../kotlin.collections/take) Returns a list containing first [n](../../kotlin.collections/take#kotlin.collections%24take(kotlin.collections.Iterable((kotlin.collections.take.T)),%20kotlin.Int)/n) elements. ``` fun <T> Iterable<T>.take(n: Int): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [takeWhile](../../kotlin.collections/take-while) Returns a list containing first elements satisfying the given [predicate](../../kotlin.collections/take-while#kotlin.collections%24takeWhile(kotlin.collections.Iterable((kotlin.collections.takeWhile.T)),%20kotlin.Function1((kotlin.collections.takeWhile.T,%20kotlin.Boolean)))/predicate). ``` fun <T> Iterable<T>.takeWhile(     predicate: (T) -> Boolean ): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toCollection](../../kotlin.collections/to-collection) Appends all elements to the given [destination](../../kotlin.collections/to-collection#kotlin.collections%24toCollection(kotlin.collections.Iterable((kotlin.collections.toCollection.T)),%20kotlin.collections.toCollection.C)/destination) collection. ``` fun <T, C : MutableCollection<in T>> Iterable<T>.toCollection(     destination: C ): C ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toHashSet](../../kotlin.collections/to-hash-set) Returns a new [HashSet](../../kotlin.collections/-hash-set/index#kotlin.collections.HashSet) of all elements. ``` fun <T> Iterable<T>.toHashSet(): HashSet<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toList](../../kotlin.collections/to-list) Returns a [List](../../kotlin.collections/-list/index#kotlin.collections.List) containing all elements. ``` fun <T> Iterable<T>.toList(): List<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toMutableSet](../../kotlin.collections/to-mutable-set) Returns a new [MutableSet](../../kotlin.collections/-mutable-set/index#kotlin.collections.MutableSet) containing all distinct elements from the given collection. ``` fun <T> Iterable<T>.toMutableSet(): MutableSet<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toSet](../../kotlin.collections/to-set) Returns a [Set](../../kotlin.collections/-set/index#kotlin.collections.Set) of all elements. ``` fun <T> Iterable<T>.toSet(): Set<T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [union](../../kotlin.collections/union) Returns a set containing all distinct elements from both collections. ``` infix fun <T> Iterable<T>.union(other: Iterable<T>): Set<T> ``` **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) #### [windowed](../../kotlin.collections/windowed) Returns a list of snapshots of the window of the given [size](../../kotlin.collections/windowed#kotlin.collections%24windowed(kotlin.collections.Iterable((kotlin.collections.windowed.T)),%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/size) sliding along this collection with the given [step](../../kotlin.collections/windowed#kotlin.collections%24windowed(kotlin.collections.Iterable((kotlin.collections.windowed.T)),%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/step), where each snapshot is a list. ``` fun <T> Iterable<T>.windowed(     size: Int,     step: Int = 1,     partialWindows: Boolean = false ): List<List<T>> ``` Returns a list of results of applying the given [transform](../../kotlin.collections/windowed#kotlin.collections%24windowed(kotlin.collections.Iterable((kotlin.collections.windowed.T)),%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.collections.List((kotlin.collections.windowed.T)),%20kotlin.collections.windowed.R)))/transform) function to an each list representing a view over the window of the given [size](../../kotlin.collections/windowed#kotlin.collections%24windowed(kotlin.collections.Iterable((kotlin.collections.windowed.T)),%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.collections.List((kotlin.collections.windowed.T)),%20kotlin.collections.windowed.R)))/size) sliding along this collection with the given [step](../../kotlin.collections/windowed#kotlin.collections%24windowed(kotlin.collections.Iterable((kotlin.collections.windowed.T)),%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean,%20kotlin.Function1((kotlin.collections.List((kotlin.collections.windowed.T)),%20kotlin.collections.windowed.R)))/step). ``` fun <T, R> Iterable<T>.windowed(     size: Int,     step: Int = 1,     partialWindows: Boolean = false,     transform: (List<T>) -> R ): List<R> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [withIndex](../../kotlin.collections/with-index) Returns a lazy [Iterable](../../kotlin.collections/-iterable/index#kotlin.collections.Iterable) that wraps each element of the original collection into an [IndexedValue](../../kotlin.collections/-indexed-value/index) containing the index of that element and the element itself. ``` fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [zip](../../kotlin.collections/zip) Returns a list of pairs built from the elements of `this` collection and the [other](../../kotlin.collections/zip#kotlin.collections%24zip(kotlin.collections.Iterable((kotlin.collections.zip.T)),%20kotlin.Array((kotlin.collections.zip.R)))/other) array with the same index. The returned list has length of the shortest collection. ``` infix fun <T, R> Iterable<T>.zip(     other: Array<out R> ): List<Pair<T, R>> ``` Returns a list of values built from the elements of `this` collection and the [other](../../kotlin.collections/zip#kotlin.collections%24zip(kotlin.collections.Iterable((kotlin.collections.zip.T)),%20kotlin.Array((kotlin.collections.zip.R)),%20kotlin.Function2((kotlin.collections.zip.T,%20kotlin.collections.zip.R,%20kotlin.collections.zip.V)))/other) array with the same index using the provided [transform](../../kotlin.collections/zip#kotlin.collections%24zip(kotlin.collections.Iterable((kotlin.collections.zip.T)),%20kotlin.Array((kotlin.collections.zip.R)),%20kotlin.Function2((kotlin.collections.zip.T,%20kotlin.collections.zip.R,%20kotlin.collections.zip.V)))/transform) function applied to each pair of elements. The returned list has length of the shortest collection. ``` fun <T, R, V> Iterable<T>.zip(     other: Array<out R>,     transform: (a: T, b: R) -> V ): List<V> ``` Returns a list of pairs built from the elements of `this` collection and [other](../../kotlin.collections/zip#kotlin.collections%24zip(kotlin.collections.Iterable((kotlin.collections.zip.T)),%20kotlin.collections.Iterable((kotlin.collections.zip.R)))/other) collection with the same index. The returned list has length of the shortest collection. ``` infix fun <T, R> Iterable<T>.zip(     other: Iterable<R> ): List<Pair<T, R>> ``` Returns a list of values built from the elements of `this` collection and the [other](../../kotlin.collections/zip#kotlin.collections%24zip(kotlin.collections.Iterable((kotlin.collections.zip.T)),%20kotlin.collections.Iterable((kotlin.collections.zip.R)),%20kotlin.Function2((kotlin.collections.zip.T,%20kotlin.collections.zip.R,%20kotlin.collections.zip.V)))/other) collection with the same index using the provided [transform](../../kotlin.collections/zip#kotlin.collections%24zip(kotlin.collections.Iterable((kotlin.collections.zip.T)),%20kotlin.collections.Iterable((kotlin.collections.zip.R)),%20kotlin.Function2((kotlin.collections.zip.T,%20kotlin.collections.zip.R,%20kotlin.collections.zip.V)))/transform) function applied to each pair of elements. The returned list has length of the shortest collection. ``` fun <T, R, V> Iterable<T>.zip(     other: Iterable<R>,     transform: (a: T, b: R) -> V ): List<V> ``` **Platform and version requirements:** JVM (1.2), JS (1.2), Native (1.2) #### [zipWithNext](../../kotlin.collections/zip-with-next) Returns a list of pairs of each two adjacent elements in this collection. ``` fun <T> Iterable<T>.zipWithNext(): List<Pair<T, T>> ``` Returns a list containing the results of applying the given [transform](../../kotlin.collections/zip-with-next#kotlin.collections%24zipWithNext(kotlin.collections.Iterable((kotlin.collections.zipWithNext.T)),%20kotlin.Function2((kotlin.collections.zipWithNext.T,%20,%20kotlin.collections.zipWithNext.R)))/transform) function to an each pair of two adjacent elements in this collection. ``` fun <T, R> Iterable<T>.zipWithNext(     transform: (a: T, b: T) -> R ): List<R> ``` Inheritors ---------- **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) #### [MatchNamedGroupCollection](../-match-named-group-collection/index) Extends [MatchGroupCollection](index) by introducing a way to get matched groups by name, when regex supports it. ``` interface MatchNamedGroupCollection : MatchGroupCollection ```
programming_docs
kotlin get get === [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchGroupCollection](index) / <get> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract operator fun get(index: Int): MatchGroup? ``` Returns a group with the specified [index](get#kotlin.text.MatchGroupCollection%24get(kotlin.Int)/index). **Return** An instance of [MatchGroup](../-match-group/index#kotlin.text.MatchGroup) if the group with the specified [index](get#kotlin.text.MatchGroupCollection%24get(kotlin.Int)/index) was matched or `null` otherwise. Groups are indexed from 1 to the count of groups in the regular expression. A group with the index 0 corresponds to the entire match. kotlin Appendable Appendable ========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Appendable](index) **Platform and version requirements:** JS (1.1) ``` interface Appendable ``` **Platform and version requirements:** JVM (1.1) ``` typealias Appendable = Appendable ``` An object to which char sequences and values can be appended. Functions --------- **Platform and version requirements:** JS (1.0) #### <append> Appends the specified character [value](append#kotlin.text.Appendable%24append(kotlin.Char)/value) to this Appendable and returns this instance. ``` abstract fun append(value: Char): Appendable ``` Appends the specified character sequence [value](append#kotlin.text.Appendable%24append(kotlin.CharSequence?)/value) to this Appendable and returns this instance. ``` abstract fun append(value: CharSequence?): Appendable ``` Appends a subsequence of the specified character sequence [value](append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/value) to this Appendable and returns this instance. ``` abstract fun append(     value: CharSequence?,     startIndex: Int,     endIndex: Int ): Appendable ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [append](../append) Appends all arguments to the given [Appendable](index#kotlin.text.Appendable). ``` fun <T : Appendable> T.append(vararg value: CharSequence?): T ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [appendLine](../append-line) Appends a line feed character (`\n`) to this Appendable. ``` fun Appendable.appendLine(): Appendable ``` Appends value to the given Appendable and a line feed character (`\n`) after it. ``` fun Appendable.appendLine(value: CharSequence?): Appendable ``` ``` fun Appendable.appendLine(value: Char): Appendable ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [appendRange](../append-range) Appends a subsequence of the specified character sequence [value](../append-range#kotlin.text%24appendRange(kotlin.text.appendRange.T,%20kotlin.CharSequence,%20kotlin.Int,%20kotlin.Int)/value) to this Appendable and returns this instance. ``` fun <T : Appendable> T.appendRange(     value: CharSequence,     startIndex: Int,     endIndex: Int ): T ``` Inheritors ---------- #### [StringBuilder](../-string-builder/index) A mutable sequence of characters. **Platform and version requirements:** JS (1.1) ``` class StringBuilder : Appendable, CharSequence ``` **Platform and version requirements:** JVM (1.1) ``` typealias StringBuilder = StringBuilder ``` kotlin append append ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Appendable](index) / <append> **Platform and version requirements:** JS (1.0) ``` abstract fun append(value: Char): Appendable ``` Appends the specified character [value](append#kotlin.text.Appendable%24append(kotlin.Char)/value) to this Appendable and returns this instance. Parameters ---------- `value` - the character to append. **Platform and version requirements:** JS (1.0) ``` abstract fun append(value: CharSequence?): Appendable ``` Appends the specified character sequence [value](append#kotlin.text.Appendable%24append(kotlin.CharSequence?)/value) to this Appendable and returns this instance. Parameters ---------- `value` - the character sequence to append. If [value](append#kotlin.text.Appendable%24append(kotlin.CharSequence?)/value) is `null`, then the four characters `"null"` are appended to this Appendable. **Platform and version requirements:** JS (1.0) ``` abstract fun append(     value: CharSequence?,     startIndex: Int,     endIndex: Int ): Appendable ``` Appends a subsequence of the specified character sequence [value](append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/value) to this Appendable and returns this instance. Parameters ---------- `value` - the character sequence from which a subsequence is appended. If [value](append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/value) is `null`, then characters are appended as if [value](append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/value) contained the four characters `"null"`. `startIndex` - the beginning (inclusive) of the subsequence to append. `endIndex` - the end (exclusive) of the subsequence to append. Exceptions ---------- `IndexOutOfBoundsException` - or [IllegalArgumentException](../../kotlin/-illegal-argument-exception/index#kotlin.IllegalArgumentException) when [startIndex](append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/startIndex) or [endIndex](append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/endIndex) is out of range of the [value](append#kotlin.text.Appendable%24append(kotlin.CharSequence?,%20kotlin.Int,%20kotlin.Int)/value) character sequence indices or when `startIndex > endIndex`. kotlin almostEqual almostEqual =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [almostEqual](almost-equal) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val almostEqual: Char ``` The character ≈ kotlin lessOrEqual lessOrEqual =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [lessOrEqual](less-or-equal) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val lessOrEqual: Char ``` The character ≤ kotlin lowSingleQuote lowSingleQuote ============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [lowSingleQuote](low-single-quote) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val lowSingleQuote: Char ``` The character ‚ kotlin rightGuillemet rightGuillemet ============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [rightGuillemet](right-guillemet) **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) ``` const val rightGuillemet: Char ``` The character » kotlin registered registered ========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <registered> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val registered: Char ``` The character ® kotlin leftSingleQuote leftSingleQuote =============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [leftSingleQuote](left-single-quote) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val leftSingleQuote: Char ``` The character ‘ kotlin less less ==== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <less> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val less: Char ``` The character < – less-than sign kotlin Typography Typography ========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` object Typography ``` Defines names for Unicode symbols used in proper Typography. Properties ---------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [almostEqual](almost-equal) The character ≈ ``` const val almostEqual: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <amp> The character & – ampersand ``` const val amp: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <bullet> The character • ``` const val bullet: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <cent> The character ¢ ``` const val cent: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <copyright> The character © ``` const val copyright: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <dagger> The character † ``` const val dagger: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <degree> The character ° ``` const val degree: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <dollar> The character $ – dollar sign ``` const val dollar: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [doubleDagger](double-dagger) The character ‡ ``` const val doubleDagger: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [doublePrime](double-prime) The character ″ ``` const val doublePrime: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <ellipsis> The character … ``` const val ellipsis: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <euro> The character € ``` const val euro: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <greater> The character > – greater-than sign ``` const val greater: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [greaterOrEqual](greater-or-equal) The character ≥ ``` const val greaterOrEqual: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <half> The character ½ ``` const val half: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [leftDoubleQuote](left-double-quote) The character “ ``` const val leftDoubleQuote: Char ``` **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) #### [leftGuillemet](left-guillemet) The character « ``` const val leftGuillemet: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [leftGuillemete](left-guillemete) The character « ``` const val leftGuillemete: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [leftSingleQuote](left-single-quote) The character ‘ ``` const val leftSingleQuote: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <less> The character < – less-than sign ``` const val less: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [lessOrEqual](less-or-equal) The character ≤ ``` const val lessOrEqual: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [lowDoubleQuote](low-double-quote) The character „ ``` const val lowDoubleQuote: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [lowSingleQuote](low-single-quote) The character ‚ ``` const val lowSingleQuote: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <mdash> The character — ``` const val mdash: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [middleDot](middle-dot) The character · ``` const val middleDot: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <nbsp> The non-breaking space character ``` const val nbsp: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <ndash> The character – ``` const val ndash: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [notEqual](not-equal) The character ≠ ``` const val notEqual: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <paragraph> The character ¶ ``` const val paragraph: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [plusMinus](plus-minus) The character ± ``` const val plusMinus: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <pound> The character £ ``` const val pound: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <prime> The character ′ ``` const val prime: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <quote> The character " – quotation mark ``` const val quote: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <registered> The character ® ``` const val registered: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [rightDoubleQuote](right-double-quote) The character ” ``` const val rightDoubleQuote: Char ``` **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) #### [rightGuillemet](right-guillemet) The character » ``` const val rightGuillemet: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [rightGuillemete](right-guillemete) The character » ``` const val rightGuillemete: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [rightSingleQuote](right-single-quote) The character ’ ``` const val rightSingleQuote: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <section> The character § ``` const val section: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <times> The character × ``` const val times: Char ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <tm> The character ™ ``` const val tm: Char ``` kotlin leftGuillemet leftGuillemet ============= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [leftGuillemet](left-guillemet) **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) ``` const val leftGuillemet: Char ``` The character « kotlin ellipsis ellipsis ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <ellipsis> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val ellipsis: Char ``` The character … kotlin dollar dollar ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <dollar> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val dollar: Char ``` The character $ – dollar sign kotlin mdash mdash ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <mdash> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val mdash: Char ``` The character — kotlin middleDot middleDot ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [middleDot](middle-dot) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val middleDot: Char ``` The character · kotlin plusMinus plusMinus ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [plusMinus](plus-minus) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val plusMinus: Char ``` The character ± kotlin dagger dagger ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <dagger> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val dagger: Char ``` The character † kotlin lowDoubleQuote lowDoubleQuote ============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [lowDoubleQuote](low-double-quote) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val lowDoubleQuote: Char ``` The character „ kotlin quote quote ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <quote> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val quote: Char ``` The character " – quotation mark kotlin nbsp nbsp ==== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <nbsp> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val nbsp: Char ``` The non-breaking space character kotlin leftGuillemete leftGuillemete ============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [leftGuillemete](left-guillemete) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @DeprecatedSinceKotlin("1.6") const val leftGuillemete: Char ``` **Deprecated:** This constant has a typo in the name. Use leftGuillemet instead. The character « kotlin leftDoubleQuote leftDoubleQuote =============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [leftDoubleQuote](left-double-quote) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val leftDoubleQuote: Char ``` The character “ kotlin pound pound ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <pound> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val pound: Char ``` The character £ kotlin bullet bullet ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <bullet> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val bullet: Char ``` The character • kotlin greaterOrEqual greaterOrEqual ============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [greaterOrEqual](greater-or-equal) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val greaterOrEqual: Char ``` The character ≥ kotlin doubleDagger doubleDagger ============ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [doubleDagger](double-dagger) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val doubleDagger: Char ``` The character ‡ kotlin notEqual notEqual ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [notEqual](not-equal) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val notEqual: Char ``` The character ≠
programming_docs
kotlin doublePrime doublePrime =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [doublePrime](double-prime) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val doublePrime: Char ``` The character ″ kotlin greater greater ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <greater> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val greater: Char ``` The character > – greater-than sign kotlin half half ==== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <half> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val half: Char ``` The character ½ kotlin rightDoubleQuote rightDoubleQuote ================ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [rightDoubleQuote](right-double-quote) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val rightDoubleQuote: Char ``` The character ” kotlin prime prime ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <prime> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val prime: Char ``` The character ′ kotlin euro euro ==== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <euro> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val euro: Char ``` The character € kotlin tm tm == [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <tm> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val tm: Char ``` The character ™ kotlin section section ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <section> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val section: Char ``` The character § kotlin times times ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <times> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val times: Char ``` The character × kotlin cent cent ==== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <cent> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val cent: Char ``` The character ¢ kotlin rightSingleQuote rightSingleQuote ================ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [rightSingleQuote](right-single-quote) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val rightSingleQuote: Char ``` The character ’ kotlin paragraph paragraph ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <paragraph> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val paragraph: Char ``` The character ¶ kotlin degree degree ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <degree> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val degree: Char ``` The character ° kotlin amp amp === [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <amp> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val amp: Char ``` The character & – ampersand kotlin ndash ndash ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / <ndash> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` const val ndash: Char ``` The character – kotlin rightGuillemete rightGuillemete =============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Typography](index) / [rightGuillemete](right-guillemete) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @DeprecatedSinceKotlin("1.6") const val rightGuillemete: Char ``` **Deprecated:** This constant has a typo in the name. Use rightGuillemet instead. The character » kotlin MatchGroup MatchGroup ========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchGroup](index) **Platform and version requirements:** ``` class MatchGroup ``` **Platform and version requirements:** JVM (1.0), JS (1.1) ``` data class MatchGroup ``` ##### For JVM Represents the results from a single capturing group within a MatchResult of [Regex](../-regex/index#kotlin.text.Regex). Parameters ---------- `value` - The value of captured group. `range` - The range of indices in the input string where group was captured. The <range> property is available on JVM only. ##### For JS Represents the results from a single capturing group within a MatchResult of [Regex](../-regex/index#kotlin.text.Regex). Parameters ---------- `value` - The value of captured group. Constructors ------------ #### [<init>](-init-) Represents the results from a single capturing group within a MatchResult of [Regex](../-regex/index#kotlin.text.Regex). **Platform and version requirements:** JVM (1.0) ``` MatchGroup(value: String, range: IntRange) ``` **Platform and version requirements:** JS (1.1) ``` MatchGroup(value: String) ``` Properties ---------- **Platform and version requirements:** JVM (1.0) #### <range> The range of indices in the input string where group was captured. ``` val range: IntRange ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### <value> The value of captured group. ``` val value: String ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchGroup](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` MatchGroup(value: String, range: IntRange) ``` Represents the results from a single capturing group within a MatchResult of [Regex](../-regex/index#kotlin.text.Regex). Parameters ---------- `value` - The value of captured group. `range` - The range of indices in the input string where group was captured. The <range> property is available on JVM only. **Platform and version requirements:** JS (1.1) ``` MatchGroup(value: String) ``` Represents the results from a single capturing group within a MatchResult of [Regex](../-regex/index#kotlin.text.Regex). Parameters ---------- `value` - The value of captured group. kotlin range range ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchGroup](index) / <range> **Platform and version requirements:** JVM (1.0) ``` val range: IntRange ``` The range of indices in the input string where group was captured. The <range> property is available on JVM only. kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchGroup](index) / <value> **Platform and version requirements:** JVM (1.0), JS (1.1) ``` val value: String ``` The value of captured group. kotlin UTF_16LE UTF\_16LE ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Charsets](index) / [UTF\_16LE](-u-t-f_16-l-e) **Platform and version requirements:** JVM (1.0) ``` val UTF_16LE: Charset ``` Sixteen-bit UCS Transformation Format, little-endian byte order. kotlin UTF_8 UTF\_8 ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Charsets](index) / [UTF\_8](-u-t-f_8) **Platform and version requirements:** JVM (1.0) ``` val UTF_8: Charset ``` Eight-bit UCS Transformation Format. kotlin UTF_16BE UTF\_16BE ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Charsets](index) / [UTF\_16BE](-u-t-f_16-b-e) **Platform and version requirements:** JVM (1.0) ``` val UTF_16BE: Charset ``` Sixteen-bit UCS Transformation Format, big-endian byte order. kotlin Charsets Charsets ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Charsets](index) **Platform and version requirements:** JVM (1.0) ``` object Charsets ``` Constant definitions for the standard [charsets](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html). These charsets are guaranteed to be available on every implementation of the Java platform. Properties ---------- **Platform and version requirements:** JVM (1.0) #### [ISO\_8859\_1](-i-s-o_8859_1) ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1. ``` val ISO_8859_1: Charset ``` **Platform and version requirements:** JVM (1.0) #### [US\_ASCII](-u-s_-a-s-c-i-i) Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set. ``` val US_ASCII: Charset ``` **Platform and version requirements:** JVM (1.0) #### [UTF\_16](-u-t-f_16) Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark. ``` val UTF_16: Charset ``` **Platform and version requirements:** JVM (1.0) #### [UTF\_16BE](-u-t-f_16-b-e) Sixteen-bit UCS Transformation Format, big-endian byte order. ``` val UTF_16BE: Charset ``` **Platform and version requirements:** JVM (1.0) #### [UTF\_16LE](-u-t-f_16-l-e) Sixteen-bit UCS Transformation Format, little-endian byte order. ``` val UTF_16LE: Charset ``` **Platform and version requirements:** JVM (1.0) #### [UTF\_32](-u-t-f_32) 32-bit Unicode (or UCS) Transformation Format, byte order identified by an optional byte-order mark ``` val UTF_32: Charset ``` **Platform and version requirements:** JVM (1.0) #### [UTF\_32BE](-u-t-f_32-b-e) 32-bit Unicode (or UCS) Transformation Format, big-endian byte order. ``` val UTF_32BE: Charset ``` **Platform and version requirements:** JVM (1.0) #### [UTF\_32LE](-u-t-f_32-l-e) 32-bit Unicode (or UCS) Transformation Format, little-endian byte order. ``` val UTF_32LE: Charset ``` **Platform and version requirements:** JVM (1.0) #### [UTF\_8](-u-t-f_8) Eight-bit UCS Transformation Format. ``` val UTF_8: Charset ``` kotlin UTF_16 UTF\_16 ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Charsets](index) / [UTF\_16](-u-t-f_16) **Platform and version requirements:** JVM (1.0) ``` val UTF_16: Charset ``` Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark. kotlin UTF_32LE UTF\_32LE ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Charsets](index) / [UTF\_32LE](-u-t-f_32-l-e) **Platform and version requirements:** JVM (1.0) ``` val UTF_32LE: Charset ``` 32-bit Unicode (or UCS) Transformation Format, little-endian byte order. kotlin ISO_8859_1 ISO\_8859\_1 ============ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Charsets](index) / [ISO\_8859\_1](-i-s-o_8859_1) **Platform and version requirements:** JVM (1.0) ``` val ISO_8859_1: Charset ``` ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1. kotlin UTF_32BE UTF\_32BE ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Charsets](index) / [UTF\_32BE](-u-t-f_32-b-e) **Platform and version requirements:** JVM (1.0) ``` val UTF_32BE: Charset ``` 32-bit Unicode (or UCS) Transformation Format, big-endian byte order. kotlin UTF_32 UTF\_32 ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Charsets](index) / [UTF\_32](-u-t-f_32) **Platform and version requirements:** JVM (1.0) ``` val UTF_32: Charset ``` 32-bit Unicode (or UCS) Transformation Format, byte order identified by an optional byte-order mark kotlin US_ASCII US\_ASCII ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [Charsets](index) / [US\_ASCII](-u-s_-a-s-c-i-i) **Platform and version requirements:** JVM (1.0) ``` val US_ASCII: Charset ``` Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set. kotlin OTHER_SYMBOL OTHER\_SYMBOL ============= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [OTHER\_SYMBOL](-o-t-h-e-r_-s-y-m-b-o-l) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` OTHER_SYMBOL ``` General category "So" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin NON_SPACING_MARK NON\_SPACING\_MARK ================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [NON\_SPACING\_MARK](-n-o-n_-s-p-a-c-i-n-g_-m-a-r-k) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` NON_SPACING_MARK ``` General category "Mn" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin contains contains ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / <contains> **Platform and version requirements:** JVM (1.0), JS (1.1) ``` operator fun contains(char: Char): Boolean ``` Returns `true` if [char](contains#kotlin.text.CharCategory%24contains(kotlin.Char)/char) character belongs to this category. kotlin LETTER_NUMBER LETTER\_NUMBER ============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [LETTER\_NUMBER](-l-e-t-t-e-r_-n-u-m-b-e-r) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` LETTER_NUMBER ``` General category "Nl" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin CURRENCY_SYMBOL CURRENCY\_SYMBOL ================ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [CURRENCY\_SYMBOL](-c-u-r-r-e-n-c-y_-s-y-m-b-o-l) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` CURRENCY_SYMBOL ``` General category "Sc" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin START_PUNCTUATION START\_PUNCTUATION ================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [START\_PUNCTUATION](-s-t-a-r-t_-p-u-n-c-t-u-a-t-i-o-n) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` START_PUNCTUATION ``` General category "Ps" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin PARAGRAPH_SEPARATOR PARAGRAPH\_SEPARATOR ==================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [PARAGRAPH\_SEPARATOR](-p-a-r-a-g-r-a-p-h_-s-e-p-a-r-a-t-o-r) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` PARAGRAPH_SEPARATOR ``` General category "Zp" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin PRIVATE_USE PRIVATE\_USE ============ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [PRIVATE\_USE](-p-r-i-v-a-t-e_-u-s-e) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` PRIVATE_USE ``` General category "Co" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin LOWERCASE_LETTER LOWERCASE\_LETTER ================= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [LOWERCASE\_LETTER](-l-o-w-e-r-c-a-s-e_-l-e-t-t-e-r) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` LOWERCASE_LETTER ``` General category "Ll" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin CharCategory CharCategory ============ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) **Platform and version requirements:** JVM (1.0), JS (1.5) ``` enum class CharCategory ``` Represents the character general category in the Unicode specification. Enum Values ----------- **Platform and version requirements:** JVM (1.0), JS (1.0) #### [UNASSIGNED](-u-n-a-s-s-i-g-n-e-d) General category "Cn" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [UPPERCASE\_LETTER](-u-p-p-e-r-c-a-s-e_-l-e-t-t-e-r) General category "Lu" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [LOWERCASE\_LETTER](-l-o-w-e-r-c-a-s-e_-l-e-t-t-e-r) General category "Ll" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [TITLECASE\_LETTER](-t-i-t-l-e-c-a-s-e_-l-e-t-t-e-r) General category "Lt" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [MODIFIER\_LETTER](-m-o-d-i-f-i-e-r_-l-e-t-t-e-r) General category "Lm" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [OTHER\_LETTER](-o-t-h-e-r_-l-e-t-t-e-r) General category "Lo" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [NON\_SPACING\_MARK](-n-o-n_-s-p-a-c-i-n-g_-m-a-r-k) General category "Mn" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [ENCLOSING\_MARK](-e-n-c-l-o-s-i-n-g_-m-a-r-k) General category "Me" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [COMBINING\_SPACING\_MARK](-c-o-m-b-i-n-i-n-g_-s-p-a-c-i-n-g_-m-a-r-k) General category "Mc" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [DECIMAL\_DIGIT\_NUMBER](-d-e-c-i-m-a-l_-d-i-g-i-t_-n-u-m-b-e-r) General category "Nd" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [LETTER\_NUMBER](-l-e-t-t-e-r_-n-u-m-b-e-r) General category "Nl" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [OTHER\_NUMBER](-o-t-h-e-r_-n-u-m-b-e-r) General category "No" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [SPACE\_SEPARATOR](-s-p-a-c-e_-s-e-p-a-r-a-t-o-r) General category "Zs" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [LINE\_SEPARATOR](-l-i-n-e_-s-e-p-a-r-a-t-o-r) General category "Zl" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [PARAGRAPH\_SEPARATOR](-p-a-r-a-g-r-a-p-h_-s-e-p-a-r-a-t-o-r) General category "Zp" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [CONTROL](-c-o-n-t-r-o-l) General category "Cc" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [FORMAT](-f-o-r-m-a-t) General category "Cf" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [PRIVATE\_USE](-p-r-i-v-a-t-e_-u-s-e) General category "Co" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [SURROGATE](-s-u-r-r-o-g-a-t-e) General category "Cs" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [DASH\_PUNCTUATION](-d-a-s-h_-p-u-n-c-t-u-a-t-i-o-n) General category "Pd" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [START\_PUNCTUATION](-s-t-a-r-t_-p-u-n-c-t-u-a-t-i-o-n) General category "Ps" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [END\_PUNCTUATION](-e-n-d_-p-u-n-c-t-u-a-t-i-o-n) General category "Pe" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [CONNECTOR\_PUNCTUATION](-c-o-n-n-e-c-t-o-r_-p-u-n-c-t-u-a-t-i-o-n) General category "Pc" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [OTHER\_PUNCTUATION](-o-t-h-e-r_-p-u-n-c-t-u-a-t-i-o-n) General category "Po" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [MATH\_SYMBOL](-m-a-t-h_-s-y-m-b-o-l) General category "Sm" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [CURRENCY\_SYMBOL](-c-u-r-r-e-n-c-y_-s-y-m-b-o-l) General category "Sc" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [MODIFIER\_SYMBOL](-m-o-d-i-f-i-e-r_-s-y-m-b-o-l) General category "Sk" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [OTHER\_SYMBOL](-o-t-h-e-r_-s-y-m-b-o-l) General category "So" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [INITIAL\_QUOTE\_PUNCTUATION](-i-n-i-t-i-a-l_-q-u-o-t-e_-p-u-n-c-t-u-a-t-i-o-n) General category "Pi" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [FINAL\_QUOTE\_PUNCTUATION](-f-i-n-a-l_-q-u-o-t-e_-p-u-n-c-t-u-a-t-i-o-n) General category "Pf" in the Unicode specification. Properties ---------- **Platform and version requirements:** JVM (1.0), JS (1.0) #### <code> Two-letter code of this general category in the Unicode specification. ``` val code: String ``` **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0) #### <contains> Returns `true` if [char](contains#kotlin.text.CharCategory%24contains(kotlin.Char)/char) character belongs to this category. ``` operator fun contains(char: Char): Boolean ``` Companion Object Functions -------------------------- **Platform and version requirements:** JVM (1.0) #### [valueOf](value-of) Returns the [CharCategory](index#kotlin.text.CharCategory) corresponding to the specified [category](value-of#kotlin.text.CharCategory.Companion%24valueOf(kotlin.Int)/category) that represents a Java general category constant. ``` fun valueOf(category: Int): CharCategory ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.7) #### [declaringJavaClass](../../kotlin.jvm/declaring-java-class) Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance of the enum the given constant belongs to. ``` val <E : Enum<E>> Enum<E>.declaringJavaClass: Class<E> ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceAtLeast](../../kotlin.ranges/coerce-at-least) Ensures that this value is not less than the specified [minimumValue](../../kotlin.ranges/coerce-at-least#kotlin.ranges%24coerceAtLeast(kotlin.ranges.coerceAtLeast.T,%20kotlin.ranges.coerceAtLeast.T)/minimumValue). ``` fun <T : Comparable<T>> T.coerceAtLeast(minimumValue: T): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceAtMost](../../kotlin.ranges/coerce-at-most) Ensures that this value is not greater than the specified [maximumValue](../../kotlin.ranges/coerce-at-most#kotlin.ranges%24coerceAtMost(kotlin.ranges.coerceAtMost.T,%20kotlin.ranges.coerceAtMost.T)/maximumValue). ``` fun <T : Comparable<T>> T.coerceAtMost(maximumValue: T): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceIn](../../kotlin.ranges/coerce-in) Ensures that this value lies in the specified range [minimumValue](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.coerceIn.T?,%20kotlin.ranges.coerceIn.T?)/minimumValue)..[maximumValue](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.coerceIn.T?,%20kotlin.ranges.coerceIn.T?)/maximumValue). ``` fun <T : Comparable<T>> T.coerceIn(     minimumValue: T?,     maximumValue: T? ): T ``` Ensures that this value lies in the specified [range](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.ClosedFloatingPointRange((kotlin.ranges.coerceIn.T)))/range). ``` fun <T : Comparable<T>> T.coerceIn(     range: ClosedFloatingPointRange<T> ): T ``` ``` fun <T : Comparable<T>> T.coerceIn(range: ClosedRange<T>): T ``` **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) #### [compareTo](../../kotlin/compare-to) Compares this object with the specified object for order. Returns zero if this object is equal to the specified [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other) object, a negative number if it's less than [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other), or a positive number if it's greater than [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other). ``` infix fun <T> Comparable<T>.compareTo(other: T): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [rangeTo](../../kotlin.ranges/range-to) Creates a range from this [Comparable](../../kotlin/-comparable/index#kotlin.Comparable) value to the specified [that](../../kotlin.ranges/range-to#kotlin.ranges%24rangeTo(kotlin.ranges.rangeTo.T,%20kotlin.ranges.rangeTo.T)/that) value. ``` operator fun <T : Comparable<T>> T.rangeTo(     that: T ): ClosedRange<T> ``` **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) #### [rangeUntil](../../kotlin.ranges/range-until) Creates an open-ended range from this [Comparable](../../kotlin/-comparable/index#kotlin.Comparable) value to the specified [that](../../kotlin.ranges/range-until#kotlin.ranges%24rangeUntil(kotlin.ranges.rangeUntil.T,%20kotlin.ranges.rangeUntil.T)/that) value. ``` operator fun <T : Comparable<T>> T.rangeUntil(     that: T ): OpenEndRange<T> ``` Inheritors ---------- **Platform and version requirements:** JVM (1.0), JS (1.0) #### [COMBINING\_SPACING\_MARK](-c-o-m-b-i-n-i-n-g_-s-p-a-c-i-n-g_-m-a-r-k) General category "Mc" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [CONNECTOR\_PUNCTUATION](-c-o-n-n-e-c-t-o-r_-p-u-n-c-t-u-a-t-i-o-n) General category "Pc" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [CONTROL](-c-o-n-t-r-o-l) General category "Cc" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [CURRENCY\_SYMBOL](-c-u-r-r-e-n-c-y_-s-y-m-b-o-l) General category "Sc" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [DASH\_PUNCTUATION](-d-a-s-h_-p-u-n-c-t-u-a-t-i-o-n) General category "Pd" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [DECIMAL\_DIGIT\_NUMBER](-d-e-c-i-m-a-l_-d-i-g-i-t_-n-u-m-b-e-r) General category "Nd" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [ENCLOSING\_MARK](-e-n-c-l-o-s-i-n-g_-m-a-r-k) General category "Me" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [END\_PUNCTUATION](-e-n-d_-p-u-n-c-t-u-a-t-i-o-n) General category "Pe" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [FINAL\_QUOTE\_PUNCTUATION](-f-i-n-a-l_-q-u-o-t-e_-p-u-n-c-t-u-a-t-i-o-n) General category "Pf" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [FORMAT](-f-o-r-m-a-t) General category "Cf" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [INITIAL\_QUOTE\_PUNCTUATION](-i-n-i-t-i-a-l_-q-u-o-t-e_-p-u-n-c-t-u-a-t-i-o-n) General category "Pi" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [LETTER\_NUMBER](-l-e-t-t-e-r_-n-u-m-b-e-r) General category "Nl" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [LINE\_SEPARATOR](-l-i-n-e_-s-e-p-a-r-a-t-o-r) General category "Zl" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [LOWERCASE\_LETTER](-l-o-w-e-r-c-a-s-e_-l-e-t-t-e-r) General category "Ll" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [MATH\_SYMBOL](-m-a-t-h_-s-y-m-b-o-l) General category "Sm" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [MODIFIER\_LETTER](-m-o-d-i-f-i-e-r_-l-e-t-t-e-r) General category "Lm" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [MODIFIER\_SYMBOL](-m-o-d-i-f-i-e-r_-s-y-m-b-o-l) General category "Sk" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [NON\_SPACING\_MARK](-n-o-n_-s-p-a-c-i-n-g_-m-a-r-k) General category "Mn" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [OTHER\_LETTER](-o-t-h-e-r_-l-e-t-t-e-r) General category "Lo" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [OTHER\_NUMBER](-o-t-h-e-r_-n-u-m-b-e-r) General category "No" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [OTHER\_PUNCTUATION](-o-t-h-e-r_-p-u-n-c-t-u-a-t-i-o-n) General category "Po" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [OTHER\_SYMBOL](-o-t-h-e-r_-s-y-m-b-o-l) General category "So" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [PARAGRAPH\_SEPARATOR](-p-a-r-a-g-r-a-p-h_-s-e-p-a-r-a-t-o-r) General category "Zp" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [PRIVATE\_USE](-p-r-i-v-a-t-e_-u-s-e) General category "Co" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [SPACE\_SEPARATOR](-s-p-a-c-e_-s-e-p-a-r-a-t-o-r) General category "Zs" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [START\_PUNCTUATION](-s-t-a-r-t_-p-u-n-c-t-u-a-t-i-o-n) General category "Ps" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [SURROGATE](-s-u-r-r-o-g-a-t-e) General category "Cs" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [TITLECASE\_LETTER](-t-i-t-l-e-c-a-s-e_-l-e-t-t-e-r) General category "Lt" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [UNASSIGNED](-u-n-a-s-s-i-g-n-e-d) General category "Cn" in the Unicode specification. **Platform and version requirements:** JVM (1.0), JS (1.0) #### [UPPERCASE\_LETTER](-u-p-p-e-r-c-a-s-e_-l-e-t-t-e-r) General category "Lu" in the Unicode specification.
programming_docs
kotlin CONTROL CONTROL ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [CONTROL](-c-o-n-t-r-o-l) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` CONTROL ``` General category "Cc" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin UPPERCASE_LETTER UPPERCASE\_LETTER ================= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [UPPERCASE\_LETTER](-u-p-p-e-r-c-a-s-e_-l-e-t-t-e-r) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` UPPERCASE_LETTER ``` General category "Lu" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin LINE_SEPARATOR LINE\_SEPARATOR =============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [LINE\_SEPARATOR](-l-i-n-e_-s-e-p-a-r-a-t-o-r) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` LINE_SEPARATOR ``` General category "Zl" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin SPACE_SEPARATOR SPACE\_SEPARATOR ================ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [SPACE\_SEPARATOR](-s-p-a-c-e_-s-e-p-a-r-a-t-o-r) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` SPACE_SEPARATOR ``` General category "Zs" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin TITLECASE_LETTER TITLECASE\_LETTER ================= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [TITLECASE\_LETTER](-t-i-t-l-e-c-a-s-e_-l-e-t-t-e-r) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` TITLECASE_LETTER ``` General category "Lt" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin MODIFIER_SYMBOL MODIFIER\_SYMBOL ================ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [MODIFIER\_SYMBOL](-m-o-d-i-f-i-e-r_-s-y-m-b-o-l) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` MODIFIER_SYMBOL ``` General category "Sk" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin MATH_SYMBOL MATH\_SYMBOL ============ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [MATH\_SYMBOL](-m-a-t-h_-s-y-m-b-o-l) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` MATH_SYMBOL ``` General category "Sm" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin OTHER_PUNCTUATION OTHER\_PUNCTUATION ================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [OTHER\_PUNCTUATION](-o-t-h-e-r_-p-u-n-c-t-u-a-t-i-o-n) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` OTHER_PUNCTUATION ``` General category "Po" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin FORMAT FORMAT ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [FORMAT](-f-o-r-m-a-t) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` FORMAT ``` General category "Cf" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin CONNECTOR_PUNCTUATION CONNECTOR\_PUNCTUATION ====================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [CONNECTOR\_PUNCTUATION](-c-o-n-n-e-c-t-o-r_-p-u-n-c-t-u-a-t-i-o-n) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` CONNECTOR_PUNCTUATION ``` General category "Pc" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin DASH_PUNCTUATION DASH\_PUNCTUATION ================= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [DASH\_PUNCTUATION](-d-a-s-h_-p-u-n-c-t-u-a-t-i-o-n) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` DASH_PUNCTUATION ``` General category "Pd" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin OTHER_LETTER OTHER\_LETTER ============= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [OTHER\_LETTER](-o-t-h-e-r_-l-e-t-t-e-r) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` OTHER_LETTER ``` General category "Lo" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin valueOf valueOf ======= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [valueOf](value-of) **Platform and version requirements:** JVM (1.0) ``` fun valueOf(category: Int): CharCategory ``` Returns the [CharCategory](index#kotlin.text.CharCategory) corresponding to the specified [category](value-of#kotlin.text.CharCategory.Companion%24valueOf(kotlin.Int)/category) that represents a Java general category constant. Exceptions ---------- `IllegalArgumentException` - if the [category](value-of#kotlin.text.CharCategory.Companion%24valueOf(kotlin.Int)/category) does not represent a Java general category constant. kotlin DECIMAL_DIGIT_NUMBER DECIMAL\_DIGIT\_NUMBER ====================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [DECIMAL\_DIGIT\_NUMBER](-d-e-c-i-m-a-l_-d-i-g-i-t_-n-u-m-b-e-r) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` DECIMAL_DIGIT_NUMBER ``` General category "Nd" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin OTHER_NUMBER OTHER\_NUMBER ============= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [OTHER\_NUMBER](-o-t-h-e-r_-n-u-m-b-e-r) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` OTHER_NUMBER ``` General category "No" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin ENCLOSING_MARK ENCLOSING\_MARK =============== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [ENCLOSING\_MARK](-e-n-c-l-o-s-i-n-g_-m-a-r-k) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` ENCLOSING_MARK ``` General category "Me" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / <value> **Platform and version requirements:** JVM (1.0) ``` val value: Int ``` kotlin code code ==== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / <code> **Platform and version requirements:** JVM (1.0), JS (1.1) ``` val code: String ``` Two-letter code of this general category in the Unicode specification. kotlin UNASSIGNED UNASSIGNED ========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [UNASSIGNED](-u-n-a-s-s-i-g-n-e-d) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` UNASSIGNED ``` General category "Cn" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin FINAL_QUOTE_PUNCTUATION FINAL\_QUOTE\_PUNCTUATION ========================= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [FINAL\_QUOTE\_PUNCTUATION](-f-i-n-a-l_-q-u-o-t-e_-p-u-n-c-t-u-a-t-i-o-n) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` FINAL_QUOTE_PUNCTUATION ``` General category "Pf" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin COMBINING_SPACING_MARK COMBINING\_SPACING\_MARK ======================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [COMBINING\_SPACING\_MARK](-c-o-m-b-i-n-i-n-g_-s-p-a-c-i-n-g_-m-a-r-k) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` COMBINING_SPACING_MARK ``` General category "Mc" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin SURROGATE SURROGATE ========= [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [SURROGATE](-s-u-r-r-o-g-a-t-e) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` SURROGATE ``` General category "Cs" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin INITIAL_QUOTE_PUNCTUATION INITIAL\_QUOTE\_PUNCTUATION =========================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [INITIAL\_QUOTE\_PUNCTUATION](-i-n-i-t-i-a-l_-q-u-o-t-e_-p-u-n-c-t-u-a-t-i-o-n) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` INITIAL_QUOTE_PUNCTUATION ``` General category "Pi" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin MODIFIER_LETTER MODIFIER\_LETTER ================ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [MODIFIER\_LETTER](-m-o-d-i-f-i-e-r_-l-e-t-t-e-r) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` MODIFIER_LETTER ``` General category "Lm" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin END_PUNCTUATION END\_PUNCTUATION ================ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [CharCategory](index) / [END\_PUNCTUATION](-e-n-d_-p-u-n-c-t-u-a-t-i-o-n) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` END_PUNCTUATION ``` General category "Pe" in the Unicode specification. Inherited Properties -------------------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: Int ``` kotlin appendln appendln ======== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.lang.Appendable](index) / <appendln> **Platform and version requirements:** JVM (1.0) ``` fun Appendable.appendln(): Appendable ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. Appends a line separator to this Appendable. **Platform and version requirements:** JVM (1.0) ``` fun Appendable.appendln(value: CharSequence?): Appendable ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. ``` fun Appendable.appendln(value: Char): Appendable ``` **Deprecated:** Use appendLine instead. Note that the new method always appends the line feed character '\\n' regardless of the system line separator. Appends value to the given Appendable and line separator after it. kotlin Extensions for java.lang.Appendable Extensions for java.lang.Appendable =================================== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [java.lang.Appendable](index) **Platform and version requirements:** JVM (1.0) #### <appendln> Appends a line separator to this Appendable. ``` fun Appendable.appendln(): Appendable ``` Appends value to the given Appendable and line separator after it. ``` fun Appendable.appendln(value: CharSequence?): Appendable ``` ``` fun Appendable.appendln(value: Char): Appendable ``` kotlin groupValues groupValues =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchResult](index) / [groupValues](group-values) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract val groupValues: List<String> ``` A list of matched indexed group values. This list has size of `groupCount + 1` where `groupCount` is the count of groups in the regular expression. Groups are indexed from 1 to `groupCount` and group with the index 0 corresponds to the entire match. If the group in the regular expression is optional and there were no match captured by that group, corresponding item in [groupValues](group-values) is an empty string. ``` fun main(args: Array<String>) { //sampleStart val inputString = "John 9731879" val match = Regex("(\\w+) (\\d+)").find(inputString)!! val (name, phone) = match.destructured println(name) // John // value of the first group matched by \w+ println(phone) // 9731879 // value of the second group matched by \d+ // group with the zero index is the whole substring matched by the regular expression println(match.groupValues) // [John 9731879, John, 9731879] val numberedGroupValues = match.destructured.toList() // destructured group values only contain values of the groups, excluding the zeroth group. println(numberedGroupValues) // [John, 9731879] //sampleEnd } ``` kotlin MatchResult MatchResult =========== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchResult](index) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` interface MatchResult ``` Represents the results from a single regular expression match. Types ----- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [Destructured](-destructured/index) Provides components for destructuring assignment of group values. ``` class Destructured ``` Properties ---------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <destructured> An instance of [MatchResult.Destructured](-destructured/index) wrapper providing components for destructuring assignment of group values. ``` open val destructured: Destructured ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <groups> A collection of groups matched by the regular expression. ``` abstract val groups: MatchGroupCollection ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [groupValues](group-values) A list of matched indexed group values. ``` abstract val groupValues: List<String> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <range> The range of indices in the original string where match was captured. ``` abstract val range: IntRange ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <value> The substring from the input string captured by this match. ``` abstract val value: String ``` Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <next> Returns a new [MatchResult](index) with the results for the next match, starting at the position at which the last match ended (at the character after the last matched character). ``` abstract fun next(): MatchResult? ``` kotlin groups groups ====== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchResult](index) / <groups> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract val groups: MatchGroupCollection ``` A collection of groups matched by the regular expression. This collection has size of `groupCount + 1` where `groupCount` is the count of groups in the regular expression. Groups are indexed from 1 to `groupCount` and group with the index 0 corresponds to the entire match. kotlin next next ==== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchResult](index) / <next> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract fun next(): MatchResult? ``` Returns a new [MatchResult](index) with the results for the next match, starting at the position at which the last match ended (at the character after the last matched character). kotlin destructured destructured ============ [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchResult](index) / <destructured> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open val destructured: Destructured ``` An instance of [MatchResult.Destructured](-destructured/index) wrapper providing components for destructuring assignment of group values. component1 corresponds to the value of the first group, component2 — of the second, and so on. ``` fun main(args: Array<String>) { //sampleStart val inputString = "John 9731879" val match = Regex("(\\w+) (\\d+)").find(inputString)!! val (name, phone) = match.destructured println(name) // John // value of the first group matched by \w+ println(phone) // 9731879 // value of the second group matched by \d+ // group with the zero index is the whole substring matched by the regular expression println(match.groupValues) // [John 9731879, John, 9731879] val numberedGroupValues = match.destructured.toList() // destructured group values only contain values of the groups, excluding the zeroth group. println(numberedGroupValues) // [John, 9731879] //sampleEnd } ``` kotlin range range ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchResult](index) / <range> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract val range: IntRange ``` The range of indices in the original string where match was captured. kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.text](../index) / [MatchResult](index) / <value> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract val value: String ``` The substring from the input string captured by this match. kotlin component7 component7 ========== [kotlin-stdlib](../../../../../../../index) / [kotlin.text](../../index) / [MatchResult](../index) / [Destructured](index) / <component7> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun component7(): String ```
programming_docs
kotlin component10 component10 =========== [kotlin-stdlib](../../../../../../../index) / [kotlin.text](../../index) / [MatchResult](../index) / [Destructured](index) / <component10> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun component10(): String ``` kotlin toList toList ====== [kotlin-stdlib](../../../../../../../index) / [kotlin.text](../../index) / [MatchResult](../index) / [Destructured](index) / [toList](to-list) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun toList(): List<String> ``` Returns destructured group values as a list of strings. First value in the returned list corresponds to the value of the first group, and so on. ``` fun main(args: Array<String>) { //sampleStart val inputString = "John 9731879" val match = Regex("(\\w+) (\\d+)").find(inputString)!! val (name, phone) = match.destructured println(name) // John // value of the first group matched by \w+ println(phone) // 9731879 // value of the second group matched by \d+ // group with the zero index is the whole substring matched by the regular expression println(match.groupValues) // [John 9731879, John, 9731879] val numberedGroupValues = match.destructured.toList() // destructured group values only contain values of the groups, excluding the zeroth group. println(numberedGroupValues) // [John, 9731879] //sampleEnd } ``` kotlin Destructured Destructured ============ [kotlin-stdlib](../../../../../../../index) / [kotlin.text](../../index) / [MatchResult](../index) / [Destructured](index) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` class Destructured ``` Provides components for destructuring assignment of group values. <component1> corresponds to the value of the first group, <component2> — of the second, and so on. If the group in the regular expression is optional and there were no match captured by that group, corresponding component value is an empty string. ``` fun main(args: Array<String>) { //sampleStart val inputString = "John 9731879" val match = Regex("(\\w+) (\\d+)").find(inputString)!! val (name, phone) = match.destructured println(name) // John // value of the first group matched by \w+ println(phone) // 9731879 // value of the second group matched by \d+ // group with the zero index is the whole substring matched by the regular expression println(match.groupValues) // [John 9731879, John, 9731879] val numberedGroupValues = match.destructured.toList() // destructured group values only contain values of the groups, excluding the zeroth group. println(numberedGroupValues) // [John, 9731879] //sampleEnd } ``` Properties ---------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <match> ``` val match: MatchResult ``` Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <component1> ``` operator fun component1(): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <component10> ``` operator fun component10(): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <component2> ``` operator fun component2(): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <component3> ``` operator fun component3(): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <component4> ``` operator fun component4(): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <component5> ``` operator fun component5(): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <component6> ``` operator fun component6(): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <component7> ``` operator fun component7(): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <component8> ``` operator fun component8(): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <component9> ``` operator fun component9(): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toList](to-list) Returns destructured group values as a list of strings. First value in the returned list corresponds to the value of the first group, and so on. ``` fun toList(): List<String> ``` kotlin component6 component6 ========== [kotlin-stdlib](../../../../../../../index) / [kotlin.text](../../index) / [MatchResult](../index) / [Destructured](index) / <component6> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun component6(): String ``` kotlin component1 component1 ========== [kotlin-stdlib](../../../../../../../index) / [kotlin.text](../../index) / [MatchResult](../index) / [Destructured](index) / <component1> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun component1(): String ``` kotlin component3 component3 ========== [kotlin-stdlib](../../../../../../../index) / [kotlin.text](../../index) / [MatchResult](../index) / [Destructured](index) / <component3> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun component3(): String ``` kotlin match match ===== [kotlin-stdlib](../../../../../../../index) / [kotlin.text](../../index) / [MatchResult](../index) / [Destructured](index) / <match> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` val match: MatchResult ``` kotlin component2 component2 ========== [kotlin-stdlib](../../../../../../../index) / [kotlin.text](../../index) / [MatchResult](../index) / [Destructured](index) / <component2> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun component2(): String ``` kotlin component5 component5 ========== [kotlin-stdlib](../../../../../../../index) / [kotlin.text](../../index) / [MatchResult](../index) / [Destructured](index) / <component5> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun component5(): String ``` kotlin component9 component9 ========== [kotlin-stdlib](../../../../../../../index) / [kotlin.text](../../index) / [MatchResult](../index) / [Destructured](index) / <component9> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun component9(): String ``` kotlin component8 component8 ========== [kotlin-stdlib](../../../../../../../index) / [kotlin.text](../../index) / [MatchResult](../index) / [Destructured](index) / <component8> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun component8(): String ``` kotlin component4 component4 ========== [kotlin-stdlib](../../../../../../../index) / [kotlin.text](../../index) / [MatchResult](../index) / [Destructured](index) / <component4> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun component4(): String ``` kotlin COROUTINE_SUSPENDED COROUTINE\_SUSPENDED ==================== [kotlin-stdlib](../../../../../index) / [kotlin.coroutines.intrinsics](index) / [COROUTINE\_SUSPENDED](-c-o-r-o-u-t-i-n-e_-s-u-s-p-e-n-d-e-d) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` val COROUTINE_SUSPENDED: Any ``` This value is used as a return value of [suspendCoroutineUninterceptedOrReturn](suspend-coroutine-unintercepted-or-return) `block` argument to state that the execution was suspended and will not return any result immediately. **Note: this value should not be used in general code.** Using it outside of the context of `suspendCoroutineUninterceptedOrReturn` function return value (including, but not limited to, storing this value in other properties, returning it from other functions, etc) can lead to unspecified behavior of the code. kotlin Package kotlin.coroutines.intrinsics Package kotlin.coroutines.intrinsics ==================================== [kotlin-stdlib](../../../../../index) / [kotlin.coroutines.intrinsics](index) Low-level building blocks for libraries that provide coroutine-based APIs. Properties ---------- **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [COROUTINE\_SUSPENDED](-c-o-r-o-u-t-i-n-e_-s-u-s-p-e-n-d-e-d) This value is used as a return value of [suspendCoroutineUninterceptedOrReturn](suspend-coroutine-unintercepted-or-return) `block` argument to state that the execution was suspended and will not return any result immediately. ``` val COROUTINE_SUSPENDED: Any ``` Functions --------- **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [createCoroutineUnintercepted](create-coroutine-unintercepted) Creates unintercepted coroutine without receiver and with result type [T](create-coroutine-unintercepted#T). This function creates a new, fresh instance of suspendable computation every time it is invoked. ``` fun <T> (suspend () -> T).createCoroutineUnintercepted(     completion: Continuation<T> ): Continuation<Unit> ``` Creates unintercepted coroutine with receiver type [R](create-coroutine-unintercepted#R) and result type [T](create-coroutine-unintercepted#T). This function creates a new, fresh instance of suspendable computation every time it is invoked. ``` fun <R, T> (suspend R.() -> T).createCoroutineUnintercepted(     receiver: R,     completion: Continuation<T> ): Continuation<Unit> ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### <intercepted> Intercepts this continuation with [ContinuationInterceptor](../kotlin.coroutines/-continuation-interceptor/index). ``` fun <T> Continuation<T>.intercepted(): Continuation<T> ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [startCoroutineUninterceptedOrReturn](start-coroutine-unintercepted-or-return) Starts an unintercepted coroutine without a receiver and with result type [T](start-coroutine-unintercepted-or-return#T) and executes it until its first suspension. Returns the result of the coroutine or throws its exception if it does not suspend or [COROUTINE\_SUSPENDED](-c-o-r-o-u-t-i-n-e_-s-u-s-p-e-n-d-e-d) if it suspends. In the latter case, the [completion](start-coroutine-unintercepted-or-return#kotlin.coroutines.intrinsics%24startCoroutineUninterceptedOrReturn(kotlin.coroutines.SuspendFunction0((kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.T)),%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.T)))/completion) continuation is invoked when the coroutine completes with a result or an exception. ``` fun <T> (suspend () -> T).startCoroutineUninterceptedOrReturn(     completion: Continuation<T> ): Any? ``` Starts an unintercepted coroutine with receiver type [R](start-coroutine-unintercepted-or-return#R) and result type [T](start-coroutine-unintercepted-or-return#T) and executes it until its first suspension. Returns the result of the coroutine or throws its exception if it does not suspend or [COROUTINE\_SUSPENDED](-c-o-r-o-u-t-i-n-e_-s-u-s-p-e-n-d-e-d) if it suspends. In the latter case, the [completion](start-coroutine-unintercepted-or-return#kotlin.coroutines.intrinsics%24startCoroutineUninterceptedOrReturn(kotlin.coroutines.SuspendFunction1((kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.R,%20kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.T)),%20kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.R,%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.T)))/completion) continuation is invoked when the coroutine completes with a result or an exception. ``` fun <R, T> (suspend R.() -> T).startCoroutineUninterceptedOrReturn(     receiver: R,     completion: Continuation<T> ): Any? ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [suspendCoroutineUninterceptedOrReturn](suspend-coroutine-unintercepted-or-return) Obtains the current continuation instance inside suspend functions and either suspends currently running coroutine or returns result immediately without suspension. ``` suspend fun <T> suspendCoroutineUninterceptedOrReturn(     block: (Continuation<T>) -> Any? ): T ``` kotlin intercepted intercepted =========== [kotlin-stdlib](../../../../../index) / [kotlin.coroutines.intrinsics](index) / <intercepted> **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` fun <T> Continuation<T>.intercepted(): Continuation<T> ``` ##### For Common, JS, Native Intercepts this continuation with [ContinuationInterceptor](../kotlin.coroutines/-continuation-interceptor/index). This function shall be used on the immediate result of [createCoroutineUnintercepted](create-coroutine-unintercepted#kotlin.coroutines.intrinsics%24createCoroutineUnintercepted(kotlin.coroutines.SuspendFunction0((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)),%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)))) or [suspendCoroutineUninterceptedOrReturn](suspend-coroutine-unintercepted-or-return), in which case it checks for [ContinuationInterceptor](../kotlin.coroutines/-continuation-interceptor/index) in the continuation's [context](../kotlin.coroutines/-continuation/context), invokes [ContinuationInterceptor.interceptContinuation](../kotlin.coroutines/-continuation-interceptor/intercept-continuation), caches and returns the result. If this function is invoked on other [Continuation](../kotlin.coroutines/-continuation/index) instances it returns `this` continuation unchanged. ##### For JVM Intercepts this continuation with ContinuationInterceptor. This function shall be used on the immediate result of [createCoroutineUnintercepted](create-coroutine-unintercepted#kotlin.coroutines.intrinsics%24createCoroutineUnintercepted(kotlin.coroutines.SuspendFunction0((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)),%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)))) or suspendCoroutineUninterceptedOrReturn, in which case it checks for ContinuationInterceptor in the continuation's context, invokes ContinuationInterceptor.interceptContinuation, caches and returns the result. If this function is invoked on other Continuation instances it returns `this` continuation unchanged. kotlin createCoroutineUnintercepted createCoroutineUnintercepted ============================ [kotlin-stdlib](../../../../../index) / [kotlin.coroutines.intrinsics](index) / [createCoroutineUnintercepted](create-coroutine-unintercepted) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` fun <T> (suspend () -> T).createCoroutineUnintercepted(     completion: Continuation<T> ): Continuation<Unit> ``` Creates unintercepted coroutine without receiver and with result type [T](create-coroutine-unintercepted#T). This function creates a new, fresh instance of suspendable computation every time it is invoked. To start executing the created coroutine, invoke `resume(Unit)` on the returned Continuation instance. The [completion](create-coroutine-unintercepted#kotlin.coroutines.intrinsics%24createCoroutineUnintercepted(kotlin.coroutines.SuspendFunction0((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)),%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)))/completion) continuation is invoked when coroutine completes with result or exception. This function returns unintercepted continuation. Invocation of `resume(Unit)` starts coroutine immediately in the invoker's call stack without going through the ContinuationInterceptor that might be present in the completion's CoroutineContext. It is the invoker's responsibility to ensure that a proper invocation context is established. Note that [completion](create-coroutine-unintercepted#kotlin.coroutines.intrinsics%24createCoroutineUnintercepted(kotlin.coroutines.SuspendFunction0((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)),%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)))/completion) of this function may get invoked in an arbitrary context. [Continuation.intercepted](intercepted#kotlin.coroutines.intrinsics%24intercepted(kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.intercepted.T)))) can be used to acquire the intercepted continuation. Invocation of `resume(Unit)` on intercepted continuation guarantees that execution of both the coroutine and [completion](create-coroutine-unintercepted#kotlin.coroutines.intrinsics%24createCoroutineUnintercepted(kotlin.coroutines.SuspendFunction0((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)),%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)))/completion) happens in the invocation context established by ContinuationInterceptor. Repeated invocation of any resume function on the resulting continuation corrupts the state machine of the coroutine and may result in arbitrary behaviour or exception. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` fun <R, T> (suspend R.() -> T).createCoroutineUnintercepted(     receiver: R,     completion: Continuation<T> ): Continuation<Unit> ``` Creates unintercepted coroutine with receiver type [R](create-coroutine-unintercepted#R) and result type [T](create-coroutine-unintercepted#T). This function creates a new, fresh instance of suspendable computation every time it is invoked. To start executing the created coroutine, invoke `resume(Unit)` on the returned Continuation instance. The [completion](create-coroutine-unintercepted#kotlin.coroutines.intrinsics%24createCoroutineUnintercepted(kotlin.coroutines.SuspendFunction1((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.R,%20kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)),%20kotlin.coroutines.intrinsics.createCoroutineUnintercepted.R,%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)))/completion) continuation is invoked when coroutine completes with result or exception. This function returns unintercepted continuation. Invocation of `resume(Unit)` starts coroutine immediately in the invoker's call stack without going through the ContinuationInterceptor that might be present in the completion's CoroutineContext. It is the invoker's responsibility to ensure that a proper invocation context is established. Note that [completion](create-coroutine-unintercepted#kotlin.coroutines.intrinsics%24createCoroutineUnintercepted(kotlin.coroutines.SuspendFunction1((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.R,%20kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)),%20kotlin.coroutines.intrinsics.createCoroutineUnintercepted.R,%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)))/completion) of this function may get invoked in an arbitrary context. [Continuation.intercepted](intercepted#kotlin.coroutines.intrinsics%24intercepted(kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.intercepted.T)))) can be used to acquire the intercepted continuation. Invocation of `resume(Unit)` on intercepted continuation guarantees that execution of both the coroutine and [completion](create-coroutine-unintercepted#kotlin.coroutines.intrinsics%24createCoroutineUnintercepted(kotlin.coroutines.SuspendFunction1((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.R,%20kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)),%20kotlin.coroutines.intrinsics.createCoroutineUnintercepted.R,%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.createCoroutineUnintercepted.T)))/completion) happens in the invocation context established by ContinuationInterceptor. Repeated invocation of any resume function on the resulting continuation corrupts the state machine of the coroutine and may result in arbitrary behaviour or exception.
programming_docs
kotlin startCoroutineUninterceptedOrReturn startCoroutineUninterceptedOrReturn =================================== [kotlin-stdlib](../../../../../index) / [kotlin.coroutines.intrinsics](index) / [startCoroutineUninterceptedOrReturn](start-coroutine-unintercepted-or-return) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` fun <T> (suspend () -> T).startCoroutineUninterceptedOrReturn(     completion: Continuation<T> ): Any? ``` ##### For Common, JS, Native Starts an unintercepted coroutine without a receiver and with result type [T](start-coroutine-unintercepted-or-return#T) and executes it until its first suspension. Returns the result of the coroutine or throws its exception if it does not suspend or [COROUTINE\_SUSPENDED](-c-o-r-o-u-t-i-n-e_-s-u-s-p-e-n-d-e-d) if it suspends. In the latter case, the [completion](start-coroutine-unintercepted-or-return#kotlin.coroutines.intrinsics%24startCoroutineUninterceptedOrReturn(kotlin.coroutines.SuspendFunction0((kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.T)),%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.T)))/completion) continuation is invoked when the coroutine completes with a result or an exception. The coroutine is started directly in the invoker's thread without going through the [ContinuationInterceptor](../kotlin.coroutines/-continuation-interceptor/index) that might be present in the completion's [CoroutineContext](../kotlin.coroutines/-coroutine-context/index). It is the invoker's responsibility to ensure that a proper invocation context is established. This function is designed to be used from inside of [suspendCoroutineUninterceptedOrReturn](suspend-coroutine-unintercepted-or-return) to resume the execution of the suspended coroutine using a reference to the suspending function. ##### For JVM Starts an unintercepted coroutine without a receiver and with result type [T](start-coroutine-unintercepted-or-return#T) and executes it until its first suspension. Returns the result of the coroutine or throws its exception if it does not suspend or COROUTINE\_SUSPENDED if it suspends. In the latter case, the [completion](start-coroutine-unintercepted-or-return#kotlin.coroutines.intrinsics%24startCoroutineUninterceptedOrReturn(kotlin.coroutines.SuspendFunction0((kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.T)),%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.T)))/completion) continuation is invoked when the coroutine completes with a result or an exception. The coroutine is started directly in the invoker's thread without going through the ContinuationInterceptor that might be present in the completion's CoroutineContext. It is the invoker's responsibility to ensure that a proper invocation context is established. This function is designed to be used from inside of suspendCoroutineUninterceptedOrReturn to resume the execution of the suspended coroutine using a reference to the suspending function. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` fun <R, T> (suspend R.() -> T).startCoroutineUninterceptedOrReturn(     receiver: R,     completion: Continuation<T> ): Any? ``` ##### For Common, JS, Native Starts an unintercepted coroutine with receiver type [R](start-coroutine-unintercepted-or-return#R) and result type [T](start-coroutine-unintercepted-or-return#T) and executes it until its first suspension. Returns the result of the coroutine or throws its exception if it does not suspend or [COROUTINE\_SUSPENDED](-c-o-r-o-u-t-i-n-e_-s-u-s-p-e-n-d-e-d) if it suspends. In the latter case, the [completion](start-coroutine-unintercepted-or-return#kotlin.coroutines.intrinsics%24startCoroutineUninterceptedOrReturn(kotlin.coroutines.SuspendFunction1((kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.R,%20kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.T)),%20kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.R,%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.T)))/completion) continuation is invoked when the coroutine completes with a result or an exception. The coroutine is started directly in the invoker's thread without going through the [ContinuationInterceptor](../kotlin.coroutines/-continuation-interceptor/index) that might be present in the completion's [CoroutineContext](../kotlin.coroutines/-coroutine-context/index). It is the invoker's responsibility to ensure that a proper invocation context is established. This function is designed to be used from inside of [suspendCoroutineUninterceptedOrReturn](suspend-coroutine-unintercepted-or-return) to resume the execution of the suspended coroutine using a reference to the suspending function. ##### For JVM Starts an unintercepted coroutine with receiver type [R](start-coroutine-unintercepted-or-return#R) and result type [T](start-coroutine-unintercepted-or-return#T) and executes it until its first suspension. Returns the result of the coroutine or throws its exception if it does not suspend or COROUTINE\_SUSPENDED if it suspends. In the latter case, the [completion](start-coroutine-unintercepted-or-return#kotlin.coroutines.intrinsics%24startCoroutineUninterceptedOrReturn(kotlin.coroutines.SuspendFunction1((kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.R,%20kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.T)),%20kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.R,%20kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn.T)))/completion) continuation is invoked when the coroutine completes with a result or an exception. The coroutine is started directly in the invoker's thread without going through the ContinuationInterceptor that might be present in the completion's CoroutineContext. It is the invoker's responsibility to ensure that a proper invocation context is established. This function is designed to be used from inside of suspendCoroutineUninterceptedOrReturn to resume the execution of the suspended coroutine using a reference to the suspending function. kotlin suspendCoroutineUninterceptedOrReturn suspendCoroutineUninterceptedOrReturn ===================================== [kotlin-stdlib](../../../../../index) / [kotlin.coroutines.intrinsics](index) / [suspendCoroutineUninterceptedOrReturn](suspend-coroutine-unintercepted-or-return) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` suspend inline fun <T> suspendCoroutineUninterceptedOrReturn(     crossinline block: (Continuation<T>) -> Any? ): T ``` Obtains the current continuation instance inside suspend functions and either suspends currently running coroutine or returns result immediately without suspension. If the [block](suspend-coroutine-unintercepted-or-return#kotlin.coroutines.intrinsics%24suspendCoroutineUninterceptedOrReturn(kotlin.Function1((kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn.T)),%20kotlin.Any?)))/block) returns the special [COROUTINE\_SUSPENDED](-c-o-r-o-u-t-i-n-e_-s-u-s-p-e-n-d-e-d) value, it means that suspend function did suspend the execution and will not return any result immediately. In this case, the [Continuation](../kotlin.coroutines/-continuation/index) provided to the [block](suspend-coroutine-unintercepted-or-return#kotlin.coroutines.intrinsics%24suspendCoroutineUninterceptedOrReturn(kotlin.Function1((kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn.T)),%20kotlin.Any?)))/block) shall be resumed by invoking [Continuation.resumeWith](../kotlin.coroutines/-continuation/resume-with) at some moment in the future when the result becomes available to resume the computation. Otherwise, the return value of the [block](suspend-coroutine-unintercepted-or-return#kotlin.coroutines.intrinsics%24suspendCoroutineUninterceptedOrReturn(kotlin.Function1((kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn.T)),%20kotlin.Any?)))/block) must have a type assignable to [T](suspend-coroutine-unintercepted-or-return#T) and represents the result of this suspend function. It means that the execution was not suspended and the [Continuation](../kotlin.coroutines/-continuation/index) provided to the [block](suspend-coroutine-unintercepted-or-return#kotlin.coroutines.intrinsics%24suspendCoroutineUninterceptedOrReturn(kotlin.Function1((kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn.T)),%20kotlin.Any?)))/block) shall not be invoked. As the result type of the [block](suspend-coroutine-unintercepted-or-return#kotlin.coroutines.intrinsics%24suspendCoroutineUninterceptedOrReturn(kotlin.Function1((kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn.T)),%20kotlin.Any?)))/block) is declared as `Any?` and cannot be correctly type-checked, its proper return type remains on the conscience of the suspend function's author. Invocation of [Continuation.resumeWith](../kotlin.coroutines/-continuation/resume-with) resumes coroutine directly in the invoker's thread without going through the [ContinuationInterceptor](../kotlin.coroutines/-continuation-interceptor/index) that might be present in the coroutine's [CoroutineContext](../kotlin.coroutines/-coroutine-context/index). It is the invoker's responsibility to ensure that a proper invocation context is established. [Continuation.intercepted](intercepted#kotlin.coroutines.intrinsics%24intercepted(kotlin.coroutines.Continuation((kotlin.coroutines.intrinsics.intercepted.T)))) can be used to acquire the intercepted continuation. Note that it is not recommended to call either [Continuation.resume](../kotlin.coroutines/resume) nor [Continuation.resumeWithException](../kotlin.coroutines/resume-with-exception) functions synchronously in the same stackframe where suspension function is run. Use [suspendCoroutine](../kotlin.coroutines/suspend-coroutine) as a safer way to obtain current continuation instance. kotlin readBits readBits ======== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [readBits](read-bits) **Platform and version requirements:** Native (1.3) ``` fun readBits(     ptr: NativePtr,     offset: Long,     size: Int,     signed: Boolean ): Long ``` kotlin cValuesOf cValuesOf ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [cValuesOf](c-values-of) **Platform and version requirements:** Native (1.3) ``` fun cValuesOf(vararg elements: Byte): CValues<ByteVar> ``` Returns sequence of immutable values [CValues](-c-values/index) to pass them to C code. **Platform and version requirements:** Native (1.3) ``` fun cValuesOf(vararg elements: Short): CValues<ShortVar> ``` ``` fun cValuesOf(vararg elements: Int): CValues<IntVar> ``` ``` fun cValuesOf(vararg elements: Long): CValues<LongVar> ``` ``` fun cValuesOf(vararg elements: Float): CValues<FloatVar> ``` ``` fun cValuesOf(vararg elements: Double): CValues<DoubleVar> ``` ``` fun <T : CPointed> cValuesOf(     vararg elements: CPointer<T>? ): CValues<CPointerVar<T>> ``` ``` fun cValuesOf(vararg elements: UByte): CValues<UByteVar> ``` ``` fun cValuesOf(vararg elements: UShort): CValues<UShortVar> ``` ``` fun cValuesOf(vararg elements: UInt): CValues<UIntVar> ``` ``` fun cValuesOf(vararg elements: ULong): CValues<ULongVar> ``` kotlin refTo refTo ===== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [refTo](ref-to) **Platform and version requirements:** Native (1.3) ``` fun ByteArray.refTo(index: Int): CValuesRef<ByteVar> ``` ``` fun String.refTo(index: Int): CValuesRef<COpaque> ``` ``` fun CharArray.refTo(index: Int): CValuesRef<COpaque> ``` ``` fun ShortArray.refTo(index: Int): CValuesRef<ShortVar> ``` ``` fun IntArray.refTo(index: Int): CValuesRef<IntVar> ``` ``` fun LongArray.refTo(index: Int): CValuesRef<LongVar> ``` ``` fun UByteArray.refTo(index: Int): CValuesRef<UByteVar> ``` ``` fun UShortArray.refTo(index: Int): CValuesRef<UShortVar> ``` ``` fun UIntArray.refTo(index: Int): CValuesRef<UIntVar> ``` ``` fun ULongArray.refTo(index: Int): CValuesRef<ULongVar> ``` ``` fun FloatArray.refTo(index: Int): CValuesRef<FloatVar> ``` ``` fun DoubleArray.refTo(index: Int): CValuesRef<DoubleVar> ``` kotlin CreateKStringFromNSString CreateKStringFromNSString ========================= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [CreateKStringFromNSString](-create-k-string-from-n-s-string) **Platform and version requirements:** Native (1.3) ``` fun CreateKStringFromNSString(ptr: NativePtr): String? ``` **Deprecated:** Use plain Kotlin cast of NSString to String kotlin toByte toByte ====== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [toByte](to-byte) **Platform and version requirements:** Native (1.3) ``` fun Boolean.toByte(): Byte ``` kotlin arrayMemberAt arrayMemberAt ============= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [arrayMemberAt](array-member-at) **Platform and version requirements:** Native (1.3) ``` fun <reified T : CVariable> CStructVar.arrayMemberAt(     offset: Long ): CArrayPointer<T> ``` kotlin LongVar LongVar ======= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [LongVar](-long-var) **Platform and version requirements:** Native (1.3) ``` typealias LongVar = LongVarOf<Long> ``` kotlin objc_autoreleasePoolPop objc\_autoreleasePoolPop ======================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [objc\_autoreleasePoolPop](objc_autorelease-pool-pop) **Platform and version requirements:** Native (1.3) ``` fun objc_autoreleasePoolPop(ptr: NativePtr) ``` kotlin zeroValue zeroValue ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [zeroValue](zero-value) **Platform and version requirements:** Native (1.3) ``` fun <T : CVariable> zeroValue(     size: Int,     align: Int ): CValue<T> ``` ``` fun <reified T : CVariable> zeroValue(): CValue<T> ``` kotlin ObjCClassOf ObjCClassOf =========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [ObjCClassOf](-obj-c-class-of) **Platform and version requirements:** Native (1.3) ``` interface ObjCClassOf<T : ObjCObject> : ObjCClass ``` kotlin ObjCObject ObjCObject ========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [ObjCObject](-obj-c-object) **Platform and version requirements:** Native (1.3) ``` interface ObjCObject ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### <reinterpret> ``` fun <T : ObjCObject> ObjCObject.reinterpret(): T ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [ObjCClass](-obj-c-class) ``` interface ObjCClass : ObjCObject ``` **Platform and version requirements:** Native (1.3) #### [ObjCObjectBase](-obj-c-object-base/index) ``` abstract class ObjCObjectBase : ObjCObject ``` **Platform and version requirements:** Native (1.3) #### [ObjCProtocol](-obj-c-protocol) ``` interface ObjCProtocol : ObjCObject ``` kotlin utf32 utf32 ===== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <utf32> **Platform and version requirements:** Native (1.3) ``` val String.utf32: CValues<IntVar> ``` **Return** the value of zero-terminated UTF-32-encoded C string constructed from given [kotlin.String](../kotlin/-string/index#kotlin.String). kotlin bitsToFloat bitsToFloat =========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [bitsToFloat](bits-to-float) **Platform and version requirements:** Native (1.3) ``` fun bitsToFloat(bits: Int): Float ``` kotlin Package kotlinx.cinterop Package kotlinx.cinterop ======================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) Types ----- **Platform and version requirements:** Native (1.3) #### [Arena](-arena/index) ``` class Arena : ArenaBase ``` **Platform and version requirements:** Native (1.3) #### [ArenaBase](-arena-base/index) ``` open class ArenaBase : AutofreeScope ``` **Platform and version requirements:** Native (1.3) #### [AutofreeScope](-autofree-scope/index) ``` abstract class AutofreeScope : DeferScope, NativePlacement ``` **Platform and version requirements:** Native (1.3) #### [BooleanVar](-boolean-var) ``` typealias BooleanVar = BooleanVarOf<Boolean> ``` **Platform and version requirements:** Native (1.3) #### [BooleanVarOf](-boolean-var-of/index) ``` class BooleanVarOf<T : Boolean> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [ByteVar](-byte-var) ``` typealias ByteVar = ByteVarOf<Byte> ``` **Platform and version requirements:** Native (1.3) #### [ByteVarOf](-byte-var-of/index) ``` class ByteVarOf<T : Byte> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [CArrayPointer](-c-array-pointer) ``` typealias CArrayPointer<T> = CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [CArrayPointerVar](-c-array-pointer-var) ``` typealias CArrayPointerVar<T> = CPointerVar<T> ``` **Platform and version requirements:** Native (1.3) #### [CEnum](-c-enum/index) ``` interface CEnum ``` **Platform and version requirements:** Native (1.3) #### [CEnumVar](-c-enum-var/index) ``` abstract class CEnumVar : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [CFunction](-c-function/index) The C function. ``` class CFunction<T : Function<*>> : CPointed ``` **Platform and version requirements:** Native (1.3) #### [COpaque](-c-opaque/index) The [CPointed](-c-pointed/index) without any specified interpretation. ``` abstract class COpaque : CPointed ``` **Platform and version requirements:** Native (1.3) #### [COpaquePointer](-c-opaque-pointer) The pointer with an opaque type. ``` typealias COpaquePointer = CPointer<out CPointed> ``` **Platform and version requirements:** Native (1.3) #### [COpaquePointerVar](-c-opaque-pointer-var) The variable containing a [COpaquePointer](-c-opaque-pointer). ``` typealias COpaquePointerVar = CPointerVarOf<COpaquePointer> ``` **Platform and version requirements:** Native (1.3) #### [CPlusPlusClass](-c-plus-plus-class) ``` interface CPlusPlusClass ``` **Platform and version requirements:** Native (1.3) #### [CPointed](-c-pointed/index) C data or code. ``` abstract class CPointed : NativePointed ``` **Platform and version requirements:** Native (1.3) #### [CPointer](-c-pointer/index) C pointer. ``` class CPointer<T : CPointed> : CValuesRef<T> ``` **Platform and version requirements:** Native (1.3) #### [CPointerVar](-c-pointer-var) The C data variable containing the pointer to `T`. ``` typealias CPointerVar<T> = CPointerVarOf<CPointer<T>> ``` **Platform and version requirements:** Native (1.3) #### [CPointerVarOf](-c-pointer-var-of/index) ``` class CPointerVarOf<T : CPointer<*>> : CVariable ``` **Platform and version requirements:** Native (1.3) #### [CPrimitiveVar](-c-primitive-var/index) The C primitive-typed variable located in memory. ``` sealed class CPrimitiveVar : CVariable ``` **Platform and version requirements:** Native (1.3) #### [CStructVar](-c-struct-var/index) The C struct-typed variable located in memory. ``` abstract class CStructVar : CVariable ``` **Platform and version requirements:** Native (1.3) #### [CValue](-c-value/index) The single immutable C value. It is self-contained and doesn't depend on native memory. ``` abstract class CValue<T : CVariable> : CValues<T> ``` **Platform and version requirements:** Native (1.3) #### [CValues](-c-values/index) The (possibly empty) sequence of immutable C values. It is self-contained and doesn't depend on native memory. ``` abstract class CValues<T : CVariable> : CValuesRef<T> ``` **Platform and version requirements:** Native (1.3) #### [CValuesRef](-c-values-ref/index) Represents a reference to (possibly empty) sequence of C values. It can be either a stable pointer [CPointer](-c-pointer/index) or a sequence of immutable values [CValues](-c-values/index). ``` abstract class CValuesRef<T : CPointed> ``` **Platform and version requirements:** Native (1.3) #### [CVariable](-c-variable/index) The C data variable located in memory. ``` abstract class CVariable : CPointed ``` **Platform and version requirements:** Native (1.3) #### [DeferScope](-defer-scope/index) ``` open class DeferScope ``` **Platform and version requirements:** Native (1.3) #### [DoubleVar](-double-var) ``` typealias DoubleVar = DoubleVarOf<Double> ``` **Platform and version requirements:** Native (1.3) #### [DoubleVarOf](-double-var-of/index) ``` class DoubleVarOf<T : Double> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [FloatVar](-float-var) ``` typealias FloatVar = FloatVarOf<Float> ``` **Platform and version requirements:** Native (1.3) #### [FloatVarOf](-float-var-of/index) ``` class FloatVarOf<T : Float> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [ForeignException](-foreign-exception/index) ``` class ForeignException : Exception ``` **Platform and version requirements:** Native (1.3) #### [IntVar](-int-var) ``` typealias IntVar = IntVarOf<Int> ``` **Platform and version requirements:** Native (1.3) #### [IntVarOf](-int-var-of/index) ``` class IntVarOf<T : Int> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [LongVar](-long-var) ``` typealias LongVar = LongVarOf<Long> ``` **Platform and version requirements:** Native (1.3) #### [LongVarOf](-long-var-of/index) ``` class LongVarOf<T : Long> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [ManagedType](-managed-type/index) ``` abstract class ManagedType<T : CStructVar> ``` **Platform and version requirements:** Native (1.3) #### [MemScope](-mem-scope/index) ``` class MemScope : ArenaBase ``` **Platform and version requirements:** Native (1.3) #### [NativeFreeablePlacement](-native-freeable-placement/index) ``` interface NativeFreeablePlacement : NativePlacement ``` **Platform and version requirements:** Native (1.3) #### [nativeHeap](native-heap/index) ``` object nativeHeap : NativeFreeablePlacement ``` **Platform and version requirements:** Native (1.3) #### [NativePlacement](-native-placement/index) ``` interface NativePlacement ``` **Platform and version requirements:** Native (1.3) #### [NativePointed](-native-pointed/index) The entity which has an associated native pointer. Subtypes are supposed to represent interpretations of the pointed data or code. ``` open class NativePointed ``` **Platform and version requirements:** Native (1.3) #### [NativePtr](-native-ptr) ``` typealias NativePtr = NativePtr ``` **Platform and version requirements:** Native (1.3) #### [ObjCBlockVar](-obj-c-block-var) ``` typealias ObjCBlockVar<T> = ObjCNotImplementedVar<T> ``` **Platform and version requirements:** Native (1.3) #### [ObjCClass](-obj-c-class) ``` interface ObjCClass : ObjCObject ``` **Platform and version requirements:** Native (1.3) #### [ObjCClassOf](-obj-c-class-of) ``` interface ObjCClassOf<T : ObjCObject> : ObjCClass ``` **Platform and version requirements:** Native (1.3) #### [ObjCNotImplementedVar](-obj-c-not-implemented-var/index) ``` class ObjCNotImplementedVar<T> : CVariable ``` **Platform and version requirements:** Native (1.3) #### [ObjCObject](-obj-c-object) ``` interface ObjCObject ``` **Platform and version requirements:** Native (1.3) #### [ObjCObjectBase](-obj-c-object-base/index) ``` abstract class ObjCObjectBase : ObjCObject ``` **Platform and version requirements:** Native (1.3) #### [ObjCObjectBaseMeta](-obj-c-object-base-meta/index) ``` abstract class ObjCObjectBaseMeta :      ObjCObjectBase,     ObjCObjectMeta ``` **Platform and version requirements:** Native (1.3) #### [ObjCObjectMeta](-obj-c-object-meta) ``` typealias ObjCObjectMeta = ObjCClass ``` **Platform and version requirements:** Native (1.3) #### [ObjCObjectVar](-obj-c-object-var/index) ``` class ObjCObjectVar<T> : CVariable ``` **Platform and version requirements:** Native (1.3) #### [ObjCProtocol](-obj-c-protocol) ``` interface ObjCProtocol : ObjCObject ``` **Platform and version requirements:** Native (1.3) #### [ObjCStringVarOf](-obj-c-string-var-of) ``` typealias ObjCStringVarOf<T> = ObjCNotImplementedVar<T> ``` **Platform and version requirements:** Native (1.3) #### [Pinned](-pinned/index) ``` data class Pinned<out T : Any> ``` **Platform and version requirements:** Native (1.3) #### [ShortVar](-short-var) ``` typealias ShortVar = ShortVarOf<Short> ``` **Platform and version requirements:** Native (1.3) #### [ShortVarOf](-short-var-of/index) ``` class ShortVarOf<T : Short> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [SkiaRefCnt](-skia-ref-cnt) ``` interface SkiaRefCnt ``` **Platform and version requirements:** Native (1.3) #### [StableObjPtr](-stable-obj-ptr) ``` typealias StableObjPtr = StableRef<*> ``` **Platform and version requirements:** Native (1.3) #### [StableRef](-stable-ref/index) ``` class StableRef<out T : Any> ``` **Platform and version requirements:** Native (1.3) #### [UByteVar](-u-byte-var) ``` typealias UByteVar = UByteVarOf<UByte> ``` **Platform and version requirements:** Native (1.3) #### [UByteVarOf](-u-byte-var-of/index) ``` class UByteVarOf<T : UByte> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [UIntVar](-u-int-var) ``` typealias UIntVar = UIntVarOf<UInt> ``` **Platform and version requirements:** Native (1.3) #### [UIntVarOf](-u-int-var-of/index) ``` class UIntVarOf<T : UInt> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [ULongVar](-u-long-var) ``` typealias ULongVar = ULongVarOf<ULong> ``` **Platform and version requirements:** Native (1.3) #### [ULongVarOf](-u-long-var-of/index) ``` class ULongVarOf<T : ULong> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [UShortVar](-u-short-var) ``` typealias UShortVar = UShortVarOf<UShort> ``` **Platform and version requirements:** Native (1.3) #### [UShortVarOf](-u-short-var-of/index) ``` class UShortVarOf<T : UShort> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [Vector128Var](-vector128-var) ``` typealias Vector128Var = Vector128VarOf<Vector128> ``` **Platform and version requirements:** Native (1.3) #### [Vector128VarOf](-vector128-var-of/index) ``` class Vector128VarOf<T : Vector128> : CVariable ``` Annotations ----------- **Platform and version requirements:** Native (1.3) #### [ExportObjCClass](-export-obj-c-class/index) Makes Kotlin subclass of Objective-C class visible for runtime lookup after Kotlin `main` function gets invoked. ``` annotation class ExportObjCClass ``` **Platform and version requirements:** Native (1.3) #### [ExternalObjCClass](-external-obj-c-class/index) ``` annotation class ExternalObjCClass ``` **Platform and version requirements:** Native (1.3) #### [InteropStubs](-interop-stubs/index) ``` annotation class InteropStubs ``` **Platform and version requirements:** Native (1.3) #### [ObjCAction](-obj-c-action/index) Makes Kotlin method in Objective-C class accessible through Objective-C dispatch to be used as action sent by control in UIKit or AppKit. ``` annotation class ObjCAction ``` **Platform and version requirements:** Native (1.3) #### [ObjCConstructor](-obj-c-constructor/index) ``` annotation class ObjCConstructor ``` **Platform and version requirements:** Native (1.3) #### [ObjCFactory](-obj-c-factory/index) ``` annotation class ObjCFactory ``` **Platform and version requirements:** Native (1.3) #### [ObjCMethod](-obj-c-method/index) ``` annotation class ObjCMethod ``` **Platform and version requirements:** Native (1.3) #### [ObjCOutlet](-obj-c-outlet/index) Makes Kotlin property in Objective-C class settable through Objective-C dispatch to be used as IB outlet. ``` annotation class ObjCOutlet ``` **Platform and version requirements:** Native (1.3) #### [UnsafeNumber](-unsafe-number/index) Marker for declarations that depend on numeric types of different bit width on at least two platforms. ``` annotation class UnsafeNumber ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <cstr> ``` val String.cstr: CValues<ByteVar> ``` **Platform and version requirements:** Native (1.3) #### [nativeNullPtr](native-null-ptr) ``` val nativeNullPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### <pointed> Returns the corresponding [CPointed](-c-pointed/index). ``` val <T : CPointed> CPointer<T>.pointed: T ``` The code or data pointed by the value of this variable. ``` var <T : CPointed, P : CPointer<T>> CPointerVarOf<P>.pointed: T? ``` **Platform and version requirements:** Native (1.3) #### <ptr> Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` ``` val <T : CStructVar> ManagedType<T>.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [rawValue](raw-value) ``` val CPointer<*>?.rawValue: NativePtr ``` **Platform and version requirements:** Native (1.3) #### <utf16> ``` val String.utf16: CValues<UShortVar> ``` **Platform and version requirements:** Native (1.3) #### <utf32> ``` val String.utf32: CValues<IntVar> ``` **Platform and version requirements:** Native (1.3) #### <utf8> ``` val String.utf8: CValues<ByteVar> ``` **Platform and version requirements:** Native (1.3) #### <value> ``` var <T : Boolean> BooleanVarOf<T>.value: T ``` ``` var <T : Byte> ByteVarOf<T>.value: T ``` ``` var <T : Short> ShortVarOf<T>.value: T ``` ``` var <T : Int> IntVarOf<T>.value: T ``` ``` var <T : Long> LongVarOf<T>.value: T ``` ``` var <T : UByte> UByteVarOf<T>.value: T ``` ``` var <T : UShort> UShortVarOf<T>.value: T ``` ``` var <T : UInt> UIntVarOf<T>.value: T ``` ``` var <T : ULong> ULongVarOf<T>.value: T ``` ``` var <T : Float> FloatVarOf<T>.value: T ``` ``` var <T : Double> DoubleVarOf<T>.value: T ``` ``` var <T : Vector128> Vector128VarOf<T>.value: T ``` ``` var <T> ObjCNotImplementedVar<T>.value: T ``` ``` var <T> ObjCObjectVar<T>.value: T ``` The value of this variable. ``` var <P : CPointer<*>> CPointerVarOf<P>.value: P? ``` **Platform and version requirements:** Native (1.3) #### <wcstr> ``` val String.wcstr: CValues<UShortVar> ``` Functions --------- **Platform and version requirements:** Native (1.3) #### [addressOf](address-of) ``` fun Pinned<ByteArray>.addressOf(     index: Int ): CPointer<ByteVar> ``` ``` fun Pinned<String>.addressOf(index: Int): CPointer<COpaque> ``` ``` fun Pinned<CharArray>.addressOf(     index: Int ): CPointer<COpaque> ``` ``` fun Pinned<ShortArray>.addressOf(     index: Int ): CPointer<ShortVar> ``` ``` fun Pinned<IntArray>.addressOf(index: Int): CPointer<IntVar> ``` ``` fun Pinned<LongArray>.addressOf(     index: Int ): CPointer<LongVar> ``` ``` fun Pinned<UByteArray>.addressOf(     index: Int ): CPointer<UByteVar> ``` ``` fun Pinned<UShortArray>.addressOf(     index: Int ): CPointer<UShortVar> ``` ``` fun Pinned<UIntArray>.addressOf(     index: Int ): CPointer<UIntVar> ``` ``` fun Pinned<ULongArray>.addressOf(     index: Int ): CPointer<ULongVar> ``` ``` fun Pinned<FloatArray>.addressOf(     index: Int ): CPointer<FloatVar> ``` ``` fun Pinned<DoubleArray>.addressOf(     index: Int ): CPointer<DoubleVar> ``` **Platform and version requirements:** Native (1.3) #### [alignOf](align-of) ``` fun <T : CVariable> alignOf(): Int ``` **Platform and version requirements:** Native (1.3) #### <alloc> Allocates variable of given type. ``` fun <T : CVariable> NativePlacement.alloc(): T ``` Allocates variable of given type and initializes it applying given block. ``` fun <T : CVariable> NativePlacement.alloc(     initialize: T.() -> Unit ): T ``` Allocates variable with given value type and initializes it with given value. ``` fun <T : Boolean> NativePlacement.alloc(     value: T ): BooleanVarOf<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArray](alloc-array) Allocates C array of given elements type and length. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int ): CArrayPointer<T> ``` Allocates C array of given elements type and length, and initializes its elements applying given block. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long,     initializer: T.(index: Long) -> Unit ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int,     initializer: T.(index: Int) -> Unit ): CArrayPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOf](alloc-array-of) Allocates C array of given values. ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     vararg elements: T? ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     elements: List<T?> ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun NativePlacement.allocArrayOf(     elements: ByteArray ): CArrayPointer<ByteVar> ``` ``` fun NativePlacement.allocArrayOf(     vararg elements: Float ): CArrayPointer<FloatVar> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOfPointersTo](alloc-array-of-pointers-to) Allocates C array of pointers to given elements. ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     elements: List<T?> ): CArrayPointer<CPointerVar<T>> ``` ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     vararg elements: T? ): CArrayPointer<CPointerVar<T>> ``` **Platform and version requirements:** Native (1.3) #### [allocPointerTo](alloc-pointer-to) ``` fun <T : CPointed> NativePlacement.allocPointerTo(): CPointerVar<T> ``` **Platform and version requirements:** Native (1.3) #### [arrayMemberAt](array-member-at) ``` fun <T : CVariable> CStructVar.arrayMemberAt(     offset: Long ): CArrayPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [asStableRef](as-stable-ref) Converts to [StableRef](-stable-ref/index) this opaque pointer produced by [StableRef.asCPointer](-stable-ref/as-c-pointer). ``` fun <T : Any> CPointer<*>.asStableRef(): StableRef<T> ``` **Platform and version requirements:** Native (1.3) #### <autoreleasepool> ``` fun <R> autoreleasepool(block: () -> R): R ``` **Platform and version requirements:** Native (1.3) #### [bitsToDouble](bits-to-double) ``` fun bitsToDouble(bits: Long): Double ``` **Platform and version requirements:** Native (1.3) #### [bitsToFloat](bits-to-float) ``` fun bitsToFloat(bits: Int): Float ``` **Platform and version requirements:** Native (1.3) #### <convert> ``` fun <R : Any> Byte.convert(): R ``` ``` fun <R : Any> Short.convert(): R ``` ``` fun <R : Any> Int.convert(): R ``` ``` fun <R : Any> Long.convert(): R ``` ``` fun <R : Any> UByte.convert(): R ``` ``` fun <R : Any> UShort.convert(): R ``` ``` fun <R : Any> UInt.convert(): R ``` ``` fun <R : Any> ULong.convert(): R ``` **Platform and version requirements:** Native (1.3) #### <copy> ``` fun <T : CStructVar> CValue<T>.copy(     modify: T.() -> Unit ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [createKotlinObjectHolder](create-kotlin-object-holder) ``` fun createKotlinObjectHolder(any: Any?): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [CreateKStringFromNSString](-create-k-string-from-n-s-string) ``` fun CreateKStringFromNSString(ptr: NativePtr): String? ``` **Platform and version requirements:** Native (1.3) #### [CreateNSStringFromKString](-create-n-s-string-from-k-string) ``` fun CreateNSStringFromKString(str: String?): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [createValues](create-values) ``` fun <T : CVariable> createValues(     count: Int,     initializer: T.(index: Int) -> Unit ): CValues<T> ``` **Platform and version requirements:** Native (1.3) #### [cValue](c-value) ``` fun <T : CVariable> cValue(): CValue<T> ``` ``` fun <T : CStructVar> cValue(     initialize: T.() -> Unit ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [cValuesOf](c-values-of) Returns sequence of immutable values [CValues](-c-values/index) to pass them to C code. ``` fun cValuesOf(vararg elements: Byte): CValues<ByteVar> ``` ``` fun cValuesOf(vararg elements: Short): CValues<ShortVar> ``` ``` fun cValuesOf(vararg elements: Int): CValues<IntVar> ``` ``` fun cValuesOf(vararg elements: Long): CValues<LongVar> ``` ``` fun cValuesOf(vararg elements: Float): CValues<FloatVar> ``` ``` fun cValuesOf(vararg elements: Double): CValues<DoubleVar> ``` ``` fun <T : CPointed> cValuesOf(     vararg elements: CPointer<T>? ): CValues<CPointerVar<T>> ``` ``` fun cValuesOf(vararg elements: UByte): CValues<UByteVar> ``` ``` fun cValuesOf(vararg elements: UShort): CValues<UShortVar> ``` ``` fun cValuesOf(vararg elements: UInt): CValues<UIntVar> ``` ``` fun cValuesOf(vararg elements: ULong): CValues<ULongVar> ``` **Platform and version requirements:** Native (1.3) #### <free> ``` fun NativeFreeablePlacement.free(pointer: CPointer<*>) ``` ``` fun NativeFreeablePlacement.free(pointed: NativePointed) ``` **Platform and version requirements:** Native (1.3) #### <get> ``` operator fun <T : Byte> CPointer<ByteVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Byte> CPointer<ByteVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Short> CPointer<ShortVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Short> CPointer<ShortVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Int> CPointer<IntVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Int> CPointer<IntVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Long> CPointer<LongVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Long> CPointer<LongVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : UByte> CPointer<UByteVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : UByte> CPointer<UByteVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : UShort> CPointer<UShortVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : UShort> CPointer<UShortVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : UInt> CPointer<UIntVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : UInt> CPointer<UIntVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : ULong> CPointer<ULongVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : ULong> CPointer<ULongVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Float> CPointer<FloatVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Float> CPointer<FloatVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Double> CPointer<DoubleVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Double> CPointer<DoubleVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : CVariable> CPointer<T>.get(index: Long): T ``` ``` operator fun <T : CVariable> CPointer<T>.get(index: Int): T ``` ``` operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.get(     index: Int ): T? ``` ``` operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.get(     index: Long ): T? ``` **Platform and version requirements:** Native (1.3) #### [getBytes](get-bytes) ``` fun <T : CVariable> CValues<T>.getBytes(): ByteArray ``` **Platform and version requirements:** Native (1.3) #### [getOriginalKotlinClass](get-original-kotlin-class) If [objCClass](get-original-kotlin-class#kotlinx.cinterop%24getOriginalKotlinClass(kotlinx.cinterop.ObjCClass)/objCClass) is a class generated to Objective-C header for Kotlin class, returns [KClass](../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) for that original Kotlin class. ``` fun getOriginalKotlinClass(objCClass: ObjCClass): KClass<*>? ``` If [objCProtocol](get-original-kotlin-class#kotlinx.cinterop%24getOriginalKotlinClass(kotlinx.cinterop.ObjCProtocol)/objCProtocol) is a protocol generated to Objective-C header for Kotlin class, returns [KClass](../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) for that original Kotlin class. ``` fun getOriginalKotlinClass(     objCProtocol: ObjCProtocol ): KClass<*>? ``` **Platform and version requirements:** Native (1.3) #### [getRawPointer](get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [getRawValue](get-raw-value) ``` fun CPointer<*>.getRawValue(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [initBy](init-by) ``` fun <T : ObjCObjectBase> T.initBy(constructorCall: T): T ``` **Platform and version requirements:** Native (1.3) #### [interpretCPointer](interpret-c-pointer) Performs type cast of the [CPointer](-c-pointer/index) from the given raw pointer. ``` fun <T : CPointed> interpretCPointer(     rawValue: NativePtr ): CPointer<T>? ``` **Platform and version requirements:** Native (1.3) #### [interpretNullableOpaquePointed](interpret-nullable-opaque-pointed) ``` fun interpretNullableOpaquePointed(     ptr: NativePtr ): NativePointed? ``` **Platform and version requirements:** Native (1.3) #### [interpretNullablePointed](interpret-nullable-pointed) Performs type cast of the native pointer to given interop type, including null values. ``` fun <T : NativePointed> interpretNullablePointed(     ptr: NativePtr ): T? ``` **Platform and version requirements:** Native (1.3) #### [interpretObjCPointer](interpret-obj-c-pointer) ``` fun <T : Any> interpretObjCPointer(objcPtr: NativePtr): T ``` **Platform and version requirements:** Native (1.3) #### [interpretObjCPointerOrNull](interpret-obj-c-pointer-or-null) ``` fun <T> interpretObjCPointerOrNull(objcPtr: NativePtr): T? ``` **Platform and version requirements:** Native (1.3) #### [interpretOpaquePointed](interpret-opaque-pointed) ``` fun interpretOpaquePointed(ptr: NativePtr): NativePointed ``` **Platform and version requirements:** Native (1.3) #### [interpretPointed](interpret-pointed) Returns interpretation of entity with given pointer. ``` fun <T : NativePointed> interpretPointed(ptr: NativePtr): T ``` **Platform and version requirements:** Native (1.3) #### <invoke> ``` operator fun <R> CPointer<CFunction<() -> R>>.invoke(): R ``` ``` operator fun <P1, R> CPointer<CFunction<(P1) -> R>>.invoke(     p1: P1 ): R ``` ``` operator fun <P1, P2, R> CPointer<CFunction<(P1, P2) -> R>>.invoke(     p1: P1,     p2: P2 ): R ``` ``` operator fun <P1, P2, P3, R> CPointer<CFunction<(P1, P2, P3) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3 ): R ``` ``` operator fun <P1, P2, P3, P4, R> CPointer<CFunction<(P1, P2, P3, P4) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, R> CPointer<CFunction<(P1, P2, P3, P4, P5) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18,     p19: P19 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18,     p19: P19,     p20: P20 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18,     p19: P19,     p20: P20,     p21: P21 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18,     p19: P19,     p20: P20,     p21: P21,     p22: P22 ): R ``` **Platform and version requirements:** Native (1.3) #### [memberAt](member-at) Returns the member of this [CStructVar](-c-struct-var/index) which is located by given offset in bytes. ``` fun <T : CPointed> CStructVar.memberAt(offset: Long): T ``` **Platform and version requirements:** Native (1.3) #### [memScoped](mem-scoped) Runs given [block](mem-scoped#kotlinx.cinterop%24memScoped(kotlin.Function1((kotlinx.cinterop.MemScope,%20kotlinx.cinterop.memScoped.R)))/block) providing allocation of memory which will be automatically disposed at the end of this scope. ``` fun <R> memScoped(block: MemScope.() -> R): R ``` **Platform and version requirements:** Native (1.3) #### <narrow> ``` fun <R : Number> Number.narrow(): R ``` **Platform and version requirements:** Native (1.3) #### [objc\_autoreleasePoolPop](objc_autorelease-pool-pop) ``` fun objc_autoreleasePoolPop(ptr: NativePtr) ``` **Platform and version requirements:** Native (1.3) #### [objc\_autoreleasePoolPush](objc_autorelease-pool-push) ``` fun objc_autoreleasePoolPush(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### <objc_release> ``` fun objc_release(ptr: NativePtr) ``` **Platform and version requirements:** Native (1.3) #### <objc_retain> ``` fun objc_retain(ptr: NativePtr): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [objc\_retainAutoreleaseReturnValue](objc_retain-autorelease-return-value) ``` fun objc_retainAutoreleaseReturnValue(     ptr: NativePtr ): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [objcPtr](objc-ptr) ``` fun Any?.objcPtr(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### <optional> ``` fun optional(): Nothing ``` **Platform and version requirements:** Native (1.3) #### <pin> ``` fun <T : Any> T.pin(): Pinned<T> ``` **Platform and version requirements:** Native (1.3) #### [placeTo](place-to) ``` fun <T : CVariable> CValues<T>.placeTo(     scope: AutofreeScope ): CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### <plus> ``` operator fun <T : ByteVarOf<*>> CPointer<T>?.plus(     index: Long ): CPointer<T>? ``` ``` operator fun <T : ByteVarOf<*>> CPointer<T>?.plus(     index: Int ): CPointer<T>? ``` **Platform and version requirements:** Native (1.3) #### [readBits](read-bits) ``` fun readBits(     ptr: NativePtr,     offset: Long,     size: Int,     signed: Boolean ): Long ``` **Platform and version requirements:** Native (1.3) #### [readBytes](read-bytes) ``` fun COpaquePointer.readBytes(count: Int): ByteArray ``` **Platform and version requirements:** Native (1.3) #### [readValue](read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` ``` fun <T : CStructVar> T.readValue(): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` **Platform and version requirements:** Native (1.3) #### [refTo](ref-to) ``` fun ByteArray.refTo(index: Int): CValuesRef<ByteVar> ``` ``` fun String.refTo(index: Int): CValuesRef<COpaque> ``` ``` fun CharArray.refTo(index: Int): CValuesRef<COpaque> ``` ``` fun ShortArray.refTo(index: Int): CValuesRef<ShortVar> ``` ``` fun IntArray.refTo(index: Int): CValuesRef<IntVar> ``` ``` fun LongArray.refTo(index: Int): CValuesRef<LongVar> ``` ``` fun UByteArray.refTo(index: Int): CValuesRef<UByteVar> ``` ``` fun UShortArray.refTo(index: Int): CValuesRef<UShortVar> ``` ``` fun UIntArray.refTo(index: Int): CValuesRef<UIntVar> ``` ``` fun ULongArray.refTo(index: Int): CValuesRef<ULongVar> ``` ``` fun FloatArray.refTo(index: Int): CValuesRef<FloatVar> ``` ``` fun DoubleArray.refTo(index: Int): CValuesRef<DoubleVar> ``` **Platform and version requirements:** Native (1.3) #### <reinterpret> Changes the interpretation of the pointed data or code. ``` fun <T : NativePointed> NativePointed.reinterpret(): T ``` ``` fun <T : CPointed> CPointer<*>.reinterpret(): CPointer<T> ``` ``` fun <T : ObjCObject> ObjCObject.reinterpret(): T ``` **Platform and version requirements:** Native (1.3) #### <set> ``` operator fun <T : Byte> CPointer<ByteVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Byte> CPointer<ByteVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Short> CPointer<ShortVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Short> CPointer<ShortVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Int> CPointer<IntVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Int> CPointer<IntVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Long> CPointer<LongVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Long> CPointer<LongVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : UByte> CPointer<UByteVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : UByte> CPointer<UByteVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : UShort> CPointer<UShortVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : UShort> CPointer<UShortVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : UInt> CPointer<UIntVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : UInt> CPointer<UIntVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : ULong> CPointer<ULongVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : ULong> CPointer<ULongVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Float> CPointer<FloatVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Float> CPointer<FloatVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Double> CPointer<DoubleVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Double> CPointer<DoubleVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.set(     index: Int,     value: T?) ``` ``` operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.set(     index: Long,     value: T?) ``` **Platform and version requirements:** Native (1.3) #### [signExtend](sign-extend) ``` fun <R : Number> Number.signExtend(): R ``` **Platform and version requirements:** Native (1.3) #### [sizeOf](size-of) ``` fun <T : CVariable> sizeOf(): Long ``` **Platform and version requirements:** Native (1.3) #### [staticCFunction](static-c-function) Returns a pointer to C function which calls given Kotlin *static* function. ``` fun <R> staticCFunction(     function: () -> R ): CPointer<CFunction<() -> R>> ``` ``` fun <P1, R> staticCFunction(     function: (P1) -> R ): CPointer<CFunction<(P1) -> R>> ``` ``` fun <P1, P2, R> staticCFunction(     function: (P1, P2) -> R ): CPointer<CFunction<(P1, P2) -> R>> ``` ``` fun <P1, P2, P3, R> staticCFunction(     function: (P1, P2, P3) -> R ): CPointer<CFunction<(P1, P2, P3) -> R>> ``` ``` fun <P1, P2, P3, P4, R> staticCFunction(     function: (P1, P2, P3, P4) -> R ): CPointer<CFunction<(P1, P2, P3, P4) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, R> staticCFunction(     function: (P1, P2, P3, P4, P5) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22) -> R>> ``` **Platform and version requirements:** Native (1.3) #### [toBoolean](to-boolean) ``` fun Byte.toBoolean(): Boolean ``` **Platform and version requirements:** Native (1.3) #### [toByte](to-byte) ``` fun Boolean.toByte(): Byte ``` **Platform and version requirements:** Native (1.3) #### [toCPointer](to-c-pointer) ``` fun <T : CPointed> Long.toCPointer(): CPointer<T>? ``` **Platform and version requirements:** Native (1.3) #### [toCStringArray](to-c-string-array) Convert this list of Kotlin strings to C array of C strings, allocating memory for the array and C strings with given [AutofreeScope](-autofree-scope/index). ``` fun List<String>.toCStringArray(     autofreeScope: AutofreeScope ): CPointer<CPointerVar<ByteVar>> ``` Convert this array of Kotlin strings to C array of C strings, allocating memory for the array and C strings with given [AutofreeScope](-autofree-scope/index). ``` fun Array<String>.toCStringArray(     autofreeScope: AutofreeScope ): CPointer<CPointerVar<ByteVar>> ``` **Platform and version requirements:** Native (1.3) #### [toCValues](to-c-values) ``` fun ByteArray.toCValues(): CValues<ByteVar> ``` ``` fun ShortArray.toCValues(): CValues<ShortVar> ``` ``` fun IntArray.toCValues(): CValues<IntVar> ``` ``` fun LongArray.toCValues(): CValues<LongVar> ``` ``` fun FloatArray.toCValues(): CValues<FloatVar> ``` ``` fun DoubleArray.toCValues(): CValues<DoubleVar> ``` ``` fun <T : CPointed> Array<CPointer<T>?>.toCValues(): CValues<CPointerVar<T>> ``` ``` fun <T : CPointed> List<CPointer<T>?>.toCValues(): CValues<CPointerVar<T>> ``` ``` fun UByteArray.toCValues(): CValues<UByteVar> ``` ``` fun UShortArray.toCValues(): CValues<UShortVar> ``` ``` fun UIntArray.toCValues(): CValues<UIntVar> ``` ``` fun ULongArray.toCValues(): CValues<ULongVar> ``` **Platform and version requirements:** Native (1.3) #### [toKString](to-k-string) ``` fun CPointer<ByteVar>.toKString(): String ``` ``` fun CPointer<ShortVar>.toKString(): String ``` ``` fun CPointer<UShortVar>.toKString(): String ``` Decodes a string from the bytes in UTF-8 encoding in this array. Bytes following the first occurrence of `0` byte, if it occurs, are not decoded. ``` fun ByteArray.toKString(): String ``` Decodes a string from the bytes in UTF-8 encoding in this array or its subrange. Bytes following the first occurrence of `0` byte, if it occurs, are not decoded. ``` fun ByteArray.toKString(     startIndex: Int = 0,     endIndex: Int = this.size,     throwOnInvalidSequence: Boolean = false ): String ``` **Platform and version requirements:** Native (1.3) #### [toKStringFromUtf16](to-k-string-from-utf16) ``` fun CPointer<ShortVar>.toKStringFromUtf16(): String ``` ``` fun CPointer<UShortVar>.toKStringFromUtf16(): String ``` **Platform and version requirements:** Native (1.3) #### [toKStringFromUtf32](to-k-string-from-utf32) ``` fun CPointer<IntVar>.toKStringFromUtf32(): String ``` **Platform and version requirements:** Native (1.3) #### [toKStringFromUtf8](to-k-string-from-utf8) ``` fun CPointer<ByteVar>.toKStringFromUtf8(): String ``` **Platform and version requirements:** Native (1.3) #### [toLong](to-long) ``` fun <T : CPointed> CPointer<T>?.toLong(): Long ``` **Platform and version requirements:** Native (1.3) #### [typeOf](type-of) ``` fun <T : CVariable> typeOf(): Type ``` **Platform and version requirements:** Native (1.3) #### [unwrapKotlinObjectHolder](unwrap-kotlin-object-holder) ``` fun <T : Any> unwrapKotlinObjectHolder(holder: Any?): T ``` **Platform and version requirements:** Native (1.3) #### [useContents](use-contents) Calls the [block](use-contents#kotlinx.cinterop%24useContents(kotlinx.cinterop.CValue((kotlinx.cinterop.useContents.T)),%20kotlin.Function1((kotlinx.cinterop.useContents.T,%20kotlinx.cinterop.useContents.R)))/block) with temporary copy of this value as receiver. ``` fun <T : CStructVar, R> CValue<T>.useContents(     block: T.() -> R ): R ``` **Platform and version requirements:** Native (1.3) #### [usePinned](use-pinned) ``` fun <T : Any, R> T.usePinned(block: (Pinned<T>) -> R): R ``` **Platform and version requirements:** Native (1.3) #### <write> ``` fun <T : CVariable> CValue<T>.write(location: NativePtr) ``` **Platform and version requirements:** Native (1.3) #### [writeBits](write-bits) ``` fun writeBits(     ptr: NativePtr,     offset: Long,     size: Int,     value: Long) ``` **Platform and version requirements:** Native (1.3) #### [zeroValue](zero-value) ``` fun <T : CVariable> zeroValue(     size: Int,     align: Int ): CValue<T> ``` ``` fun <T : CVariable> zeroValue(): CValue<T> ```
programming_docs
kotlin ShortVar ShortVar ======== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [ShortVar](-short-var) **Platform and version requirements:** Native (1.3) ``` typealias ShortVar = ShortVarOf<Short> ``` kotlin ObjCBlockVar ObjCBlockVar ============ [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [ObjCBlockVar](-obj-c-block-var) **Platform and version requirements:** Native (1.3) ``` typealias ObjCBlockVar<T> = ObjCNotImplementedVar<T> ``` kotlin createKotlinObjectHolder createKotlinObjectHolder ======================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [createKotlinObjectHolder](create-kotlin-object-holder) **Platform and version requirements:** Native (1.3) ``` fun createKotlinObjectHolder(any: Any?): NativePtr ``` kotlin optional optional ======== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <optional> **Platform and version requirements:** Native (1.3) ``` fun optional(): Nothing ``` kotlin UShortVar UShortVar ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [UShortVar](-u-short-var) **Platform and version requirements:** Native (1.3) ``` typealias UShortVar = UShortVarOf<UShort> ``` kotlin invoke invoke ====== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <invoke> **Platform and version requirements:** Native (1.3) ``` operator fun <R> CPointer<CFunction<() -> R>>.invoke(): R ``` ``` operator fun <P1, R> CPointer<CFunction<(P1) -> R>>.invoke(     p1: P1 ): R ``` ``` operator fun <P1, P2, R> CPointer<CFunction<(P1, P2) -> R>>.invoke(     p1: P1,     p2: P2 ): R ``` ``` operator fun <P1, P2, P3, R> CPointer<CFunction<(P1, P2, P3) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3 ): R ``` ``` operator fun <P1, P2, P3, P4, R> CPointer<CFunction<(P1, P2, P3, P4) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, R> CPointer<CFunction<(P1, P2, P3, P4, P5) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18,     p19: P19 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18,     p19: P19,     p20: P20 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18,     p19: P19,     p20: P20,     p21: P21 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18,     p19: P19,     p20: P20,     p21: P21,     p22: P22 ): R ``` kotlin toLong toLong ====== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [toLong](to-long) **Platform and version requirements:** Native (1.3) ``` fun <T : CPointed> CPointer<T>?.toLong(): Long ``` kotlin initBy initBy ====== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [initBy](init-by) **Platform and version requirements:** Native (1.3) ``` fun <T : ObjCObjectBase> T.initBy(constructorCall: T): T ``` **Deprecated:** Add @OverrideInit to constructor to make it override Objective-C initializer kotlin unwrapKotlinObjectHolder unwrapKotlinObjectHolder ======================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [unwrapKotlinObjectHolder](unwrap-kotlin-object-holder) **Platform and version requirements:** Native (1.3) ``` fun <reified T : Any> unwrapKotlinObjectHolder(     holder: Any? ): T ``` kotlin NativePtr NativePtr ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [NativePtr](-native-ptr) **Platform and version requirements:** Native (1.3) ``` typealias NativePtr = NativePtr ``` kotlin objc_autoreleasePoolPush objc\_autoreleasePoolPush ========================= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [objc\_autoreleasePoolPush](objc_autorelease-pool-push) **Platform and version requirements:** Native (1.3) ``` fun objc_autoreleasePoolPush(): NativePtr ``` kotlin nativeNullPtr nativeNullPtr ============= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [nativeNullPtr](native-null-ptr) **Platform and version requirements:** Native (1.3) ``` inline val nativeNullPtr: NativePtr ``` kotlin Vector128Var Vector128Var ============ [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [Vector128Var](-vector128-var) **Platform and version requirements:** Native (1.3) ``` typealias Vector128Var = Vector128VarOf<Vector128> ``` kotlin typeOf typeOf ====== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [typeOf](type-of) **Platform and version requirements:** Native (1.3) ``` fun <T : CVariable> typeOf(): Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin objc_retainAutoreleaseReturnValue objc\_retainAutoreleaseReturnValue ================================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [objc\_retainAutoreleaseReturnValue](objc_retain-autorelease-return-value) **Platform and version requirements:** Native (1.3) ``` fun objc_retainAutoreleaseReturnValue(     ptr: NativePtr ): NativePtr ``` kotlin toCPointer toCPointer ========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [toCPointer](to-c-pointer) **Platform and version requirements:** Native (1.3) ``` fun <T : CPointed> Long.toCPointer(): CPointer<T>? ``` kotlin readValue readValue ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [readValue](read-value) **Platform and version requirements:** Native (1.3) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` ``` fun <reified T : CStructVar> T.readValue(): CValue<T> ``` kotlin memberAt memberAt ======== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [memberAt](member-at) **Platform and version requirements:** Native (1.3) ``` fun <reified T : CPointed> CStructVar.memberAt(     offset: Long ): T ``` Returns the member of this [CStructVar](-c-struct-var/index) which is located by given offset in bytes. kotlin pin pin === [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <pin> **Platform and version requirements:** Native (1.3) ``` fun <T : Any> T.pin(): Pinned<T> ``` kotlin UByteVar UByteVar ======== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [UByteVar](-u-byte-var) **Platform and version requirements:** Native (1.3) ``` typealias UByteVar = UByteVarOf<UByte> ``` kotlin CreateNSStringFromKString CreateNSStringFromKString ========================= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [CreateNSStringFromKString](-create-n-s-string-from-k-string) **Platform and version requirements:** Native (1.3) ``` fun CreateNSStringFromKString(str: String?): NativePtr ``` **Deprecated:** Use plain Kotlin cast of String to NSString kotlin memScoped memScoped ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [memScoped](mem-scoped) **Platform and version requirements:** Native (1.3) ``` inline fun <R> memScoped(block: MemScope.() -> R): R ``` Runs given [block](mem-scoped#kotlinx.cinterop%24memScoped(kotlin.Function1((kotlinx.cinterop.MemScope,%20kotlinx.cinterop.memScoped.R)))/block) providing allocation of memory which will be automatically disposed at the end of this scope. kotlin rawValue rawValue ======== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [rawValue](raw-value) **Platform and version requirements:** Native (1.3) ``` val CPointer<*>?.rawValue: NativePtr ``` kotlin toKStringFromUtf16 toKStringFromUtf16 ================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [toKStringFromUtf16](to-k-string-from-utf16) **Platform and version requirements:** Native (1.3) ``` fun CPointer<ShortVar>.toKStringFromUtf16(): String ``` **Return** the [kotlin.String](../kotlin/-string/index#kotlin.String) decoded from given zero-terminated UTF-16-encoded C string. **Platform and version requirements:** Native (1.3) ``` fun CPointer<UShortVar>.toKStringFromUtf16(): String ``` kotlin toKString toKString ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [toKString](to-k-string) **Platform and version requirements:** Native (1.3) ``` fun CPointer<ByteVar>.toKString(): String ``` **Return** the [kotlin.String](../kotlin/-string/index#kotlin.String) decoded from given zero-terminated UTF-8-encoded C string. **Platform and version requirements:** Native (1.3) ``` fun ByteArray.toKString(): String ``` Decodes a string from the bytes in UTF-8 encoding in this array. Bytes following the first occurrence of `0` byte, if it occurs, are not decoded. Malformed byte sequences are replaced by the replacement char `\uFFFD`. **Platform and version requirements:** Native (1.3) ``` fun ByteArray.toKString(     startIndex: Int = 0,     endIndex: Int = this.size,     throwOnInvalidSequence: Boolean = false ): String ``` Decodes a string from the bytes in UTF-8 encoding in this array or its subrange. Bytes following the first occurrence of `0` byte, if it occurs, are not decoded. Parameters ---------- `startIndex` - the beginning (inclusive) of the subrange to decode, 0 by default. `endIndex` - the end (exclusive) of the subrange to decode, size of this array by default. `throwOnInvalidSequence` - specifies whether to throw an exception on malformed byte sequence or replace it by the replacement char `\uFFFD`. Exceptions ---------- `IndexOutOfBoundsException` - if [startIndex](to-k-string#kotlinx.cinterop%24toKString(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/startIndex) is less than zero or [endIndex](to-k-string#kotlinx.cinterop%24toKString(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/endIndex) is greater than the size of this array. `IllegalArgumentException` - if [startIndex](to-k-string#kotlinx.cinterop%24toKString(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/startIndex) is greater than [endIndex](to-k-string#kotlinx.cinterop%24toKString(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/endIndex). `CharacterCodingException` - if the byte array contains malformed UTF-8 byte sequence and [throwOnInvalidSequence](to-k-string#kotlinx.cinterop%24toKString(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int,%20kotlin.Boolean)/throwOnInvalidSequence) is true. **Platform and version requirements:** Native (1.3) ``` fun CPointer<ShortVar>.toKString(): String ``` ``` fun CPointer<UShortVar>.toKString(): String ``` kotlin CPlusPlusClass CPlusPlusClass ============== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [CPlusPlusClass](-c-plus-plus-class) **Platform and version requirements:** Native (1.3) ``` interface CPlusPlusClass ``` kotlin toCStringArray toCStringArray ============== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [toCStringArray](to-c-string-array) **Platform and version requirements:** Native (1.3) ``` fun List<String>.toCStringArray(     autofreeScope: AutofreeScope ): CPointer<CPointerVar<ByteVar>> ``` Convert this list of Kotlin strings to C array of C strings, allocating memory for the array and C strings with given [AutofreeScope](-autofree-scope/index). **Platform and version requirements:** Native (1.3) ``` fun Array<String>.toCStringArray(     autofreeScope: AutofreeScope ): CPointer<CPointerVar<ByteVar>> ``` Convert this array of Kotlin strings to C array of C strings, allocating memory for the array and C strings with given [AutofreeScope](-autofree-scope/index). kotlin allocPointerTo allocPointerTo ============== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [allocPointerTo](alloc-pointer-to) **Platform and version requirements:** Native (1.3) ``` fun <T : CPointed> NativePlacement.allocPointerTo(): CPointerVar<T> ``` kotlin SkiaRefCnt SkiaRefCnt ========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [SkiaRefCnt](-skia-ref-cnt) **Platform and version requirements:** Native (1.3) ``` interface SkiaRefCnt ``` kotlin toBoolean toBoolean ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [toBoolean](to-boolean) **Platform and version requirements:** Native (1.3) ``` fun Byte.toBoolean(): Boolean ``` kotlin utf8 utf8 ==== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <utf8> **Platform and version requirements:** Native (1.3) ``` val String.utf8: CValues<ByteVar> ``` **Return** the value of zero-terminated UTF-8-encoded C string constructed from given [kotlin.String](../kotlin/-string/index#kotlin.String). kotlin ObjCStringVarOf ObjCStringVarOf =============== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [ObjCStringVarOf](-obj-c-string-var-of) **Platform and version requirements:** Native (1.3) ``` typealias ObjCStringVarOf<T> = ObjCNotImplementedVar<T> ``` kotlin alloc alloc ===== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <alloc> **Platform and version requirements:** Native (1.3) ``` fun <reified T : CVariable> NativePlacement.alloc(): T ``` Allocates variable of given type. Parameters ---------- `T` - must not be abstract **Platform and version requirements:** Native (1.3) ``` inline fun <reified T : CVariable> NativePlacement.alloc(     initialize: T.() -> Unit ): T ``` Allocates variable of given type and initializes it applying given block. Parameters ---------- `T` - must not be abstract **Platform and version requirements:** Native (1.3) ``` fun <T : Boolean> NativePlacement.alloc(     value: T ): BooleanVarOf<T> ``` Allocates variable with given value type and initializes it with given value.
programming_docs
kotlin allocArrayOfPointersTo allocArrayOfPointersTo ====================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [allocArrayOfPointersTo](alloc-array-of-pointers-to) **Platform and version requirements:** Native (1.3) ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     elements: List<T?> ): CArrayPointer<CPointerVar<T>> ``` ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     vararg elements: T? ): CArrayPointer<CPointerVar<T>> ``` Allocates C array of pointers to given elements. kotlin usePinned usePinned ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [usePinned](use-pinned) **Platform and version requirements:** Native (1.3) ``` inline fun <T : Any, R> T.usePinned(     block: (Pinned<T>) -> R ): R ``` kotlin free free ==== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <free> **Platform and version requirements:** Native (1.3) ``` fun NativeFreeablePlacement.free(pointer: CPointer<*>) ``` ``` fun NativeFreeablePlacement.free(pointed: NativePointed) ``` kotlin allocArrayOf allocArrayOf ============ [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [allocArrayOf](alloc-array-of) **Platform and version requirements:** Native (1.3) ``` fun <reified T : CPointer<*>> NativePlacement.allocArrayOf(     vararg elements: T? ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun <reified T : CPointer<*>> NativePlacement.allocArrayOf(     elements: List<T?> ): CArrayPointer<CPointerVarOf<T>> ``` Allocates C array of given values. **Platform and version requirements:** Native (1.3) ``` fun NativePlacement.allocArrayOf(     elements: ByteArray ): CArrayPointer<ByteVar> ``` ``` fun NativePlacement.allocArrayOf(     vararg elements: Float ): CArrayPointer<FloatVar> ``` kotlin IntVar IntVar ====== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [IntVar](-int-var) **Platform and version requirements:** Native (1.3) ``` typealias IntVar = IntVarOf<Int> ``` kotlin getRawPointer getRawPointer ============= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [getRawPointer](get-raw-pointer) **Platform and version requirements:** Native (1.3) ``` fun NativePointed.getRawPointer(): NativePtr ``` kotlin CArrayPointerVar CArrayPointerVar ================ [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [CArrayPointerVar](-c-array-pointer-var) **Platform and version requirements:** Native (1.3) ``` typealias CArrayPointerVar<T> = CPointerVar<T> ``` kotlin objc_release objc\_release ============= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <objc_release> **Platform and version requirements:** Native (1.3) ``` fun objc_release(ptr: NativePtr) ``` kotlin staticCFunction staticCFunction =============== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [staticCFunction](static-c-function) **Platform and version requirements:** Native (1.3) ``` fun <R> staticCFunction(     function: () -> R ): CPointer<CFunction<() -> R>> ``` Returns a pointer to C function which calls given Kotlin *static* function. Parameters ---------- `function` - must be *static*, i.e. an (unbound) reference to a Kotlin function or a closure which doesn't capture any variable **Platform and version requirements:** Native (1.3) ``` fun <P1, R> staticCFunction(     function: (P1) -> R ): CPointer<CFunction<(P1) -> R>> ``` ``` fun <P1, P2, R> staticCFunction(     function: (P1, P2) -> R ): CPointer<CFunction<(P1, P2) -> R>> ``` ``` fun <P1, P2, P3, R> staticCFunction(     function: (P1, P2, P3) -> R ): CPointer<CFunction<(P1, P2, P3) -> R>> ``` ``` fun <P1, P2, P3, P4, R> staticCFunction(     function: (P1, P2, P3, P4) -> R ): CPointer<CFunction<(P1, P2, P3, P4) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, R> staticCFunction(     function: (P1, P2, P3, P4, P5) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21) -> R>> ``` ``` fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, R> staticCFunction(     function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22) -> R ): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22) -> R>> ``` kotlin createValues createValues ============ [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [createValues](create-values) **Platform and version requirements:** Native (1.3) ``` inline fun <reified T : CVariable> createValues(     count: Int,     initializer: T.(index: Int) -> Unit ): CValues<T> ``` kotlin utf16 utf16 ===== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <utf16> **Platform and version requirements:** Native (1.3) ``` val String.utf16: CValues<UShortVar> ``` **Return** the value of zero-terminated UTF-16-encoded C string constructed from given [kotlin.String](../kotlin/-string/index#kotlin.String). kotlin rawPtr rawPtr ====== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [rawPtr](raw-ptr) **Platform and version requirements:** Native (1.3) ``` val NativePointed?.rawPtr: NativePtr ``` kotlin COpaquePointerVar COpaquePointerVar ================= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [COpaquePointerVar](-c-opaque-pointer-var) **Platform and version requirements:** Native (1.3) ``` typealias COpaquePointerVar = CPointerVarOf<COpaquePointer> ``` The variable containing a [COpaquePointer](-c-opaque-pointer). kotlin UIntVar UIntVar ======= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [UIntVar](-u-int-var) **Platform and version requirements:** Native (1.3) ``` typealias UIntVar = UIntVarOf<UInt> ``` kotlin ObjCProtocol ObjCProtocol ============ [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [ObjCProtocol](-obj-c-protocol) **Platform and version requirements:** Native (1.3) ``` interface ObjCProtocol : ObjCObject ``` kotlin getOriginalKotlinClass getOriginalKotlinClass ====================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [getOriginalKotlinClass](get-original-kotlin-class) **Platform and version requirements:** Native (1.3) ``` fun getOriginalKotlinClass(objCClass: ObjCClass): KClass<*>? ``` If [objCClass](get-original-kotlin-class#kotlinx.cinterop%24getOriginalKotlinClass(kotlinx.cinterop.ObjCClass)/objCClass) is a class generated to Objective-C header for Kotlin class, returns [KClass](../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) for that original Kotlin class. Otherwise returns `null`. **Platform and version requirements:** Native (1.3) ``` fun getOriginalKotlinClass(     objCProtocol: ObjCProtocol ): KClass<*>? ``` If [objCProtocol](get-original-kotlin-class#kotlinx.cinterop%24getOriginalKotlinClass(kotlinx.cinterop.ObjCProtocol)/objCProtocol) is a protocol generated to Objective-C header for Kotlin class, returns [KClass](../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) for that original Kotlin class. Otherwise returns `null`. kotlin toCValues toCValues ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [toCValues](to-c-values) **Platform and version requirements:** Native (1.3) ``` fun ByteArray.toCValues(): CValues<ByteVar> ``` ``` fun ShortArray.toCValues(): CValues<ShortVar> ``` ``` fun IntArray.toCValues(): CValues<IntVar> ``` ``` fun LongArray.toCValues(): CValues<LongVar> ``` ``` fun FloatArray.toCValues(): CValues<FloatVar> ``` ``` fun DoubleArray.toCValues(): CValues<DoubleVar> ``` ``` fun <T : CPointed> Array<CPointer<T>?>.toCValues(): CValues<CPointerVar<T>> ``` ``` fun <T : CPointed> List<CPointer<T>?>.toCValues(): CValues<CPointerVar<T>> ``` ``` fun UByteArray.toCValues(): CValues<UByteVar> ``` ``` fun UShortArray.toCValues(): CValues<UShortVar> ``` ``` fun UIntArray.toCValues(): CValues<UIntVar> ``` ``` fun ULongArray.toCValues(): CValues<ULongVar> ``` kotlin readValues readValues ========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [readValues](read-values) **Platform and version requirements:** Native (1.3) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <reified T : CVariable> T.readValues(     count: Int ): CValues<T> ``` kotlin interpretPointed interpretPointed ================ [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [interpretPointed](interpret-pointed) **Platform and version requirements:** Native (1.3) ``` fun <reified T : NativePointed> interpretPointed(     ptr: NativePtr ): T ``` Returns interpretation of entity with given pointer. Parameters ---------- `T` - must not be abstract kotlin bitsToDouble bitsToDouble ============ [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [bitsToDouble](bits-to-double) **Platform and version requirements:** Native (1.3) ``` fun bitsToDouble(bits: Long): Double ``` kotlin ULongVar ULongVar ======== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [ULongVar](-u-long-var) **Platform and version requirements:** Native (1.3) ``` typealias ULongVar = ULongVarOf<ULong> ``` kotlin interpretNullablePointed interpretNullablePointed ======================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [interpretNullablePointed](interpret-nullable-pointed) **Platform and version requirements:** Native (1.3) ``` fun <T : NativePointed> interpretNullablePointed(     ptr: NativePtr ): T? ``` Performs type cast of the native pointer to given interop type, including null values. Parameters ---------- `T` - must not be abstract kotlin useContents useContents =========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [useContents](use-contents) **Platform and version requirements:** Native (1.3) ``` inline fun <reified T : CStructVar, R> CValue<T>.useContents(     block: T.() -> R ): R ``` Calls the [block](use-contents#kotlinx.cinterop%24useContents(kotlinx.cinterop.CValue((kotlinx.cinterop.useContents.T)),%20kotlin.Function1((kotlinx.cinterop.useContents.T,%20kotlinx.cinterop.useContents.R)))/block) with temporary copy of this value as receiver. kotlin COpaquePointer COpaquePointer ============== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [COpaquePointer](-c-opaque-pointer) **Platform and version requirements:** Native (1.3) ``` typealias COpaquePointer = CPointer<out CPointed> ``` The pointer with an opaque type. kotlin value value ===== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <value> **Platform and version requirements:** Native (1.3) ``` var <T : Boolean> BooleanVarOf<T>.value: T ``` ``` var <T : Byte> ByteVarOf<T>.value: T ``` ``` var <T : Short> ShortVarOf<T>.value: T ``` ``` var <T : Int> IntVarOf<T>.value: T ``` ``` var <T : Long> LongVarOf<T>.value: T ``` ``` var <T : UByte> UByteVarOf<T>.value: T ``` ``` var <T : UShort> UShortVarOf<T>.value: T ``` ``` var <T : UInt> UIntVarOf<T>.value: T ``` ``` var <T : ULong> ULongVarOf<T>.value: T ``` ``` var <T : Float> FloatVarOf<T>.value: T ``` ``` var <T : Double> DoubleVarOf<T>.value: T ``` ``` var <T : Vector128> Vector128VarOf<T>.value: T ``` ``` var <T> ObjCNotImplementedVar<T>.value: T ``` ``` var <T> ObjCObjectVar<T>.value: T ``` **Platform and version requirements:** Native (1.3) ``` inline var <P : CPointer<*>> CPointerVarOf<P>.value: P? ``` The value of this variable. kotlin ptr ptr === [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <ptr> **Platform and version requirements:** Native (1.3) ``` val <T : CPointed> T.ptr: CPointer<T> ``` Returns the pointer to this data or code. **Platform and version requirements:** Native (1.3) ``` val <T : CStructVar> ManagedType<T>.ptr: CPointer<T> ``` kotlin alignOf alignOf ======= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [alignOf](align-of) **Platform and version requirements:** Native (1.3) ``` fun <reified T : CVariable> alignOf(): Int ``` kotlin objc_retain objc\_retain ============ [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <objc_retain> **Platform and version requirements:** Native (1.3) ``` fun objc_retain(ptr: NativePtr): NativePtr ``` kotlin toKStringFromUtf8 toKStringFromUtf8 ================= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [toKStringFromUtf8](to-k-string-from-utf8) **Platform and version requirements:** Native (1.3) ``` fun CPointer<ByteVar>.toKStringFromUtf8(): String ``` **Return** the [kotlin.String](../kotlin/-string/index#kotlin.String) decoded from given zero-terminated UTF-8-encoded C string. kotlin placeTo placeTo ======= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [placeTo](place-to) **Platform and version requirements:** Native (1.3) ``` fun <T : CVariable> CValues<T>.placeTo(     scope: AutofreeScope ): CPointer<T> ``` kotlin StableObjPtr StableObjPtr ============ [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [StableObjPtr](-stable-obj-ptr) **Platform and version requirements:** Native (1.3) ``` typealias StableObjPtr = StableRef<*> ``` **Deprecated:** Use StableRef<T> instead kotlin write write ===== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <write> **Platform and version requirements:** Native (1.3) ``` fun <T : CVariable> CValue<T>.write(location: NativePtr) ``` kotlin copy copy ==== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <copy> **Platform and version requirements:** Native (1.3) ``` inline fun <reified T : CStructVar> CValue<T>.copy(     modify: T.() -> Unit ): CValue<T> ``` kotlin interpretCPointer interpretCPointer ================= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [interpretCPointer](interpret-c-pointer) **Platform and version requirements:** Native (1.3) ``` fun <T : CPointed> interpretCPointer(     rawValue: NativePtr ): CPointer<T>? ``` Performs type cast of the [CPointer](-c-pointer/index) from the given raw pointer. kotlin ObjCObjectMeta ObjCObjectMeta ============== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [ObjCObjectMeta](-obj-c-object-meta) **Platform and version requirements:** Native (1.3) ``` typealias ObjCObjectMeta = ObjCClass ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [ObjCObjectBaseMeta](-obj-c-object-base-meta/index) ``` abstract class ObjCObjectBaseMeta :      ObjCObjectBase,     ObjCObjectMeta ``` kotlin interpretNullableOpaquePointed interpretNullableOpaquePointed ============================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [interpretNullableOpaquePointed](interpret-nullable-opaque-pointed) **Platform and version requirements:** Native (1.3) ``` fun interpretNullableOpaquePointed(     ptr: NativePtr ): NativePointed? ``` kotlin getRawValue getRawValue =========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [getRawValue](get-raw-value) **Platform and version requirements:** Native (1.3) ``` fun CPointer<*>.getRawValue(): NativePtr ```
programming_docs
kotlin readBytes readBytes ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [readBytes](read-bytes) **Platform and version requirements:** Native (1.3) ``` fun COpaquePointer.readBytes(count: Int): ByteArray ``` kotlin autoreleasepool autoreleasepool =============== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <autoreleasepool> **Platform and version requirements:** Native (1.3) ``` inline fun <R> autoreleasepool(block: () -> R): R ``` kotlin interpretOpaquePointed interpretOpaquePointed ====================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [interpretOpaquePointed](interpret-opaque-pointed) **Platform and version requirements:** Native (1.3) ``` fun interpretOpaquePointed(ptr: NativePtr): NativePointed ``` kotlin sizeOf sizeOf ====== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [sizeOf](size-of) **Platform and version requirements:** Native (1.3) ``` fun <reified T : CVariable> sizeOf(): Long ``` kotlin interpretObjCPointerOrNull interpretObjCPointerOrNull ========================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [interpretObjCPointerOrNull](interpret-obj-c-pointer-or-null) **Platform and version requirements:** Native (1.3) ``` fun <T> interpretObjCPointerOrNull(objcPtr: NativePtr): T? ``` kotlin DoubleVar DoubleVar ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [DoubleVar](-double-var) **Platform and version requirements:** Native (1.3) ``` typealias DoubleVar = DoubleVarOf<Double> ``` kotlin addressOf addressOf ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [addressOf](address-of) **Platform and version requirements:** Native (1.3) ``` fun Pinned<ByteArray>.addressOf(     index: Int ): CPointer<ByteVar> ``` ``` fun Pinned<String>.addressOf(index: Int): CPointer<COpaque> ``` ``` fun Pinned<CharArray>.addressOf(     index: Int ): CPointer<COpaque> ``` ``` fun Pinned<ShortArray>.addressOf(     index: Int ): CPointer<ShortVar> ``` ``` fun Pinned<IntArray>.addressOf(index: Int): CPointer<IntVar> ``` ``` fun Pinned<LongArray>.addressOf(     index: Int ): CPointer<LongVar> ``` ``` fun Pinned<UByteArray>.addressOf(     index: Int ): CPointer<UByteVar> ``` ``` fun Pinned<UShortArray>.addressOf(     index: Int ): CPointer<UShortVar> ``` ``` fun Pinned<UIntArray>.addressOf(     index: Int ): CPointer<UIntVar> ``` ``` fun Pinned<ULongArray>.addressOf(     index: Int ): CPointer<ULongVar> ``` ``` fun Pinned<FloatArray>.addressOf(     index: Int ): CPointer<FloatVar> ``` ``` fun Pinned<DoubleArray>.addressOf(     index: Int ): CPointer<DoubleVar> ``` kotlin set set === [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <set> **Platform and version requirements:** Native (1.3) ``` operator fun <T : Byte> CPointer<ByteVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Byte> CPointer<ByteVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Short> CPointer<ShortVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Short> CPointer<ShortVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Int> CPointer<IntVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Int> CPointer<IntVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Long> CPointer<LongVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Long> CPointer<LongVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : UByte> CPointer<UByteVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : UByte> CPointer<UByteVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : UShort> CPointer<UShortVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : UShort> CPointer<UShortVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : UInt> CPointer<UIntVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : UInt> CPointer<UIntVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : ULong> CPointer<ULongVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : ULong> CPointer<ULongVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Float> CPointer<FloatVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Float> CPointer<FloatVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Double> CPointer<DoubleVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Double> CPointer<DoubleVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.set(     index: Int,     value: T?) ``` ``` operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.set(     index: Long,     value: T?) ``` kotlin CPointerVar CPointerVar =========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [CPointerVar](-c-pointer-var) **Platform and version requirements:** Native (1.3) ``` typealias CPointerVar<T> = CPointerVarOf<CPointer<T>> ``` The C data variable containing the pointer to `T`. kotlin ObjCClass ObjCClass ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [ObjCClass](-obj-c-class) **Platform and version requirements:** Native (1.3) ``` interface ObjCClass : ObjCObject ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [ObjCClassOf](-obj-c-class-of) ``` interface ObjCClassOf<T : ObjCObject> : ObjCClass ``` kotlin interpretObjCPointer interpretObjCPointer ==================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [interpretObjCPointer](interpret-obj-c-pointer) **Platform and version requirements:** Native (1.3) ``` fun <T : Any> interpretObjCPointer(objcPtr: NativePtr): T ``` kotlin getBytes getBytes ======== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [getBytes](get-bytes) **Platform and version requirements:** Native (1.3) ``` fun <T : CVariable> CValues<T>.getBytes(): ByteArray ``` kotlin plus plus ==== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <plus> **Platform and version requirements:** Native (1.3) ``` operator fun <T : ByteVarOf<*>> CPointer<T>?.plus(     index: Long ): CPointer<T>? ``` ``` operator fun <T : ByteVarOf<*>> CPointer<T>?.plus(     index: Int ): CPointer<T>? ``` kotlin objcPtr objcPtr ======= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [objcPtr](objc-ptr) **Platform and version requirements:** Native (1.3) ``` fun Any?.objcPtr(): NativePtr ``` kotlin pointed pointed ======= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <pointed> **Platform and version requirements:** Native (1.3) ``` inline val <reified T : CPointed> CPointer<T>.pointed: T ``` Returns the corresponding [CPointed](-c-pointed/index). Parameters ---------- `T` - must not be abstract **Platform and version requirements:** Native (1.3) ``` inline var <reified T : CPointed, reified P : CPointer<T>> CPointerVarOf<P>.pointed: T? ``` The code or data pointed by the value of this variable. Parameters ---------- `T` - must not be abstract kotlin FloatVar FloatVar ======== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [FloatVar](-float-var) **Platform and version requirements:** Native (1.3) ``` typealias FloatVar = FloatVarOf<Float> ``` kotlin toKStringFromUtf32 toKStringFromUtf32 ================== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [toKStringFromUtf32](to-k-string-from-utf32) **Platform and version requirements:** Native (1.3) ``` fun CPointer<IntVar>.toKStringFromUtf32(): String ``` **Return** the [kotlin.String](../kotlin/-string/index#kotlin.String) decoded from given zero-terminated UTF-32-encoded C string. kotlin BooleanVar BooleanVar ========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [BooleanVar](-boolean-var) **Platform and version requirements:** Native (1.3) ``` typealias BooleanVar = BooleanVarOf<Boolean> ``` kotlin asStableRef asStableRef =========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [asStableRef](as-stable-ref) **Platform and version requirements:** Native (1.3) ``` fun <reified T : Any> CPointer<*>.asStableRef(): StableRef<T> ``` Converts to [StableRef](-stable-ref/index) this opaque pointer produced by [StableRef.asCPointer](-stable-ref/as-c-pointer). kotlin cstr cstr ==== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <cstr> **Platform and version requirements:** Native (1.3) ``` val String.cstr: CValues<ByteVar> ``` **Return** the value of zero-terminated UTF-8-encoded C string constructed from given [kotlin.String](../kotlin/-string/index#kotlin.String). kotlin convert convert ======= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <convert> **Platform and version requirements:** Native (1.3) ``` fun <reified R : Any> Byte.convert(): R ``` ``` fun <reified R : Any> Short.convert(): R ``` ``` fun <reified R : Any> Int.convert(): R ``` ``` fun <reified R : Any> Long.convert(): R ``` ``` fun <reified R : Any> UByte.convert(): R ``` ``` fun <reified R : Any> UShort.convert(): R ``` ``` fun <reified R : Any> UInt.convert(): R ``` ``` fun <reified R : Any> ULong.convert(): R ``` kotlin get get === [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <get> **Platform and version requirements:** Native (1.3) ``` operator fun <T : Byte> CPointer<ByteVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Byte> CPointer<ByteVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Short> CPointer<ShortVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Short> CPointer<ShortVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Int> CPointer<IntVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Int> CPointer<IntVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Long> CPointer<LongVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Long> CPointer<LongVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : UByte> CPointer<UByteVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : UByte> CPointer<UByteVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : UShort> CPointer<UShortVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : UShort> CPointer<UShortVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : UInt> CPointer<UIntVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : UInt> CPointer<UIntVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : ULong> CPointer<ULongVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : ULong> CPointer<ULongVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Float> CPointer<FloatVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Float> CPointer<FloatVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Double> CPointer<DoubleVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Double> CPointer<DoubleVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <reified T : CVariable> CPointer<T>.get(     index: Long ): T ``` ``` operator fun <reified T : CVariable> CPointer<T>.get(     index: Int ): T ``` ``` operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.get(     index: Int ): T? ``` ``` operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.get(     index: Long ): T? ``` kotlin writeBits writeBits ========= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [writeBits](write-bits) **Platform and version requirements:** Native (1.3) ``` fun writeBits(     ptr: NativePtr,     offset: Long,     size: Int,     value: Long) ``` kotlin allocArray allocArray ========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [allocArray](alloc-array) **Platform and version requirements:** Native (1.3) ``` fun <reified T : CVariable> NativePlacement.allocArray(     length: Long ): CArrayPointer<T> ``` ``` fun <reified T : CVariable> NativePlacement.allocArray(     length: Int ): CArrayPointer<T> ``` Allocates C array of given elements type and length. Parameters ---------- `T` - must not be abstract **Platform and version requirements:** Native (1.3) ``` inline fun <reified T : CVariable> NativePlacement.allocArray(     length: Long,     initializer: T.(index: Long) -> Unit ): CArrayPointer<T> ``` ``` inline fun <reified T : CVariable> NativePlacement.allocArray(     length: Int,     initializer: T.(index: Int) -> Unit ): CArrayPointer<T> ``` Allocates C array of given elements type and length, and initializes its elements applying given block. Parameters ---------- `T` - must not be abstract kotlin narrow narrow ====== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <narrow> **Platform and version requirements:** Native (1.3) ``` fun <reified R : Number> Number.narrow(): R ``` kotlin CArrayPointer CArrayPointer ============= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [CArrayPointer](-c-array-pointer) **Platform and version requirements:** Native (1.3) ``` typealias CArrayPointer<T> = CPointer<T> ``` kotlin reinterpret reinterpret =========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <reinterpret> **Platform and version requirements:** Native (1.3) ``` fun <reified T : NativePointed> NativePointed.reinterpret(): T ``` Changes the interpretation of the pointed data or code. **Platform and version requirements:** Native (1.3) ``` fun <T : CPointed> CPointer<*>.reinterpret(): CPointer<T> ``` ``` fun <T : ObjCObject> ObjCObject.reinterpret(): T ``` **Deprecated:** Use plain Kotlin cast kotlin signExtend signExtend ========== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [signExtend](sign-extend) **Platform and version requirements:** Native (1.3) ``` fun <reified R : Number> Number.signExtend(): R ``` kotlin ByteVar ByteVar ======= [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [ByteVar](-byte-var) **Platform and version requirements:** Native (1.3) ``` typealias ByteVar = ByteVarOf<Byte> ``` kotlin cValue cValue ====== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / [cValue](c-value) **Platform and version requirements:** Native (1.3) ``` fun <reified T : CVariable> cValue(): CValue<T> ``` ``` inline fun <reified T : CStructVar> cValue(     initialize: T.() -> Unit ): CValue<T> ``` kotlin wcstr wcstr ===== [kotlin-stdlib](../../../../../index) / [kotlinx.cinterop](index) / <wcstr> **Platform and version requirements:** Native (1.3) ``` val String.wcstr: CValues<UShortVar> ``` **Return** the value of zero-terminated UTF-16-encoded C string constructed from given [kotlin.String](../kotlin/-string/index#kotlin.String). kotlin UShortVarOf UShortVarOf =========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [UShortVarOf](index) **Platform and version requirements:** Native (1.3) ``` class UShortVarOf<T : UShort> : CPrimitiveVar ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` UShortVarOf(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T : UShort> UShortVarOf<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [UShortVarOf](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [UShortVarOf](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` UShortVarOf(rawPtr: NativePtr) ``` kotlin CValuesRef CValuesRef ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CValuesRef](index) **Platform and version requirements:** Native (1.3) ``` abstract class CValuesRef<T : CPointed> ``` Represents a reference to (possibly empty) sequence of C values. It can be either a stable pointer [CPointer](../-c-pointer/index) or a sequence of immutable values [CValues](../-c-values/index). [CValuesRef](index) is designed to be used as Kotlin representation of pointer-typed parameters of C functions. When passing [CPointer](../-c-pointer/index) as [CValuesRef](index) to the Kotlin binding method, the C function receives exactly this pointer. Passing [CValues](../-c-values/index) has nearly the same semantics as passing by value: the C function receives the pointer to the temporary copy of these values, and the caller can't observe the modifications to this copy. The copy is valid until the C function returns. There are also other implementations of [CValuesRef](index) that provide temporary pointer, e.g. Kotlin Native specific [refTo](../ref-to) functions to pass primitive arrays directly to native. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Represents a reference to (possibly empty) sequence of C values. It can be either a stable pointer [CPointer](../-c-pointer/index) or a sequence of immutable values [CValues](../-c-values/index). ``` CValuesRef() ``` Functions --------- **Platform and version requirements:** Native (1.3) #### [getPointer](get-pointer) If this reference is [CPointer](../-c-pointer/index), returns this pointer, otherwise allocate storage value in the scope and return it. ``` abstract fun getPointer(scope: AutofreeScope): CPointer<T> ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [CPointer](../-c-pointer/index) C pointer. ``` class CPointer<T : CPointed> : CValuesRef<T> ``` **Platform and version requirements:** Native (1.3) #### [CValues](../-c-values/index) The (possibly empty) sequence of immutable C values. It is self-contained and doesn't depend on native memory. ``` abstract class CValues<T : CVariable> : CValuesRef<T> ```
programming_docs
kotlin getPointer getPointer ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CValuesRef](index) / [getPointer](get-pointer) **Platform and version requirements:** Native (1.3) ``` abstract fun getPointer(scope: AutofreeScope): CPointer<T> ``` If this reference is [CPointer](../-c-pointer/index), returns this pointer, otherwise allocate storage value in the scope and return it. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CValuesRef](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` CValuesRef() ``` Represents a reference to (possibly empty) sequence of C values. It can be either a stable pointer [CPointer](../-c-pointer/index) or a sequence of immutable values [CValues](../-c-values/index). [CValuesRef](index) is designed to be used as Kotlin representation of pointer-typed parameters of C functions. When passing [CPointer](../-c-pointer/index) as [CValuesRef](index) to the Kotlin binding method, the C function receives exactly this pointer. Passing [CValues](../-c-values/index) has nearly the same semantics as passing by value: the C function receives the pointer to the temporary copy of these values, and the caller can't observe the modifications to this copy. The copy is valid until the C function returns. There are also other implementations of [CValuesRef](index) that provide temporary pointer, e.g. Kotlin Native specific [refTo](../ref-to) functions to pass primitive arrays directly to native. kotlin CPointer CPointer ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CPointer](index) **Platform and version requirements:** Native (1.3) ``` class CPointer<T : CPointed> : CValuesRef<T> ``` C pointer. Properties ---------- **Platform and version requirements:** Native (1.3) #### [rawValue](raw-value) ``` val rawValue: NativePtr ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <equals> Indicates whether some other object is "equal to" this one. Implementations must fulfil the following requirements: ``` fun equals(other: Any?): Boolean ``` **Platform and version requirements:** Native (1.3) #### [getPointer](get-pointer) If this reference is [CPointer](index), returns this pointer, otherwise allocate storage value in the scope and return it. ``` fun getPointer(scope: AutofreeScope): CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [hashCode](hash-code) Returns a hash code value for the object. The general contract of `hashCode` is: ``` fun hashCode(): Int ``` **Platform and version requirements:** Native (1.3) #### [toString](to-string) Returns a string representation of the object. ``` fun toString(): String ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [pointed](../pointed) Returns the corresponding [CPointed](../-c-pointed/index). ``` val <T : CPointed> CPointer<T>.pointed: T ``` **Platform and version requirements:** Native (1.3) #### [rawValue](../raw-value) ``` val CPointer<*>?.rawValue: NativePtr ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [asStableRef](../as-stable-ref) Converts to [StableRef](../-stable-ref/index) this opaque pointer produced by [StableRef.asCPointer](../-stable-ref/as-c-pointer). ``` fun <T : Any> CPointer<*>.asStableRef(): StableRef<T> ``` **Platform and version requirements:** Native (1.3) #### [callContinuation0](../../kotlin.native.concurrent/call-continuation0) ``` fun COpaquePointer.callContinuation0() ``` **Platform and version requirements:** Native (1.3) #### [callContinuation1](../../kotlin.native.concurrent/call-continuation1) ``` fun <T1> COpaquePointer.callContinuation1() ``` **Platform and version requirements:** Native (1.3) #### [callContinuation2](../../kotlin.native.concurrent/call-continuation2) ``` fun <T1, T2> COpaquePointer.callContinuation2() ``` **Platform and version requirements:** Native (1.3) #### [get](../get) ``` operator fun <T : Byte> CPointer<ByteVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Byte> CPointer<ByteVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Short> CPointer<ShortVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Short> CPointer<ShortVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Int> CPointer<IntVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Int> CPointer<IntVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Long> CPointer<LongVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Long> CPointer<LongVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : UByte> CPointer<UByteVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : UByte> CPointer<UByteVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : UShort> CPointer<UShortVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : UShort> CPointer<UShortVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : UInt> CPointer<UIntVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : UInt> CPointer<UIntVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : ULong> CPointer<ULongVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : ULong> CPointer<ULongVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Float> CPointer<FloatVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Float> CPointer<FloatVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : Double> CPointer<DoubleVarOf<T>>.get(     index: Int ): T ``` ``` operator fun <T : Double> CPointer<DoubleVarOf<T>>.get(     index: Long ): T ``` ``` operator fun <T : CVariable> CPointer<T>.get(index: Long): T ``` ``` operator fun <T : CVariable> CPointer<T>.get(index: Int): T ``` ``` operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.get(     index: Int ): T? ``` ``` operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.get(     index: Long ): T? ``` **Platform and version requirements:** Native (1.3) #### [getRawValue](../get-raw-value) ``` fun CPointer<*>.getRawValue(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [invoke](../invoke) ``` operator fun <R> CPointer<CFunction<() -> R>>.invoke(): R ``` ``` operator fun <P1, R> CPointer<CFunction<(P1) -> R>>.invoke(     p1: P1 ): R ``` ``` operator fun <P1, P2, R> CPointer<CFunction<(P1, P2) -> R>>.invoke(     p1: P1,     p2: P2 ): R ``` ``` operator fun <P1, P2, P3, R> CPointer<CFunction<(P1, P2, P3) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3 ): R ``` ``` operator fun <P1, P2, P3, P4, R> CPointer<CFunction<(P1, P2, P3, P4) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, R> CPointer<CFunction<(P1, P2, P3, P4, P5) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18,     p19: P19 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18,     p19: P19,     p20: P20 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18,     p19: P19,     p20: P20,     p21: P21 ): R ``` ``` operator fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, R> CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22) -> R>>.invoke(     p1: P1,     p2: P2,     p3: P3,     p4: P4,     p5: P5,     p6: P6,     p7: P7,     p8: P8,     p9: P9,     p10: P10,     p11: P11,     p12: P12,     p13: P13,     p14: P14,     p15: P15,     p16: P16,     p17: P17,     p18: P18,     p19: P19,     p20: P20,     p21: P21,     p22: P22 ): R ``` **Platform and version requirements:** Native (1.3) #### [plus](../plus) ``` operator fun <T : ByteVarOf<*>> CPointer<T>?.plus(     index: Long ): CPointer<T>? ``` ``` operator fun <T : ByteVarOf<*>> CPointer<T>?.plus(     index: Int ): CPointer<T>? ``` **Platform and version requirements:** Native (1.3) #### [readBytes](../read-bytes) ``` fun COpaquePointer.readBytes(count: Int): ByteArray ``` **Platform and version requirements:** Native (1.3) #### [reinterpret](../reinterpret) ``` fun <T : CPointed> CPointer<*>.reinterpret(): CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [set](../set) ``` operator fun <T : Byte> CPointer<ByteVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Byte> CPointer<ByteVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Short> CPointer<ShortVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Short> CPointer<ShortVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Int> CPointer<IntVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Int> CPointer<IntVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Long> CPointer<LongVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Long> CPointer<LongVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : UByte> CPointer<UByteVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : UByte> CPointer<UByteVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : UShort> CPointer<UShortVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : UShort> CPointer<UShortVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : UInt> CPointer<UIntVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : UInt> CPointer<UIntVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : ULong> CPointer<ULongVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : ULong> CPointer<ULongVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Float> CPointer<FloatVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Float> CPointer<FloatVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : Double> CPointer<DoubleVarOf<T>>.set(     index: Int,     value: T) ``` ``` operator fun <T : Double> CPointer<DoubleVarOf<T>>.set(     index: Long,     value: T) ``` ``` operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.set(     index: Int,     value: T?) ``` ``` operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.set(     index: Long,     value: T?) ``` **Platform and version requirements:** Native (1.3) #### [toKString](../to-k-string) ``` fun CPointer<ByteVar>.toKString(): String ``` ``` fun CPointer<ShortVar>.toKString(): String ``` ``` fun CPointer<UShortVar>.toKString(): String ``` **Platform and version requirements:** Native (1.3) #### [toKStringFromUtf16](../to-k-string-from-utf16) ``` fun CPointer<ShortVar>.toKStringFromUtf16(): String ``` ``` fun CPointer<UShortVar>.toKStringFromUtf16(): String ``` **Platform and version requirements:** Native (1.3) #### [toKStringFromUtf32](../to-k-string-from-utf32) ``` fun CPointer<IntVar>.toKStringFromUtf32(): String ``` **Platform and version requirements:** Native (1.3) #### [toKStringFromUtf8](../to-k-string-from-utf8) ``` fun CPointer<ByteVar>.toKStringFromUtf8(): String ``` **Platform and version requirements:** Native (1.3) #### [toLong](../to-long) ``` fun <T : CPointed> CPointer<T>?.toLong(): Long ``` kotlin getPointer getPointer ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CPointer](index) / [getPointer](get-pointer) **Platform and version requirements:** Native (1.3) ``` fun getPointer(scope: AutofreeScope): CPointer<T> ``` If this reference is [CPointer](index), returns this pointer, otherwise allocate storage value in the scope and return it. kotlin rawValue rawValue ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CPointer](index) / [rawValue](raw-value) **Platform and version requirements:** Native (1.3) ``` inline val rawValue: NativePtr ``` kotlin hashCode hashCode ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CPointer](index) / [hashCode](hash-code) **Platform and version requirements:** Native (1.3) ``` fun hashCode(): Int ``` Returns a hash code value for the object. The general contract of `hashCode` is: * Whenever it is invoked on the same object more than once, the `hashCode` method must consistently return the same integer, provided no information used in `equals` comparisons on the object is modified. * If two objects are equal according to the `equals()` method, then calling the `hashCode` method on each of the two objects must produce the same integer result. kotlin toString toString ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CPointer](index) / [toString](to-string) **Platform and version requirements:** Native (1.3) ``` fun toString(): String ``` Returns a string representation of the object. kotlin equals equals ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CPointer](index) / <equals> **Platform and version requirements:** Native (1.3) ``` fun equals(other: Any?): Boolean ``` Indicates whether some other object is "equal to" this one. Implementations must fulfil the following requirements: * Reflexive: for any non-null value `x`, `x.equals(x)` should return true. * Symmetric: for any non-null values `x` and `y`, `x.equals(y)` should return true if and only if `y.equals(x)` returns true. * Transitive: for any non-null values `x`, `y`, and `z`, if `x.equals(y)` returns true and `y.equals(z)` returns true, then `x.equals(z)` should return true. * Consistent: for any non-null values `x` and `y`, multiple invocations of `x.equals(y)` consistently return true or consistently return false, provided no information used in `equals` comparisons on the objects is modified. * Never equal to null: for any non-null value `x`, `x.equals(null)` should return false. Read more about [equality](../../../../../../docs/equality) in Kotlin.
programming_docs
kotlin ArenaBase ArenaBase ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ArenaBase](index) **Platform and version requirements:** Native (1.3) ``` open class ArenaBase : AutofreeScope ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` ArenaBase(parent: NativeFreeablePlacement = nativeHeap) ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <alloc> ``` fun alloc(size: Long, align: Int): NativePointed ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [alloc](../alloc) Allocates variable of given type. ``` fun <T : CVariable> NativePlacement.alloc(): T ``` Allocates variable of given type and initializes it applying given block. ``` fun <T : CVariable> NativePlacement.alloc(     initialize: T.() -> Unit ): T ``` Allocates variable with given value type and initializes it with given value. ``` fun <T : Boolean> NativePlacement.alloc(     value: T ): BooleanVarOf<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArray](../alloc-array) Allocates C array of given elements type and length. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int ): CArrayPointer<T> ``` Allocates C array of given elements type and length, and initializes its elements applying given block. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long,     initializer: T.(index: Long) -> Unit ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int,     initializer: T.(index: Int) -> Unit ): CArrayPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOf](../alloc-array-of) Allocates C array of given values. ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     vararg elements: T? ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     elements: List<T?> ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun NativePlacement.allocArrayOf(     elements: ByteArray ): CArrayPointer<ByteVar> ``` ``` fun NativePlacement.allocArrayOf(     vararg elements: Float ): CArrayPointer<FloatVar> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOfPointersTo](../alloc-array-of-pointers-to) Allocates C array of pointers to given elements. ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     elements: List<T?> ): CArrayPointer<CPointerVar<T>> ``` ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     vararg elements: T? ): CArrayPointer<CPointerVar<T>> ``` **Platform and version requirements:** Native (1.3) #### [allocPointerTo](../alloc-pointer-to) ``` fun <T : CPointed> NativePlacement.allocPointerTo(): CPointerVar<T> ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [Arena](../-arena/index) ``` class Arena : ArenaBase ``` **Platform and version requirements:** Native (1.3) #### [MemScope](../-mem-scope/index) ``` class MemScope : ArenaBase ``` kotlin alloc alloc ===== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ArenaBase](index) / <alloc> **Platform and version requirements:** Native (1.3) ``` fun alloc(size: Long, align: Int): NativePointed ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ArenaBase](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ArenaBase(parent: NativeFreeablePlacement = nativeHeap) ``` kotlin ByteVarOf ByteVarOf ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ByteVarOf](index) **Platform and version requirements:** Native (1.3) ``` class ByteVarOf<T : Byte> : CPrimitiveVar ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` ByteVarOf(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T : Byte> ByteVarOf<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ByteVarOf](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ByteVarOf](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ByteVarOf(rawPtr: NativePtr) ``` kotlin ULongVarOf ULongVarOf ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ULongVarOf](index) **Platform and version requirements:** Native (1.3) ``` class ULongVarOf<T : ULong> : CPrimitiveVar ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` ULongVarOf(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T : ULong> ULongVarOf<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ULongVarOf](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ULongVarOf](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ULongVarOf(rawPtr: NativePtr) ``` kotlin size size ==== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CValues](index) / <size> **Platform and version requirements:** Native (1.3) ``` abstract val size: Int ``` kotlin CValues CValues ======= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CValues](index) **Platform and version requirements:** Native (1.3) ``` abstract class CValues<T : CVariable> : CValuesRef<T> ``` The (possibly empty) sequence of immutable C values. It is self-contained and doesn't depend on native memory. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) The (possibly empty) sequence of immutable C values. It is self-contained and doesn't depend on native memory. ``` CValues() ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <align> ``` abstract val align: Int ``` **Platform and version requirements:** Native (1.3) #### <size> ``` abstract val size: Int ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <equals> Indicates whether some other object is "equal to" this one. Implementations must fulfil the following requirements: ``` open fun equals(other: Any?): Boolean ``` **Platform and version requirements:** Native (1.3) #### [getPointer](get-pointer) Copies the values to placement and returns the pointer to the copy. ``` open fun getPointer(scope: AutofreeScope): CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [hashCode](hash-code) Returns a hash code value for the object. The general contract of `hashCode` is: ``` open fun hashCode(): Int ``` **Platform and version requirements:** Native (1.3) #### <place> Copy the referenced values to [placement](place#kotlinx.cinterop.CValues%24place(kotlinx.cinterop.CPointer((kotlinx.cinterop.CValues.T)))/placement) and return placement pointer. ``` abstract fun place(placement: CPointer<T>): CPointer<T> ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getBytes](../get-bytes) ``` fun <T : CVariable> CValues<T>.getBytes(): ByteArray ``` **Platform and version requirements:** Native (1.3) #### [placeTo](../place-to) ``` fun <T : CVariable> CValues<T>.placeTo(     scope: AutofreeScope ): CPointer<T> ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [CValue](../-c-value/index) The single immutable C value. It is self-contained and doesn't depend on native memory. ``` abstract class CValue<T : CVariable> : CValues<T> ``` kotlin getPointer getPointer ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CValues](index) / [getPointer](get-pointer) **Platform and version requirements:** Native (1.3) ``` open fun getPointer(scope: AutofreeScope): CPointer<T> ``` Copies the values to placement and returns the pointer to the copy. kotlin place place ===== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CValues](index) / <place> **Platform and version requirements:** Native (1.3) ``` abstract fun place(placement: CPointer<T>): CPointer<T> ``` Copy the referenced values to [placement](place#kotlinx.cinterop.CValues%24place(kotlinx.cinterop.CPointer((kotlinx.cinterop.CValues.T)))/placement) and return placement pointer. kotlin hashCode hashCode ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CValues](index) / [hashCode](hash-code) **Platform and version requirements:** Native (1.3) ``` open fun hashCode(): Int ``` Returns a hash code value for the object. The general contract of `hashCode` is: * Whenever it is invoked on the same object more than once, the `hashCode` method must consistently return the same integer, provided no information used in `equals` comparisons on the object is modified. * If two objects are equal according to the `equals()` method, then calling the `hashCode` method on each of the two objects must produce the same integer result. kotlin align align ===== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CValues](index) / <align> **Platform and version requirements:** Native (1.3) ``` abstract val align: Int ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CValues](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` CValues() ``` The (possibly empty) sequence of immutable C values. It is self-contained and doesn't depend on native memory. kotlin equals equals ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CValues](index) / <equals> **Platform and version requirements:** Native (1.3) ``` open fun equals(other: Any?): Boolean ``` Indicates whether some other object is "equal to" this one. Implementations must fulfil the following requirements: * Reflexive: for any non-null value `x`, `x.equals(x)` should return true. * Symmetric: for any non-null values `x` and `y`, `x.equals(y)` should return true if and only if `y.equals(x)` returns true. * Transitive: for any non-null values `x`, `y`, and `z`, if `x.equals(y)` returns true and `y.equals(z)` returns true, then `x.equals(z)` should return true. * Consistent: for any non-null values `x` and `y`, multiple invocations of `x.equals(y)` consistently return true or consistently return false, provided no information used in `equals` comparisons on the objects is modified. * Never equal to null: for any non-null value `x`, `x.equals(null)` should return false. Read more about [equality](../../../../../../docs/equality) in Kotlin. kotlin message message ======= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ForeignException](index) / <message> **Platform and version requirements:** Native (1.3) ``` val message: String ``` the detail message string. kotlin ForeignException ForeignException ================ [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ForeignException](index) **Platform and version requirements:** Native (1.3) ``` class ForeignException : Exception ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <message> the detail message string. ``` val message: String ``` **Platform and version requirements:** Native (1.3) #### [nativeException](native-exception) ``` val nativeException: Any? ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getStackTraceAddresses](../../kotlin.native/get-stack-trace-addresses) Returns a list of stack trace addresses representing the stack trace pertaining to this throwable. ``` fun Throwable.getStackTraceAddresses(): List<Long> ``` kotlin nativeException nativeException =============== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ForeignException](index) / [nativeException](native-exception) **Platform and version requirements:** Native (1.3) ``` val nativeException: Any? ``` kotlin CPointerVarOf CPointerVarOf ============= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CPointerVarOf](index) **Platform and version requirements:** Native (1.3) ``` class CPointerVarOf<T : CPointer<*>> : CVariable ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` CPointerVarOf(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [pointed](../pointed) The code or data pointed by the value of this variable. ``` var <T : CPointed, P : CPointer<T>> CPointerVarOf<P>.pointed: T? ``` **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) The value of this variable. ``` var <P : CPointer<*>> CPointerVarOf<P>.value: P? ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CPointerVarOf](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CPointerVarOf](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` CPointerVarOf(rawPtr: NativePtr) ``` kotlin CPrimitiveVar CPrimitiveVar ============= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CPrimitiveVar](index) **Platform and version requirements:** Native (1.3) ``` sealed class CPrimitiveVar : CVariable ``` The C primitive-typed variable located in memory. Types ----- **Platform and version requirements:** Native (1.3) #### [Type](-type/index) ``` open class Type : Type ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [BooleanVarOf](../-boolean-var-of/index) ``` class BooleanVarOf<T : Boolean> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [ByteVarOf](../-byte-var-of/index) ``` class ByteVarOf<T : Byte> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [CEnumVar](../-c-enum-var/index) ``` abstract class CEnumVar : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [DoubleVarOf](../-double-var-of/index) ``` class DoubleVarOf<T : Double> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [FloatVarOf](../-float-var-of/index) ``` class FloatVarOf<T : Float> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [IntVarOf](../-int-var-of/index) ``` class IntVarOf<T : Int> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [LongVarOf](../-long-var-of/index) ``` class LongVarOf<T : Long> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [ShortVarOf](../-short-var-of/index) ``` class ShortVarOf<T : Short> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [UByteVarOf](../-u-byte-var-of/index) ``` class UByteVarOf<T : UByte> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [UIntVarOf](../-u-int-var-of/index) ``` class UIntVarOf<T : UInt> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [ULongVarOf](../-u-long-var-of/index) ``` class ULongVarOf<T : ULong> : CPrimitiveVar ``` **Platform and version requirements:** Native (1.3) #### [UShortVarOf](../-u-short-var-of/index) ``` class UShortVarOf<T : UShort> : CPrimitiveVar ```
programming_docs
kotlin Type Type ==== [kotlin-stdlib](../../../../../../../index) / [kotlinx.cinterop](../../index) / [CPrimitiveVar](../index) / [Type](index) **Platform and version requirements:** Native (1.3) ``` open class Type : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` Type(size: Int) ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../../index) / [kotlinx.cinterop](../../index) / [CPrimitiveVar](../index) / [Type](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` Type(size: Int) ``` kotlin ShortVarOf ShortVarOf ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ShortVarOf](index) **Platform and version requirements:** Native (1.3) ``` class ShortVarOf<T : Short> : CPrimitiveVar ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` ShortVarOf(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T : Short> ShortVarOf<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ShortVarOf](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ShortVarOf](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ShortVarOf(rawPtr: NativePtr) ``` kotlin ObjCMethod ObjCMethod ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCMethod](index) **Platform and version requirements:** Native (1.3) ``` @Target([AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER]) annotation class ObjCMethod ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` ObjCMethod(     selector: String,     encoding: String,     isStret: Boolean = false) ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <encoding> ``` val encoding: String ``` **Platform and version requirements:** Native (1.3) #### [isStret](is-stret) ``` val isStret: Boolean ``` **Platform and version requirements:** Native (1.3) #### <selector> ``` val selector: String ``` kotlin isStret isStret ======= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCMethod](index) / [isStret](is-stret) **Platform and version requirements:** Native (1.3) ``` val isStret: Boolean ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCMethod](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ObjCMethod(     selector: String,     encoding: String,     isStret: Boolean = false) ``` kotlin selector selector ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCMethod](index) / <selector> **Platform and version requirements:** Native (1.3) ``` val selector: String ``` kotlin encoding encoding ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCMethod](index) / <encoding> **Platform and version requirements:** Native (1.3) ``` val encoding: String ``` kotlin CValue CValue ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CValue](index) **Platform and version requirements:** Native (1.3) ``` abstract class CValue<T : CVariable> : CValues<T> ``` The single immutable C value. It is self-contained and doesn't depend on native memory. TODO: consider providing an adapter instead of subtyping [CValues](../-c-values/index). Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) The single immutable C value. It is self-contained and doesn't depend on native memory. ``` CValue() ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [copy](../copy) ``` fun <T : CStructVar> CValue<T>.copy(     modify: T.() -> Unit ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [getBytes](../get-bytes) ``` fun <T : CVariable> CValues<T>.getBytes(): ByteArray ``` **Platform and version requirements:** Native (1.3) #### [placeTo](../place-to) ``` fun <T : CVariable> CValues<T>.placeTo(     scope: AutofreeScope ): CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [useContents](../use-contents) Calls the [block](../use-contents#kotlinx.cinterop%24useContents(kotlinx.cinterop.CValue((kotlinx.cinterop.useContents.T)),%20kotlin.Function1((kotlinx.cinterop.useContents.T,%20kotlinx.cinterop.useContents.R)))/block) with temporary copy of this value as receiver. ``` fun <T : CStructVar, R> CValue<T>.useContents(     block: T.() -> R ): R ``` **Platform and version requirements:** Native (1.3) #### [write](../write) ``` fun <T : CVariable> CValue<T>.write(location: NativePtr) ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CValue](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` CValue() ``` The single immutable C value. It is self-contained and doesn't depend on native memory. TODO: consider providing an adapter instead of subtyping [CValues](../-c-values/index). kotlin ObjCAction ObjCAction ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCAction](index) **Platform and version requirements:** Native (1.3) ``` @Target([AnnotationTarget.FUNCTION]) annotation class ObjCAction ``` Makes Kotlin method in Objective-C class accessible through Objective-C dispatch to be used as action sent by control in UIKit or AppKit. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Makes Kotlin method in Objective-C class accessible through Objective-C dispatch to be used as action sent by control in UIKit or AppKit. ``` ObjCAction() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCAction](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ObjCAction() ``` Makes Kotlin method in Objective-C class accessible through Objective-C dispatch to be used as action sent by control in UIKit or AppKit. kotlin IntVarOf IntVarOf ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [IntVarOf](index) **Platform and version requirements:** Native (1.3) ``` class IntVarOf<T : Int> : CPrimitiveVar ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` IntVarOf(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T : Int> IntVarOf<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [IntVarOf](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [IntVarOf](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` IntVarOf(rawPtr: NativePtr) ``` kotlin ObjCOutlet ObjCOutlet ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCOutlet](index) **Platform and version requirements:** Native (1.3) ``` @Target([AnnotationTarget.PROPERTY]) annotation class ObjCOutlet ``` Makes Kotlin property in Objective-C class settable through Objective-C dispatch to be used as IB outlet. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Makes Kotlin property in Objective-C class settable through Objective-C dispatch to be used as IB outlet. ``` ObjCOutlet() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCOutlet](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ObjCOutlet() ``` Makes Kotlin property in Objective-C class settable through Objective-C dispatch to be used as IB outlet. kotlin CEnum CEnum ===== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CEnum](index) **Platform and version requirements:** Native (1.3) ``` interface CEnum ``` **Deprecated:** Will be removed. Properties ---------- **Platform and version requirements:** Native (1.3) #### <value> ``` abstract val value: Any ``` kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CEnum](index) / <value> **Platform and version requirements:** Native (1.3) ``` abstract val value: Any ``` kotlin nativeHeap nativeHeap ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [nativeHeap](index) **Platform and version requirements:** Native (1.3) ``` object nativeHeap : NativeFreeablePlacement ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <alloc> ``` fun alloc(size: Long, align: Int): NativePointed ``` **Platform and version requirements:** Native (1.3) #### <free> ``` fun free(mem: NativePtr) ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [alloc](../alloc) Allocates variable of given type. ``` fun <T : CVariable> NativePlacement.alloc(): T ``` Allocates variable of given type and initializes it applying given block. ``` fun <T : CVariable> NativePlacement.alloc(     initialize: T.() -> Unit ): T ``` Allocates variable with given value type and initializes it with given value. ``` fun <T : Boolean> NativePlacement.alloc(     value: T ): BooleanVarOf<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArray](../alloc-array) Allocates C array of given elements type and length. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int ): CArrayPointer<T> ``` Allocates C array of given elements type and length, and initializes its elements applying given block. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long,     initializer: T.(index: Long) -> Unit ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int,     initializer: T.(index: Int) -> Unit ): CArrayPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOf](../alloc-array-of) Allocates C array of given values. ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     vararg elements: T? ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     elements: List<T?> ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun NativePlacement.allocArrayOf(     elements: ByteArray ): CArrayPointer<ByteVar> ``` ``` fun NativePlacement.allocArrayOf(     vararg elements: Float ): CArrayPointer<FloatVar> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOfPointersTo](../alloc-array-of-pointers-to) Allocates C array of pointers to given elements. ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     elements: List<T?> ): CArrayPointer<CPointerVar<T>> ``` ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     vararg elements: T? ): CArrayPointer<CPointerVar<T>> ``` **Platform and version requirements:** Native (1.3) #### [allocPointerTo](../alloc-pointer-to) ``` fun <T : CPointed> NativePlacement.allocPointerTo(): CPointerVar<T> ``` **Platform and version requirements:** Native (1.3) #### [free](../free) ``` fun NativeFreeablePlacement.free(pointer: CPointer<*>) ``` ``` fun NativeFreeablePlacement.free(pointed: NativePointed) ``` kotlin alloc alloc ===== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [nativeHeap](index) / <alloc> **Platform and version requirements:** Native (1.3) ``` fun alloc(size: Long, align: Int): NativePointed ``` kotlin free free ==== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [nativeHeap](index) / <free> **Platform and version requirements:** Native (1.3) ``` fun free(mem: NativePtr) ``` kotlin CEnumVar CEnumVar ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CEnumVar](index) **Platform and version requirements:** Native (1.3) ``` abstract class CEnumVar : CPrimitiveVar ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` CEnumVar(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CEnumVar](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` CEnumVar(rawPtr: NativePtr) ``` kotlin NativePlacement NativePlacement =============== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [NativePlacement](index) **Platform and version requirements:** Native (1.3) ``` interface NativePlacement ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <alloc> ``` abstract fun alloc(size: Long, align: Int): NativePointed ``` ``` open fun alloc(size: Int, align: Int): NativePointed ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [alloc](../alloc) Allocates variable of given type. ``` fun <T : CVariable> NativePlacement.alloc(): T ``` Allocates variable of given type and initializes it applying given block. ``` fun <T : CVariable> NativePlacement.alloc(     initialize: T.() -> Unit ): T ``` Allocates variable with given value type and initializes it with given value. ``` fun <T : Boolean> NativePlacement.alloc(     value: T ): BooleanVarOf<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArray](../alloc-array) Allocates C array of given elements type and length. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int ): CArrayPointer<T> ``` Allocates C array of given elements type and length, and initializes its elements applying given block. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long,     initializer: T.(index: Long) -> Unit ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int,     initializer: T.(index: Int) -> Unit ): CArrayPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOf](../alloc-array-of) Allocates C array of given values. ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     vararg elements: T? ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     elements: List<T?> ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun NativePlacement.allocArrayOf(     elements: ByteArray ): CArrayPointer<ByteVar> ``` ``` fun NativePlacement.allocArrayOf(     vararg elements: Float ): CArrayPointer<FloatVar> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOfPointersTo](../alloc-array-of-pointers-to) Allocates C array of pointers to given elements. ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     elements: List<T?> ): CArrayPointer<CPointerVar<T>> ``` ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     vararg elements: T? ): CArrayPointer<CPointerVar<T>> ``` **Platform and version requirements:** Native (1.3) #### [allocPointerTo](../alloc-pointer-to) ``` fun <T : CPointed> NativePlacement.allocPointerTo(): CPointerVar<T> ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [AutofreeScope](../-autofree-scope/index) ``` abstract class AutofreeScope : DeferScope, NativePlacement ``` **Platform and version requirements:** Native (1.3) #### [NativeFreeablePlacement](../-native-freeable-placement/index) ``` interface NativeFreeablePlacement : NativePlacement ```
programming_docs
kotlin alloc alloc ===== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [NativePlacement](index) / <alloc> **Platform and version requirements:** Native (1.3) ``` abstract fun alloc(size: Long, align: Int): NativePointed ``` ``` open fun alloc(size: Int, align: Int): NativePointed ``` kotlin DeferScope DeferScope ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [DeferScope](index) **Platform and version requirements:** Native (1.3) ``` open class DeferScope ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` DeferScope() ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <defer> ``` fun defer(block: () -> Unit) ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [AutofreeScope](../-autofree-scope/index) ``` abstract class AutofreeScope : DeferScope, NativePlacement ``` kotlin defer defer ===== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [DeferScope](index) / <defer> **Platform and version requirements:** Native (1.3) ``` inline fun defer(crossinline block: () -> Unit) ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [DeferScope](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` DeferScope() ``` kotlin memScope memScope ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [MemScope](index) / [memScope](mem-scope) **Platform and version requirements:** Native (1.3) ``` val memScope: MemScope ``` kotlin MemScope MemScope ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [MemScope](index) **Platform and version requirements:** Native (1.3) ``` class MemScope : ArenaBase ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` MemScope() ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### [memScope](mem-scope) ``` val memScope: MemScope ``` **Platform and version requirements:** Native (1.3) #### <ptr> ``` val <T : CVariable> CValues<T>.ptr: CPointer<T> ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [alloc](../alloc) Allocates variable of given type. ``` fun <T : CVariable> NativePlacement.alloc(): T ``` Allocates variable of given type and initializes it applying given block. ``` fun <T : CVariable> NativePlacement.alloc(     initialize: T.() -> Unit ): T ``` Allocates variable with given value type and initializes it with given value. ``` fun <T : Boolean> NativePlacement.alloc(     value: T ): BooleanVarOf<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArray](../alloc-array) Allocates C array of given elements type and length. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int ): CArrayPointer<T> ``` Allocates C array of given elements type and length, and initializes its elements applying given block. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long,     initializer: T.(index: Long) -> Unit ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int,     initializer: T.(index: Int) -> Unit ): CArrayPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOf](../alloc-array-of) Allocates C array of given values. ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     vararg elements: T? ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     elements: List<T?> ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun NativePlacement.allocArrayOf(     elements: ByteArray ): CArrayPointer<ByteVar> ``` ``` fun NativePlacement.allocArrayOf(     vararg elements: Float ): CArrayPointer<FloatVar> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOfPointersTo](../alloc-array-of-pointers-to) Allocates C array of pointers to given elements. ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     elements: List<T?> ): CArrayPointer<CPointerVar<T>> ``` ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     vararg elements: T? ): CArrayPointer<CPointerVar<T>> ``` **Platform and version requirements:** Native (1.3) #### [allocPointerTo](../alloc-pointer-to) ``` fun <T : CPointed> NativePlacement.allocPointerTo(): CPointerVar<T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [MemScope](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` MemScope() ``` kotlin ptr ptr === [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [MemScope](index) / <ptr> **Platform and version requirements:** Native (1.3) ``` val <T : CVariable> CValues<T>.ptr: CPointer<T> ``` kotlin ObjCFactory ObjCFactory =========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCFactory](index) **Platform and version requirements:** Native (1.3) ``` @Target([AnnotationTarget.FUNCTION]) annotation class ObjCFactory ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` ObjCFactory(     selector: String,     encoding: String,     isStret: Boolean = false) ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <encoding> ``` val encoding: String ``` **Platform and version requirements:** Native (1.3) #### [isStret](is-stret) ``` val isStret: Boolean ``` **Platform and version requirements:** Native (1.3) #### <selector> ``` val selector: String ``` kotlin isStret isStret ======= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCFactory](index) / [isStret](is-stret) **Platform and version requirements:** Native (1.3) ``` val isStret: Boolean ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCFactory](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ObjCFactory(     selector: String,     encoding: String,     isStret: Boolean = false) ``` kotlin selector selector ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCFactory](index) / <selector> **Platform and version requirements:** Native (1.3) ``` val selector: String ``` kotlin encoding encoding ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCFactory](index) / <encoding> **Platform and version requirements:** Native (1.3) ``` val encoding: String ``` kotlin CStructVar CStructVar ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CStructVar](index) **Platform and version requirements:** Native (1.3) ``` abstract class CStructVar : CVariable ``` The C struct-typed variable located in memory. Types ----- **Platform and version requirements:** Native (1.3) #### [Type](-type/index) ``` open class Type : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) The C struct-typed variable located in memory. ``` CStructVar(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [arrayMemberAt](../array-member-at) ``` fun <T : CVariable> CStructVar.arrayMemberAt(     offset: Long ): CArrayPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [memberAt](../member-at) Returns the member of this [CStructVar](index) which is located by given offset in bytes. ``` fun <T : CPointed> CStructVar.memberAt(offset: Long): T ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CStructVar> T.readValue(): CValue<T> ``` ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CStructVar](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` CStructVar(rawPtr: NativePtr) ``` The C struct-typed variable located in memory. kotlin Type Type ==== [kotlin-stdlib](../../../../../../../index) / [kotlinx.cinterop](../../index) / [CStructVar](../index) / [Type](index) **Platform and version requirements:** Native (1.3) ``` open class Type : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` Type(size: Long, align: Int) ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../../index) / [kotlinx.cinterop](../../index) / [CStructVar](../index) / [Type](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` Type(size: Long, align: Int) ``` kotlin CPointed CPointed ======== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CPointed](index) **Platform and version requirements:** Native (1.3) ``` abstract class CPointed : NativePointed ``` C data or code. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) C data or code. ``` CPointed(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [CFunction](../-c-function/index) The C function. ``` class CFunction<T : Function<*>> : CPointed ``` **Platform and version requirements:** Native (1.3) #### [COpaque](../-c-opaque/index) The [CPointed](index) without any specified interpretation. ``` abstract class COpaque : CPointed ``` **Platform and version requirements:** Native (1.3) #### [CVariable](../-c-variable/index) The C data variable located in memory. ``` abstract class CVariable : CPointed ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CPointed](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` CPointed(rawPtr: NativePtr) ``` C data or code. kotlin ObjCObjectBase ObjCObjectBase ============== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCObjectBase](index) **Platform and version requirements:** Native (1.3) ``` abstract class ObjCObjectBase : ObjCObject ``` Annotations ----------- **Platform and version requirements:** Native (1.3) #### [OverrideInit](-override-init/index) ``` annotation class OverrideInit ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` ObjCObjectBase() ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [initBy](../init-by) ``` fun <T : ObjCObjectBase> T.initBy(constructorCall: T): T ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [ObjCObjectBaseMeta](../-obj-c-object-base-meta/index) ``` abstract class ObjCObjectBaseMeta :      ObjCObjectBase,     ObjCObjectMeta ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCObjectBase](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` protected ObjCObjectBase() ``` kotlin OverrideInit OverrideInit ============ [kotlin-stdlib](../../../../../../../index) / [kotlinx.cinterop](../../index) / [ObjCObjectBase](../index) / [OverrideInit](index) **Platform and version requirements:** Native (1.3) ``` @Target([AnnotationTarget.CONSTRUCTOR]) annotation class OverrideInit ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` OverrideInit() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../../index) / [kotlinx.cinterop](../../index) / [ObjCObjectBase](../index) / [OverrideInit](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` OverrideInit() ``` kotlin ObjCConstructor ObjCConstructor =============== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCConstructor](index) **Platform and version requirements:** Native (1.3) ``` @Target([AnnotationTarget.CONSTRUCTOR]) annotation class ObjCConstructor ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` ObjCConstructor(initSelector: String, designated: Boolean) ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <designated> ``` val designated: Boolean ``` **Platform and version requirements:** Native (1.3) #### [initSelector](init-selector) ``` val initSelector: String ``` kotlin initSelector initSelector ============ [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCConstructor](index) / [initSelector](init-selector) **Platform and version requirements:** Native (1.3) ``` val initSelector: String ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCConstructor](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ObjCConstructor(initSelector: String, designated: Boolean) ``` kotlin designated designated ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCConstructor](index) / <designated> **Platform and version requirements:** Native (1.3) ``` val designated: Boolean ``` kotlin Pinned Pinned ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [Pinned](index) **Platform and version requirements:** Native (1.3) ``` data class Pinned<out T : Any> ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <get> Returns the underlying pinned object. ``` fun get(): T ``` **Platform and version requirements:** Native (1.3) #### <unpin> Disposes the handle. It must not be [used](get) after that. ``` fun unpin() ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [addressOf](../address-of) ``` fun Pinned<ByteArray>.addressOf(     index: Int ): CPointer<ByteVar> ``` ``` fun Pinned<String>.addressOf(index: Int): CPointer<COpaque> ``` ``` fun Pinned<CharArray>.addressOf(     index: Int ): CPointer<COpaque> ``` ``` fun Pinned<ShortArray>.addressOf(     index: Int ): CPointer<ShortVar> ``` ``` fun Pinned<IntArray>.addressOf(index: Int): CPointer<IntVar> ``` ``` fun Pinned<LongArray>.addressOf(     index: Int ): CPointer<LongVar> ``` ``` fun Pinned<UByteArray>.addressOf(     index: Int ): CPointer<UByteVar> ``` ``` fun Pinned<UShortArray>.addressOf(     index: Int ): CPointer<UShortVar> ``` ``` fun Pinned<UIntArray>.addressOf(     index: Int ): CPointer<UIntVar> ``` ``` fun Pinned<ULongArray>.addressOf(     index: Int ): CPointer<ULongVar> ``` ``` fun Pinned<FloatArray>.addressOf(     index: Int ): CPointer<FloatVar> ``` ``` fun Pinned<DoubleArray>.addressOf(     index: Int ): CPointer<DoubleVar> ``` kotlin unpin unpin ===== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [Pinned](index) / <unpin> **Platform and version requirements:** Native (1.3) ``` fun unpin() ``` Disposes the handle. It must not be [used](get) after that. kotlin get get === [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [Pinned](index) / <get> **Platform and version requirements:** Native (1.3) ``` fun get(): T ``` Returns the underlying pinned object. kotlin CFunction CFunction ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CFunction](index) **Platform and version requirements:** Native (1.3) ``` class CFunction<T : Function<*>> : CPointed ``` The C function. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) The C function. ``` CFunction(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CFunction](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` CFunction(rawPtr: NativePtr) ``` The C function. kotlin AutofreeScope AutofreeScope ============= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [AutofreeScope](index) **Platform and version requirements:** Native (1.3) ``` abstract class AutofreeScope : DeferScope, NativePlacement ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` AutofreeScope() ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <alloc> ``` abstract fun alloc(size: Long, align: Int): NativePointed ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [alloc](../alloc) Allocates variable of given type. ``` fun <T : CVariable> NativePlacement.alloc(): T ``` Allocates variable of given type and initializes it applying given block. ``` fun <T : CVariable> NativePlacement.alloc(     initialize: T.() -> Unit ): T ``` Allocates variable with given value type and initializes it with given value. ``` fun <T : Boolean> NativePlacement.alloc(     value: T ): BooleanVarOf<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArray](../alloc-array) Allocates C array of given elements type and length. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int ): CArrayPointer<T> ``` Allocates C array of given elements type and length, and initializes its elements applying given block. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long,     initializer: T.(index: Long) -> Unit ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int,     initializer: T.(index: Int) -> Unit ): CArrayPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOf](../alloc-array-of) Allocates C array of given values. ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     vararg elements: T? ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     elements: List<T?> ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun NativePlacement.allocArrayOf(     elements: ByteArray ): CArrayPointer<ByteVar> ``` ``` fun NativePlacement.allocArrayOf(     vararg elements: Float ): CArrayPointer<FloatVar> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOfPointersTo](../alloc-array-of-pointers-to) Allocates C array of pointers to given elements. ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     elements: List<T?> ): CArrayPointer<CPointerVar<T>> ``` ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     vararg elements: T? ): CArrayPointer<CPointerVar<T>> ``` **Platform and version requirements:** Native (1.3) #### [allocPointerTo](../alloc-pointer-to) ``` fun <T : CPointed> NativePlacement.allocPointerTo(): CPointerVar<T> ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [ArenaBase](../-arena-base/index) ``` open class ArenaBase : AutofreeScope ```
programming_docs
kotlin alloc alloc ===== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [AutofreeScope](index) / <alloc> **Platform and version requirements:** Native (1.3) ``` abstract fun alloc(size: Long, align: Int): NativePointed ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [AutofreeScope](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` AutofreeScope() ``` kotlin ManagedType ManagedType =========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ManagedType](index) **Platform and version requirements:** Native (1.3) ``` abstract class ManagedType<T : CStructVar> ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` ManagedType(cpp: T) ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <cpp> ``` val cpp: T ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) ``` val <T : CStructVar> ManagedType<T>.ptr: CPointer<T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ManagedType](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ManagedType(cpp: T) ``` kotlin cpp cpp === [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ManagedType](index) / <cpp> **Platform and version requirements:** Native (1.3) ``` val cpp: T ``` kotlin dispose dispose ======= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [StableRef](index) / <dispose> **Platform and version requirements:** Native (1.3) ``` fun dispose() ``` Disposes the handle. It must not be used after that. kotlin StableRef StableRef ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [StableRef](index) **Platform and version requirements:** Native (1.3) ``` class StableRef<out T : Any> ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <value> ``` val value: COpaquePointer ``` Functions --------- **Platform and version requirements:** Native (1.3) #### [asCPointer](as-c-pointer) Converts the handle to C pointer. ``` fun asCPointer(): COpaquePointer ``` **Platform and version requirements:** Native (1.3) #### <dispose> Disposes the handle. It must not be used after that. ``` fun dispose() ``` **Platform and version requirements:** Native (1.3) #### <get> Returns the object this handle was [created](create) for. ``` fun get(): T ``` Companion Object Functions -------------------------- **Platform and version requirements:** Native (1.3) #### <create> Creates a handle for given object. ``` fun <T : Any> create(any: T): StableRef<T> ``` **Platform and version requirements:** Native (1.3) #### [fromValue](from-value) Creates [StableRef](index) from given raw value. ``` fun fromValue(value: COpaquePointer): StableRef<Any> ``` kotlin fromValue fromValue ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [StableRef](index) / [fromValue](from-value) **Platform and version requirements:** Native (1.3) ``` fun fromValue(value: COpaquePointer): StableRef<Any> ``` **Deprecated:** Use CPointer<\*>.asStableRef<T>() instead Creates [StableRef](index) from given raw value. Parameters ---------- `value` - must be a [value](from-value#kotlinx.cinterop.StableRef.Companion%24fromValue(kotlinx.cinterop.CPointer((kotlinx.cinterop.CPointed)))/value) of some [StableRef](index) kotlin create create ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [StableRef](index) / <create> **Platform and version requirements:** Native (1.3) ``` fun <T : Any> create(any: T): StableRef<T> ``` Creates a handle for given object. kotlin asCPointer asCPointer ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [StableRef](index) / [asCPointer](as-c-pointer) **Platform and version requirements:** Native (1.3) ``` fun asCPointer(): COpaquePointer ``` Converts the handle to C pointer. **See Also** [asStableRef](../as-stable-ref) kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [StableRef](index) / <value> **Platform and version requirements:** Native (1.3) ``` val value: COpaquePointer ``` **Deprecated:** Use .asCPointer() instead kotlin get get === [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [StableRef](index) / <get> **Platform and version requirements:** Native (1.3) ``` fun get(): T ``` Returns the object this handle was [created](create) for. kotlin InteropStubs InteropStubs ============ [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [InteropStubs](index) **Platform and version requirements:** Native (1.3) ``` @Target([AnnotationTarget.FILE]) annotation class InteropStubs ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` InteropStubs() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [InteropStubs](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` InteropStubs() ``` kotlin UnsafeNumber UnsafeNumber ============ [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [UnsafeNumber](index) **Platform and version requirements:** Native (1.3) ``` @Target([AnnotationTarget.TYPEALIAS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY]) annotation class UnsafeNumber ``` Marker for declarations that depend on numeric types of different bit width on at least two platforms. Parameters ---------- `actualPlatformTypes` - : Contains platform types represented as `{konanTarget}: {type fqn}` e.g. linux\_x64:kotlin.Int,linux\_arm64:kotlin.Long Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Marker for declarations that depend on numeric types of different bit width on at least two platforms. ``` UnsafeNumber(actualPlatformTypes: Array<String>) ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### [actualPlatformTypes](actual-platform-types) : Contains platform types represented as `{konanTarget}: {type fqn}` e.g. linux\_x64:kotlin.Int,linux\_arm64:kotlin.Long ``` val actualPlatformTypes: Array<String> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [UnsafeNumber](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` UnsafeNumber(actualPlatformTypes: Array<String>) ``` Marker for declarations that depend on numeric types of different bit width on at least two platforms. Parameters ---------- `actualPlatformTypes` - : Contains platform types represented as `{konanTarget}: {type fqn}` e.g. linux\_x64:kotlin.Int,linux\_arm64:kotlin.Long kotlin actualPlatformTypes actualPlatformTypes =================== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [UnsafeNumber](index) / [actualPlatformTypes](actual-platform-types) **Platform and version requirements:** Native (1.3) ``` val actualPlatformTypes: Array<String> ``` : Contains platform types represented as `{konanTarget}: {type fqn}` e.g. linux\_x64:kotlin.Int,linux\_arm64:kotlin.Long kotlin UIntVarOf UIntVarOf ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [UIntVarOf](index) **Platform and version requirements:** Native (1.3) ``` class UIntVarOf<T : UInt> : CPrimitiveVar ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` UIntVarOf(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T : UInt> UIntVarOf<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [UIntVarOf](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [UIntVarOf](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` UIntVarOf(rawPtr: NativePtr) ``` kotlin DoubleVarOf DoubleVarOf =========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [DoubleVarOf](index) **Platform and version requirements:** Native (1.3) ``` class DoubleVarOf<T : Double> : CPrimitiveVar ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` DoubleVarOf(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T : Double> DoubleVarOf<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [DoubleVarOf](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [DoubleVarOf](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` DoubleVarOf(rawPtr: NativePtr) ``` kotlin NativeFreeablePlacement NativeFreeablePlacement ======================= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [NativeFreeablePlacement](index) **Platform and version requirements:** Native (1.3) ``` interface NativeFreeablePlacement : NativePlacement ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <free> ``` abstract fun free(mem: NativePtr) ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [alloc](../alloc) Allocates variable of given type. ``` fun <T : CVariable> NativePlacement.alloc(): T ``` Allocates variable of given type and initializes it applying given block. ``` fun <T : CVariable> NativePlacement.alloc(     initialize: T.() -> Unit ): T ``` Allocates variable with given value type and initializes it with given value. ``` fun <T : Boolean> NativePlacement.alloc(     value: T ): BooleanVarOf<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArray](../alloc-array) Allocates C array of given elements type and length. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int ): CArrayPointer<T> ``` Allocates C array of given elements type and length, and initializes its elements applying given block. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long,     initializer: T.(index: Long) -> Unit ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int,     initializer: T.(index: Int) -> Unit ): CArrayPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOf](../alloc-array-of) Allocates C array of given values. ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     vararg elements: T? ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     elements: List<T?> ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun NativePlacement.allocArrayOf(     elements: ByteArray ): CArrayPointer<ByteVar> ``` ``` fun NativePlacement.allocArrayOf(     vararg elements: Float ): CArrayPointer<FloatVar> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOfPointersTo](../alloc-array-of-pointers-to) Allocates C array of pointers to given elements. ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     elements: List<T?> ): CArrayPointer<CPointerVar<T>> ``` ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     vararg elements: T? ): CArrayPointer<CPointerVar<T>> ``` **Platform and version requirements:** Native (1.3) #### [allocPointerTo](../alloc-pointer-to) ``` fun <T : CPointed> NativePlacement.allocPointerTo(): CPointerVar<T> ``` **Platform and version requirements:** Native (1.3) #### [free](../free) ``` fun NativeFreeablePlacement.free(pointer: CPointer<*>) ``` ``` fun NativeFreeablePlacement.free(pointed: NativePointed) ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [nativeHeap](../native-heap/index) ``` object nativeHeap : NativeFreeablePlacement ``` kotlin free free ==== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [NativeFreeablePlacement](index) / <free> **Platform and version requirements:** Native (1.3) ``` abstract fun free(mem: NativePtr) ``` kotlin UByteVarOf UByteVarOf ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [UByteVarOf](index) **Platform and version requirements:** Native (1.3) ``` class UByteVarOf<T : UByte> : CPrimitiveVar ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` UByteVarOf(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T : UByte> UByteVarOf<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [UByteVarOf](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [UByteVarOf](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` UByteVarOf(rawPtr: NativePtr) ``` kotlin COpaque COpaque ======= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [COpaque](index) **Platform and version requirements:** Native (1.3) ``` abstract class COpaque : CPointed ``` The [CPointed](../-c-pointed/index) without any specified interpretation. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) The [CPointed](../-c-pointed/index) without any specified interpretation. ``` COpaque(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [COpaque](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` COpaque(rawPtr: NativePtr) ``` The [CPointed](../-c-pointed/index) without any specified interpretation. kotlin Vector128VarOf Vector128VarOf ============== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [Vector128VarOf](index) **Platform and version requirements:** Native (1.3) ``` class Vector128VarOf<T : Vector128> : CVariable ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` Vector128VarOf(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T : Vector128> Vector128VarOf<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ```
programming_docs
kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [Vector128VarOf](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [Vector128VarOf](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` Vector128VarOf(rawPtr: NativePtr) ``` kotlin LongVarOf LongVarOf ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [LongVarOf](index) **Platform and version requirements:** Native (1.3) ``` class LongVarOf<T : Long> : CPrimitiveVar ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` LongVarOf(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T : Long> LongVarOf<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [LongVarOf](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [LongVarOf](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` LongVarOf(rawPtr: NativePtr) ``` kotlin BooleanVarOf BooleanVarOf ============ [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [BooleanVarOf](index) **Platform and version requirements:** Native (1.3) ``` class BooleanVarOf<T : Boolean> : CPrimitiveVar ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` BooleanVarOf(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T : Boolean> BooleanVarOf<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [BooleanVarOf](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [BooleanVarOf](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` BooleanVarOf(rawPtr: NativePtr) ``` kotlin ExportObjCClass ExportObjCClass =============== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ExportObjCClass](index) **Platform and version requirements:** Native (1.3) ``` @Target([AnnotationTarget.CLASS]) annotation class ExportObjCClass ``` Makes Kotlin subclass of Objective-C class visible for runtime lookup after Kotlin `main` function gets invoked. Note: runtime lookup can be forced even when the class is referenced statically from Objective-C source code by adding `__attribute__((objc_runtime_visible))` to its `@interface`. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Makes Kotlin subclass of Objective-C class visible for runtime lookup after Kotlin `main` function gets invoked. ``` ExportObjCClass(name: String = "") ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <name> ``` val name: String ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ExportObjCClass](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ExportObjCClass(name: String = "") ``` Makes Kotlin subclass of Objective-C class visible for runtime lookup after Kotlin `main` function gets invoked. Note: runtime lookup can be forced even when the class is referenced statically from Objective-C source code by adding `__attribute__((objc_runtime_visible))` to its `@interface`. kotlin name name ==== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ExportObjCClass](index) / <name> **Platform and version requirements:** Native (1.3) ``` val name: String ``` kotlin NativePointed NativePointed ============= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [NativePointed](index) **Platform and version requirements:** Native (1.3) ``` open class NativePointed ``` The entity which has an associated native pointer. Subtypes are supposed to represent interpretations of the pointed data or code. This interface is likely to be handled by compiler magic and shouldn't be subtyped by arbitrary classes. TODO: the behavior of [equals](../../kotlin/-any/equals#kotlin.Any%24equals(kotlin.Any?)), [hashCode](../../kotlin/-any/hash-code#kotlin.Any%24hashCode()) and [toString](../../kotlin/-any/to-string#kotlin.Any%24toString()) differs on Native and JVM backends. Properties ---------- **Platform and version requirements:** Native (1.3) #### [rawPtr](raw-ptr) ``` var rawPtr: NativePtr ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [reinterpret](../reinterpret) Changes the interpretation of the pointed data or code. ``` fun <T : NativePointed> NativePointed.reinterpret(): T ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [CPointed](../-c-pointed/index) C data or code. ``` abstract class CPointed : NativePointed ``` kotlin rawPtr rawPtr ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [NativePointed](index) / [rawPtr](raw-ptr) **Platform and version requirements:** Native (1.3) ``` var rawPtr: NativePtr ``` kotlin CVariable CVariable ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CVariable](index) **Platform and version requirements:** Native (1.3) ``` abstract class CVariable : CPointed ``` The C data variable located in memory. The non-abstract subclasses should represent the (complete) C data type and thus specify size and alignment. Each such subclass must have a companion object which is a [Type](-type/index). Types ----- **Platform and version requirements:** Native (1.3) #### [Type](-type/index) The (complete) C data type. ``` open class Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) The C data variable located in memory. ``` CVariable(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` Inheritors ---------- **Platform and version requirements:** Native (1.3) #### [CPointerVarOf](../-c-pointer-var-of/index) ``` class CPointerVarOf<T : CPointer<*>> : CVariable ``` **Platform and version requirements:** Native (1.3) #### [CPrimitiveVar](../-c-primitive-var/index) The C primitive-typed variable located in memory. ``` sealed class CPrimitiveVar : CVariable ``` **Platform and version requirements:** Native (1.3) #### [CStructVar](../-c-struct-var/index) The C struct-typed variable located in memory. ``` abstract class CStructVar : CVariable ``` **Platform and version requirements:** Native (1.3) #### [ObjCNotImplementedVar](../-obj-c-not-implemented-var/index) ``` class ObjCNotImplementedVar<T> : CVariable ``` **Platform and version requirements:** Native (1.3) #### [ObjCObjectVar](../-obj-c-object-var/index) ``` class ObjCObjectVar<T> : CVariable ``` **Platform and version requirements:** Native (1.3) #### [Vector128VarOf](../-vector128-var-of/index) ``` class Vector128VarOf<T : Vector128> : CVariable ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [CVariable](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` CVariable(rawPtr: NativePtr) ``` The C data variable located in memory. The non-abstract subclasses should represent the (complete) C data type and thus specify size and alignment. Each such subclass must have a companion object which is a [Type](-type/index). kotlin size size ==== [kotlin-stdlib](../../../../../../../index) / [kotlinx.cinterop](../../index) / [CVariable](../index) / [Type](index) / <size> **Platform and version requirements:** Native (1.3) ``` val size: Long ``` the size in bytes of data of this type kotlin Type Type ==== [kotlin-stdlib](../../../../../../../index) / [kotlinx.cinterop](../../index) / [CVariable](../index) / [Type](index) **Platform and version requirements:** Native (1.3) ``` open class Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. The (complete) C data type. Parameters ---------- `size` - the size in bytes of data of this type `align` - the alignments in bytes that is enough for this data type. It may be greater than actually required for simplicity. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) The (complete) C data type. ``` Type(size: Long, align: Int) ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <align> the alignments in bytes that is enough for this data type. It may be greater than actually required for simplicity. ``` val align: Int ``` **Platform and version requirements:** Native (1.3) #### <size> the size in bytes of data of this type ``` val size: Long ``` kotlin align align ===== [kotlin-stdlib](../../../../../../../index) / [kotlinx.cinterop](../../index) / [CVariable](../index) / [Type](index) / <align> **Platform and version requirements:** Native (1.3) ``` val align: Int ``` the alignments in bytes that is enough for this data type. It may be greater than actually required for simplicity. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../../index) / [kotlinx.cinterop](../../index) / [CVariable](../index) / [Type](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` Type(size: Long, align: Int) ``` The (complete) C data type. Parameters ---------- `size` - the size in bytes of data of this type `align` - the alignments in bytes that is enough for this data type. It may be greater than actually required for simplicity. kotlin ExternalObjCClass ExternalObjCClass ================= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ExternalObjCClass](index) **Platform and version requirements:** Native (1.3) ``` @Target([AnnotationTarget.CLASS]) annotation class ExternalObjCClass ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` ExternalObjCClass(     protocolGetter: String = "",     binaryName: String = "") ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### [binaryName](binary-name) ``` val binaryName: String ``` **Platform and version requirements:** Native (1.3) #### [protocolGetter](protocol-getter) ``` val protocolGetter: String ``` kotlin binaryName binaryName ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ExternalObjCClass](index) / [binaryName](binary-name) **Platform and version requirements:** Native (1.3) ``` val binaryName: String ``` kotlin protocolGetter protocolGetter ============== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ExternalObjCClass](index) / [protocolGetter](protocol-getter) **Platform and version requirements:** Native (1.3) ``` val protocolGetter: String ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ExternalObjCClass](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ExternalObjCClass(     protocolGetter: String = "",     binaryName: String = "") ``` kotlin ObjCObjectVar ObjCObjectVar ============= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCObjectVar](index) **Platform and version requirements:** Native (1.3) ``` class ObjCObjectVar<T> : CVariable ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` ObjCObjectVar(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T> ObjCObjectVar<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCObjectVar](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCObjectVar](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ObjCObjectVar(rawPtr: NativePtr) ``` kotlin ObjCNotImplementedVar ObjCNotImplementedVar ===================== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCNotImplementedVar](index) **Platform and version requirements:** Native (1.3) ``` class ObjCNotImplementedVar<T> : CVariable ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` ObjCNotImplementedVar(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T> ObjCNotImplementedVar<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCNotImplementedVar](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead.
programming_docs
kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCNotImplementedVar](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` ObjCNotImplementedVar(rawPtr: NativePtr) ``` kotlin ObjCObjectBaseMeta ObjCObjectBaseMeta ================== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCObjectBaseMeta](index) **Platform and version requirements:** Native (1.3) ``` abstract class ObjCObjectBaseMeta :      ObjCObjectBase,     ObjCObjectMeta ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` ObjCObjectBaseMeta() ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [initBy](../init-by) ``` fun <T : ObjCObjectBase> T.initBy(constructorCall: T): T ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [ObjCObjectBaseMeta](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` protected ObjCObjectBaseMeta() ``` kotlin FloatVarOf FloatVarOf ========== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [FloatVarOf](index) **Platform and version requirements:** Native (1.3) ``` class FloatVarOf<T : Float> : CPrimitiveVar ``` Types ----- **Platform and version requirements:** Native (1.3) #### [Companion](-companion) ``` companion object Companion : Type ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` FloatVarOf(rawPtr: NativePtr) ``` Extension Properties -------------------- **Platform and version requirements:** Native (1.3) #### [ptr](../ptr) Returns the pointer to this data or code. ``` val <T : CPointed> T.ptr: CPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [rawPtr](../raw-ptr) ``` val NativePointed?.rawPtr: NativePtr ``` **Platform and version requirements:** Native (1.3) #### [value](../value) ``` var <T : Float> FloatVarOf<T>.value: T ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getRawPointer](../get-raw-pointer) ``` fun NativePointed.getRawPointer(): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [readValue](../read-value) ``` fun <T : CVariable> CPointed.readValue(     size: Long,     align: Int ): CValue<T> ``` **Platform and version requirements:** Native (1.3) #### [readValues](../read-values) ``` fun <T : CVariable> CPointed.readValues(     size: Int,     align: Int ): CValues<T> ``` ``` fun <T : CVariable> T.readValues(count: Int): CValues<T> ``` kotlin Companion Companion ========= [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [FloatVarOf](index) / [Companion](-companion) **Platform and version requirements:** Native (1.3) ``` companion object Companion : Type ``` **Deprecated:** Use sizeOf<T>() or alignOf<T>() instead. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [FloatVarOf](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` FloatVarOf(rawPtr: NativePtr) ``` kotlin Arena Arena ===== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [Arena](index) **Platform and version requirements:** Native (1.3) ``` class Arena : ArenaBase ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` Arena(parent: NativeFreeablePlacement = nativeHeap) ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <clear> ``` fun clear() ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [alloc](../alloc) Allocates variable of given type. ``` fun <T : CVariable> NativePlacement.alloc(): T ``` Allocates variable of given type and initializes it applying given block. ``` fun <T : CVariable> NativePlacement.alloc(     initialize: T.() -> Unit ): T ``` Allocates variable with given value type and initializes it with given value. ``` fun <T : Boolean> NativePlacement.alloc(     value: T ): BooleanVarOf<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArray](../alloc-array) Allocates C array of given elements type and length. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int ): CArrayPointer<T> ``` Allocates C array of given elements type and length, and initializes its elements applying given block. ``` fun <T : CVariable> NativePlacement.allocArray(     length: Long,     initializer: T.(index: Long) -> Unit ): CArrayPointer<T> ``` ``` fun <T : CVariable> NativePlacement.allocArray(     length: Int,     initializer: T.(index: Int) -> Unit ): CArrayPointer<T> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOf](../alloc-array-of) Allocates C array of given values. ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     vararg elements: T? ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun <T : CPointer<*>> NativePlacement.allocArrayOf(     elements: List<T?> ): CArrayPointer<CPointerVarOf<T>> ``` ``` fun NativePlacement.allocArrayOf(     elements: ByteArray ): CArrayPointer<ByteVar> ``` ``` fun NativePlacement.allocArrayOf(     vararg elements: Float ): CArrayPointer<FloatVar> ``` **Platform and version requirements:** Native (1.3) #### [allocArrayOfPointersTo](../alloc-array-of-pointers-to) Allocates C array of pointers to given elements. ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     elements: List<T?> ): CArrayPointer<CPointerVar<T>> ``` ``` fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(     vararg elements: T? ): CArrayPointer<CPointerVar<T>> ``` **Platform and version requirements:** Native (1.3) #### [allocPointerTo](../alloc-pointer-to) ``` fun <T : CPointed> NativePlacement.allocPointerTo(): CPointerVar<T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [Arena](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` Arena(parent: NativeFreeablePlacement = nativeHeap) ``` kotlin clear clear ===== [kotlin-stdlib](../../../../../../index) / [kotlinx.cinterop](../index) / [Arena](index) / <clear> **Platform and version requirements:** Native (1.3) ``` fun clear() ``` kotlin Package kotlin.properties Package kotlin.properties ========================= [kotlin-stdlib](../../../../../index) / [kotlin.properties](index) Standard implementations of delegates for [delegated properties](../../../../../docs/delegated-properties) and helper functions for implementing custom delegates. Types ----- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [Delegates](-delegates/index) Standard property delegates. ``` object Delegates ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [ObservableProperty](-observable-property/index) Implements the core logic of a property delegate for a read/write property that calls callback functions when changed. ``` abstract class ObservableProperty<V> :      ReadWriteProperty<Any?, V> ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [PropertyDelegateProvider](-property-delegate-provider/index) Base interface that can be used for implementing property delegate providers. ``` fun interface PropertyDelegateProvider<in T, out D> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [ReadOnlyProperty](-read-only-property/index) Base interface that can be used for implementing property delegates of read-only properties. ``` fun interface ReadOnlyProperty<in T, out V> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [ReadWriteProperty](-read-write-property/index) Base interface that can be used for implementing property delegates of read-write properties. ``` interface ReadWriteProperty<in T, V> : ReadOnlyProperty<T, V> ``` kotlin ReadOnlyProperty ReadOnlyProperty ================ [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [ReadOnlyProperty](index) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun interface ReadOnlyProperty<in T, out V> ``` Base interface that can be used for implementing property delegates of read-only properties. This is provided only for convenience; you don't have to extend this interface as long as your property delegate has methods with the same signatures. Parameters ---------- `T` - the type of object which owns the delegated property. `V` - the type of the property value. Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [getValue](get-value) Returns the value of the property for the given object. ``` abstract operator fun getValue(     thisRef: T,     property: KProperty<*> ): V ``` Inheritors ---------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [ReadWriteProperty](../-read-write-property/index) Base interface that can be used for implementing property delegates of read-write properties. ``` interface ReadWriteProperty<in T, V> : ReadOnlyProperty<T, V> ``` kotlin getValue getValue ======== [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [ReadOnlyProperty](index) / [getValue](get-value) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract operator fun getValue(     thisRef: T,     property: KProperty<*> ): V ``` Returns the value of the property for the given object. Parameters ---------- `thisRef` - the object for which the value is requested. `property` - the metadata for the property. **Return** the property value. kotlin Delegates Delegates ========= [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [Delegates](index) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` object Delegates ``` Standard property delegates. Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [notNull](not-null) Returns a property delegate for a read/write property with a non-`null` value that is initialized not during object construction time but at a later time. Trying to read the property before the initial value has been assigned results in an exception. ``` fun <T : Any> notNull(): ReadWriteProperty<Any?, T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <observable> Returns a property delegate for a read/write property that calls a specified callback function when changed. ``` fun <T> observable(     initialValue: T,     onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit ): ReadWriteProperty<Any?, T> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <vetoable> Returns a property delegate for a read/write property that calls a specified callback function when changed, allowing the callback to veto the modification. ``` fun <T> vetoable(     initialValue: T,     onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Boolean ): ReadWriteProperty<Any?, T> ``` kotlin observable observable ========== [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [Delegates](index) / <observable> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <T> observable(     initialValue: T,     crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit ): ReadWriteProperty<Any?, T> ``` Returns a property delegate for a read/write property that calls a specified callback function when changed. ``` import kotlin.properties.Delegates import kotlin.test.* fun main(args: Array<String>) { //sampleStart var observed = false var max: Int by Delegates.observable(0) { property, oldValue, newValue -> observed = true } println(max) // 0 println("observed is ${observed}") // false max = 10 println(max) // 10 println("observed is ${observed}") // true //sampleEnd } ``` Parameters ---------- `initialValue` - the initial value of the property. `onChange` - the callback which is called after the change of the property is made. The value of the property has already been changed when this callback is invoked. kotlin vetoable vetoable ======== [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [Delegates](index) / <vetoable> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <T> vetoable(     initialValue: T,     crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Boolean ): ReadWriteProperty<Any?, T> ``` Returns a property delegate for a read/write property that calls a specified callback function when changed, allowing the callback to veto the modification. ``` import kotlin.properties.Delegates import kotlin.test.* fun main(args: Array<String>) { //sampleStart var max: Int by Delegates.vetoable(0) { property, oldValue, newValue -> newValue > oldValue } println(max) // 0 max = 10 println(max) // 10 max = 5 println(max) // 10 //sampleEnd } ``` ``` import kotlin.properties.Delegates import kotlin.test.* fun main(args: Array<String>) { //sampleStart var max: Int by Delegates.vetoable(0) { property, oldValue, newValue -> if (newValue > oldValue) true else throw IllegalArgumentException("New value must be larger than old value.") } println(max) // 0 max = 10 println(max) // 10 // max = 5 // will fail with IllegalArgumentException //sampleEnd } ``` Parameters ---------- `initialValue` - the initial value of the property. `onChange` - the callback which is called before a change to the property value is attempted. The value of the property hasn't been changed yet, when this callback is invoked. If the callback returns `true` the value of the property is being set to the new value, and if the callback returns `false` the new value is discarded and the property remains its old value. kotlin notNull notNull ======= [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [Delegates](index) / [notNull](not-null) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun <T : Any> notNull(): ReadWriteProperty<Any?, T> ``` Returns a property delegate for a read/write property with a non-`null` value that is initialized not during object construction time but at a later time. Trying to read the property before the initial value has been assigned results in an exception. ``` import kotlin.properties.Delegates import kotlin.test.* fun main(args: Array<String>) { //sampleStart var max: Int by Delegates.notNull() // println(max) // will fail with IllegalStateException max = 10 println(max) // 10 //sampleEnd } ``` kotlin PropertyDelegateProvider PropertyDelegateProvider ======================== [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [PropertyDelegateProvider](index) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` fun interface PropertyDelegateProvider<in T, out D> ``` Base interface that can be used for implementing property delegate providers. This is provided only for convenience; you don't have to extend this interface as long as your delegate provider has a method with the same signature. Parameters ---------- `T` - the type of object which owns the delegated property. `D` - the type of property delegates this provider provides. Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [provideDelegate](provide-delegate) Returns the delegate of the property for the given object. ``` abstract operator fun provideDelegate(     thisRef: T,     property: KProperty<*> ): D ``` kotlin provideDelegate provideDelegate =============== [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [PropertyDelegateProvider](index) / [provideDelegate](provide-delegate) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract operator fun provideDelegate(     thisRef: T,     property: KProperty<*> ): D ``` Returns the delegate of the property for the given object. This function can be used to extend the logic of creating the object (e.g. perform validation checks) to which the property implementation is delegated. Parameters ---------- `thisRef` - the object for which property delegate is requested. `property` - the metadata for the property. **Return** the property delegate. kotlin beforeChange beforeChange ============ [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [ObservableProperty](index) / [beforeChange](before-change) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` protected open fun beforeChange(     property: KProperty<*>,     oldValue: V,     newValue: V ): Boolean ``` The callback which is called before a change to the property value is attempted. The value of the property hasn't been changed yet, when this callback is invoked. If the callback returns `true` the value of the property is being set to the new value, and if the callback returns `false` the new value is discarded and the property remains its old value. kotlin ObservableProperty ObservableProperty ================== [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [ObservableProperty](index) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract class ObservableProperty<V> :      ReadWriteProperty<Any?, V> ``` Implements the core logic of a property delegate for a read/write property that calls callback functions when changed. Parameters ---------- `initialValue` - the initial value of the property. Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [<init>](-init-) Implements the core logic of a property delegate for a read/write property that calls callback functions when changed. ``` ObservableProperty(initialValue: V) ``` Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [afterChange](after-change) The callback which is called after the change of the property is made. The value of the property has already been changed when this callback is invoked. ``` open fun afterChange(     property: KProperty<*>,     oldValue: V,     newValue: V) ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [beforeChange](before-change) The callback which is called before a change to the property value is attempted. The value of the property hasn't been changed yet, when this callback is invoked. If the callback returns `true` the value of the property is being set to the new value, and if the callback returns `false` the new value is discarded and the property remains its old value. ``` open fun beforeChange(     property: KProperty<*>,     oldValue: V,     newValue: V ): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [getValue](get-value) Returns the value of the property for the given object. ``` open fun getValue(thisRef: Any?, property: KProperty<*>): V ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [setValue](set-value) Sets the value of the property for the given object. ``` open fun setValue(     thisRef: Any?,     property: KProperty<*>,     value: V) ```
programming_docs
kotlin setValue setValue ======== [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [ObservableProperty](index) / [setValue](set-value) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun setValue(     thisRef: Any?,     property: KProperty<*>,     value: V) ``` Sets the value of the property for the given object. Parameters ---------- `thisRef` - the object for which the value is requested. `property` - the metadata for the property. `value` - the value to set. kotlin getValue getValue ======== [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [ObservableProperty](index) / [getValue](get-value) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun getValue(thisRef: Any?, property: KProperty<*>): V ``` Returns the value of the property for the given object. Parameters ---------- `thisRef` - the object for which the value is requested. `property` - the metadata for the property. **Return** the property value. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [ObservableProperty](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` ObservableProperty(initialValue: V) ``` Implements the core logic of a property delegate for a read/write property that calls callback functions when changed. Parameters ---------- `initialValue` - the initial value of the property. kotlin afterChange afterChange =========== [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [ObservableProperty](index) / [afterChange](after-change) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` protected open fun afterChange(     property: KProperty<*>,     oldValue: V,     newValue: V) ``` The callback which is called after the change of the property is made. The value of the property has already been changed when this callback is invoked. kotlin ReadWriteProperty ReadWriteProperty ================= [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [ReadWriteProperty](index) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` interface ReadWriteProperty<in T, V> : ReadOnlyProperty<T, V> ``` Base interface that can be used for implementing property delegates of read-write properties. This is provided only for convenience; you don't have to extend this interface as long as your property delegate has methods with the same signatures. Parameters ---------- `T` - the type of object which owns the delegated property. `V` - the type of the property value. Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [getValue](get-value) Returns the value of the property for the given object. ``` abstract operator fun getValue(     thisRef: T,     property: KProperty<*> ): V ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [setValue](set-value) Sets the value of the property for the given object. ``` abstract operator fun setValue(     thisRef: T,     property: KProperty<*>,     value: V) ``` Inheritors ---------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [ObservableProperty](../-observable-property/index) Implements the core logic of a property delegate for a read/write property that calls callback functions when changed. ``` abstract class ObservableProperty<V> :      ReadWriteProperty<Any?, V> ``` kotlin setValue setValue ======== [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [ReadWriteProperty](index) / [setValue](set-value) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract operator fun setValue(     thisRef: T,     property: KProperty<*>,     value: V) ``` Sets the value of the property for the given object. Parameters ---------- `thisRef` - the object for which the value is requested. `property` - the metadata for the property. `value` - the value to set. kotlin getValue getValue ======== [kotlin-stdlib](../../../../../../index) / [kotlin.properties](../index) / [ReadWriteProperty](index) / [getValue](get-value) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract operator fun getValue(     thisRef: T,     property: KProperty<*> ): V ``` Returns the value of the property for the given object. Parameters ---------- `thisRef` - the object for which the value is requested. `property` - the metadata for the property. **Return** the property value. kotlin freeze freeze ====== [kotlin-stdlib](../../../../../index) / [kotlin.native.concurrent](index) / <freeze> **Platform and version requirements:** Native (1.3) ``` fun <T> T.freeze(): T ``` Freezes object subgraph reachable from this object. Frozen objects can be freely shared between threads/workers. Exceptions ---------- `FreezingException` - if freezing is not possible **Return** the object itself **See Also** [ensureNeverFrozen](ensure-never-frozen) kotlin waitForMultipleFutures waitForMultipleFutures ====================== [kotlin-stdlib](../../../../../index) / [kotlin.native.concurrent](index) / [waitForMultipleFutures](wait-for-multiple-futures) **Platform and version requirements:** Native (1.3) ``` fun <T> Collection<Future<T>>.waitForMultipleFutures(     millis: Int ): Set<Future<T>> ``` **Deprecated:** Use 'waitForMultipleFutures' top-level function instead kotlin Package kotlin.native.concurrent Package kotlin.native.concurrent ================================ [kotlin-stdlib](../../../../../index) / [kotlin.native.concurrent](index) Types ----- **Platform and version requirements:** Native (1.3) #### [AtomicInt](-atomic-int/index) Wrapper around [Int](../kotlin/-int/index#kotlin.Int) with atomic synchronized operations. ``` class AtomicInt ``` **Platform and version requirements:** Native (1.3) #### [AtomicLong](-atomic-long/index) Wrapper around [Long](../kotlin/-long/index#kotlin.Long) with atomic synchronized operations. ``` class AtomicLong ``` **Platform and version requirements:** Native (1.3) #### [AtomicNativePtr](-atomic-native-ptr/index) Wrapper around [kotlinx.cinterop.NativePtr](../kotlinx.cinterop/-native-ptr) with atomic synchronized operations. ``` class AtomicNativePtr ``` **Platform and version requirements:** Native (1.3) #### [AtomicReference](-atomic-reference/index) Wrapper around Kotlin object with atomic operations. ``` class AtomicReference<T> ``` **Platform and version requirements:** Native (1.3) #### [Continuation0](-continuation0/index) ``` class Continuation0 : () -> Unit ``` **Platform and version requirements:** Native (1.3) #### [Continuation1](-continuation1/index) ``` class Continuation1<T1> : (T1) -> Unit ``` **Platform and version requirements:** Native (1.3) #### [Continuation2](-continuation2/index) ``` class Continuation2<T1, T2> : (T1, T2) -> Unit ``` **Platform and version requirements:** Native (1.3) #### [DetachedObjectGraph](-detached-object-graph/index) Detached object graph encapsulates transferrable detached subgraph which cannot be accessed externally, until it is attached with the <attach> extension function. ``` class DetachedObjectGraph<T> ``` **Platform and version requirements:** Native (1.3) #### [FreezableAtomicReference](-freezable-atomic-reference/index) Note: this class is useful only with legacy memory manager. Please use [AtomicReference](-atomic-reference/index) instead. ``` class FreezableAtomicReference<T> ``` **Platform and version requirements:** Native (1.3) #### [FreezingException](-freezing-exception/index) Exception thrown whenever freezing is not possible. ``` class FreezingException : RuntimeException ``` **Platform and version requirements:** Native (1.3) #### [Future](-future/index) ``` class Future<T> ``` **Platform and version requirements:** Native (1.3) #### [FutureState](-future-state/index) State of the future object. ``` enum class FutureState ``` **Platform and version requirements:** Native (1.3) #### [InvalidMutabilityException](-invalid-mutability-exception/index) Exception thrown whenever we attempt to mutate frozen objects. ``` class InvalidMutabilityException : RuntimeException ``` **Platform and version requirements:** Native (1.3) #### [MutableData](-mutable-data/index) Mutable concurrently accessible data buffer. Could be accessed from several workers simulteniously. ``` class MutableData ``` **Platform and version requirements:** Native (1.3) #### [TransferMode](-transfer-mode/index) Note: modern Kotlin/Native memory manager allows to share objects between threads without additional ceremonies, so TransferMode has effect only in legacy memory manager. ``` enum class TransferMode ``` **Platform and version requirements:** Native (1.3) #### [Worker](-worker/index) ``` class Worker ``` **Platform and version requirements:** Native (1.3) #### [WorkerBoundReference](-worker-bound-reference/index) A shared reference to a Kotlin object that doesn't freeze the referred object when it gets frozen itself. ``` class WorkerBoundReference<out T : Any> ``` Annotations ----------- **Platform and version requirements:** Native (1.0) #### [SharedImmutable](-shared-immutable/index) Note: this annotation has effect only in Kotlin/Native with legacy memory manager. ``` annotation class SharedImmutable ``` **Platform and version requirements:** Native (1.0) #### [ThreadLocal](-thread-local/index) Marks a top level property with a backing field or an object as thread local. The object remains mutable and it is possible to change its state, but every thread will have a distinct copy of this object, so changes in one thread are not reflected in another. ``` annotation class ThreadLocal ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### [isFrozen](is-frozen) Checks if given object is null or frozen or permanent (i.e. instantiated at compile-time). ``` val Any?.isFrozen: Boolean ``` Functions --------- **Platform and version requirements:** Native (1.3) #### [atomicLazy](atomic-lazy) Atomic lazy initializer, could be used in frozen objects, freezes initializing lambda, so use very carefully. Also, as with other uses of an [AtomicReference](-atomic-reference/index) may potentially leak memory, so it is recommended to use `atomicLazy` in cases of objects living forever, such as object signletons, or in cases where it's guaranteed not to have cyclical garbage. ``` fun <T> atomicLazy(initializer: () -> T): Lazy<T> ``` **Platform and version requirements:** Native (1.3) #### <attach> Attaches previously detached object subgraph created by [DetachedObjectGraph](-detached-object-graph/index). Please note, that once object graph is attached, the DetachedObjectGraph.stable pointer does not make sense anymore, and shall be discarded, so attach of one DetachedObjectGraph object can only happen once. ``` fun <T> DetachedObjectGraph<T>.attach(): T ``` **Platform and version requirements:** Native (1.3) #### [callContinuation0](call-continuation0) ``` fun COpaquePointer.callContinuation0() ``` **Platform and version requirements:** Native (1.3) #### [callContinuation1](call-continuation1) ``` fun <T1> COpaquePointer.callContinuation1() ``` **Platform and version requirements:** Native (1.3) #### [callContinuation2](call-continuation2) ``` fun <T1, T2> COpaquePointer.callContinuation2() ``` **Platform and version requirements:** Native (1.3) #### [ensureNeverFrozen](ensure-never-frozen) This function ensures that if we see such an object during freezing attempt - freeze fails and [FreezingException](-freezing-exception/index) is thrown. ``` fun Any.ensureNeverFrozen() ``` **Platform and version requirements:** Native (1.3) #### <freeze> Freezes object subgraph reachable from this object. Frozen objects can be freely shared between threads/workers. ``` fun <T> T.freeze(): T ``` **Platform and version requirements:** Native (1.3) #### [waitForMultipleFutures](wait-for-multiple-futures) ``` fun <T> Collection<Future<T>>.waitForMultipleFutures(     millis: Int ): Set<Future<T>> ``` **Platform and version requirements:** Native (1.3) #### [waitWorkerTermination](wait-worker-termination) ``` fun waitWorkerTermination(worker: Worker) ``` **Platform and version requirements:** Native (1.3) #### [withWorker](with-worker) Executes [block](with-worker#kotlin.native.concurrent%24withWorker(kotlin.String?,%20kotlin.Boolean,%20kotlin.Function1((kotlin.native.concurrent.Worker,%20kotlin.native.concurrent.withWorker.R)))/block) with new [Worker](-worker/index) as resource, by starting the new worker, calling provided [block](with-worker#kotlin.native.concurrent%24withWorker(kotlin.String?,%20kotlin.Boolean,%20kotlin.Function1((kotlin.native.concurrent.Worker,%20kotlin.native.concurrent.withWorker.R)))/block) (in current context) with newly started worker as this and terminating worker after the block completes. Note that this operation is pretty heavyweight, use preconfigured worker or worker pool if need to execute it frequently. ``` fun <R> withWorker(     name: String? = null,     errorReporting: Boolean = true,     block: Worker.() -> R ): R ``` kotlin atomicLazy atomicLazy ========== [kotlin-stdlib](../../../../../index) / [kotlin.native.concurrent](index) / [atomicLazy](atomic-lazy) **Platform and version requirements:** Native (1.3) ``` fun <T> atomicLazy(initializer: () -> T): Lazy<T> ``` Atomic lazy initializer, could be used in frozen objects, freezes initializing lambda, so use very carefully. Also, as with other uses of an [AtomicReference](-atomic-reference/index) may potentially leak memory, so it is recommended to use `atomicLazy` in cases of objects living forever, such as object signletons, or in cases where it's guaranteed not to have cyclical garbage. kotlin callContinuation2 callContinuation2 ================= [kotlin-stdlib](../../../../../index) / [kotlin.native.concurrent](index) / [callContinuation2](call-continuation2) **Platform and version requirements:** Native (1.3) ``` fun <T1, T2> COpaquePointer.callContinuation2() ``` kotlin attach attach ====== [kotlin-stdlib](../../../../../index) / [kotlin.native.concurrent](index) / <attach> **Platform and version requirements:** Native (1.3) ``` fun <reified T> DetachedObjectGraph<T>.attach(): T ``` Attaches previously detached object subgraph created by [DetachedObjectGraph](-detached-object-graph/index). Please note, that once object graph is attached, the DetachedObjectGraph.stable pointer does not make sense anymore, and shall be discarded, so attach of one DetachedObjectGraph object can only happen once. kotlin callContinuation1 callContinuation1 ================= [kotlin-stdlib](../../../../../index) / [kotlin.native.concurrent](index) / [callContinuation1](call-continuation1) **Platform and version requirements:** Native (1.3) ``` fun <T1> COpaquePointer.callContinuation1() ``` kotlin isFrozen isFrozen ======== [kotlin-stdlib](../../../../../index) / [kotlin.native.concurrent](index) / [isFrozen](is-frozen) **Platform and version requirements:** Native (1.3) ``` val Any?.isFrozen: Boolean ``` Checks if given object is null or frozen or permanent (i.e. instantiated at compile-time). **Return** true if given object is null or frozen or permanent kotlin callContinuation0 callContinuation0 ================= [kotlin-stdlib](../../../../../index) / [kotlin.native.concurrent](index) / [callContinuation0](call-continuation0) **Platform and version requirements:** Native (1.3) ``` fun COpaquePointer.callContinuation0() ``` kotlin waitWorkerTermination waitWorkerTermination ===================== [kotlin-stdlib](../../../../../index) / [kotlin.native.concurrent](index) / [waitWorkerTermination](wait-worker-termination) **Platform and version requirements:** Native (1.3) ``` fun waitWorkerTermination(worker: Worker) ``` kotlin withWorker withWorker ========== [kotlin-stdlib](../../../../../index) / [kotlin.native.concurrent](index) / [withWorker](with-worker) **Platform and version requirements:** Native (1.3) ``` inline fun <R> withWorker(     name: String? = null,     errorReporting: Boolean = true,     block: Worker.() -> R ): R ``` Executes [block](with-worker#kotlin.native.concurrent%24withWorker(kotlin.String?,%20kotlin.Boolean,%20kotlin.Function1((kotlin.native.concurrent.Worker,%20kotlin.native.concurrent.withWorker.R)))/block) with new [Worker](-worker/index) as resource, by starting the new worker, calling provided [block](with-worker#kotlin.native.concurrent%24withWorker(kotlin.String?,%20kotlin.Boolean,%20kotlin.Function1((kotlin.native.concurrent.Worker,%20kotlin.native.concurrent.withWorker.R)))/block) (in current context) with newly started worker as this and terminating worker after the block completes. Note that this operation is pretty heavyweight, use preconfigured worker or worker pool if need to execute it frequently. Parameters ---------- `name` - of the started worker. `errorReporting` - controls if uncaught errors in worker to be reported. `block` - to be executed. **Return** value returned by the block. kotlin ensureNeverFrozen ensureNeverFrozen ================= [kotlin-stdlib](../../../../../index) / [kotlin.native.concurrent](index) / [ensureNeverFrozen](ensure-never-frozen) **Platform and version requirements:** Native (1.3) ``` fun Any.ensureNeverFrozen() ``` This function ensures that if we see such an object during freezing attempt - freeze fails and [FreezingException](-freezing-exception/index) is thrown. Exceptions ---------- `FreezingException` - thrown immediately if this object is already frozen **See Also** <freeze> kotlin reset reset ===== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [MutableData](index) / <reset> **Platform and version requirements:** Native (1.3) ``` fun reset() ``` Reset the data buffer, makings its size 0. kotlin size size ==== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [MutableData](index) / <size> **Platform and version requirements:** Native (1.3) ``` val size: Int ``` Current data size, may concurrently change later on. kotlin withBufferLocked withBufferLocked ================ [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [MutableData](index) / [withBufferLocked](with-buffer-locked) **Platform and version requirements:** Native (1.3) ``` fun <R> withBufferLocked(     block: (array: ByteArray, dataSize: Int) -> R ): R ``` Executes provided block under lock with the raw data buffer. Block is executed under the spinlock, and must be short. kotlin MutableData MutableData =========== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [MutableData](index) **Platform and version requirements:** Native (1.3) ``` class MutableData ``` Mutable concurrently accessible data buffer. Could be accessed from several workers simulteniously. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Mutable concurrently accessible data buffer. Could be accessed from several workers simulteniously. ``` MutableData(capacity: Int = 16) ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <size> Current data size, may concurrently change later on. ``` val size: Int ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <append> Appends data to the buffer. ``` fun append(data: MutableData) ``` Appends byte array to the buffer. ``` fun append(     data: ByteArray,     fromIndex: Int = 0,     toIndex: Int = data.size) ``` Appends C data to the buffer, if `data` is null or `count` is non-positive - return. ``` fun append(data: COpaquePointer?, count: Int) ``` **Platform and version requirements:** Native (1.3) #### [copyInto](copy-into) Copies range of mutable data to the byte array. ``` fun copyInto(     output: ByteArray,     destinationIndex: Int,     startIndex: Int,     endIndex: Int) ``` **Platform and version requirements:** Native (1.3) #### <get> Get a byte from the mutable data. ``` operator fun get(index: Int): Byte ``` **Platform and version requirements:** Native (1.3) #### <reset> Reset the data buffer, makings its size 0. ``` fun reset() ``` **Platform and version requirements:** Native (1.3) #### [withBufferLocked](with-buffer-locked) Executes provided block under lock with the raw data buffer. Block is executed under the spinlock, and must be short. ``` fun <R> withBufferLocked(     block: (array: ByteArray, dataSize: Int) -> R ): R ``` **Platform and version requirements:** Native (1.3) #### [withPointerLocked](with-pointer-locked) Executes provided block under lock with raw pointer to the data stored in the buffer. Block is executed under the spinlock, and must be short. ``` fun <R> withPointerLocked(     block: (COpaquePointer, dataSize: Int) -> R ): R ```
programming_docs
kotlin append append ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [MutableData](index) / <append> **Platform and version requirements:** Native (1.3) ``` fun append(data: MutableData) ``` Appends data to the buffer. **Platform and version requirements:** Native (1.3) ``` fun append(     data: ByteArray,     fromIndex: Int = 0,     toIndex: Int = data.size) ``` Appends byte array to the buffer. **Platform and version requirements:** Native (1.3) ``` fun append(data: COpaquePointer?, count: Int) ``` Appends C data to the buffer, if `data` is null or `count` is non-positive - return. kotlin copyInto copyInto ======== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [MutableData](index) / [copyInto](copy-into) **Platform and version requirements:** Native (1.3) ``` fun copyInto(     output: ByteArray,     destinationIndex: Int,     startIndex: Int,     endIndex: Int) ``` Copies range of mutable data to the byte array. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [MutableData](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` MutableData(capacity: Int = 16) ``` Mutable concurrently accessible data buffer. Could be accessed from several workers simulteniously. kotlin withPointerLocked withPointerLocked ================= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [MutableData](index) / [withPointerLocked](with-pointer-locked) **Platform and version requirements:** Native (1.3) ``` fun <R> withPointerLocked(     block: (COpaquePointer, dataSize: Int) -> R ): R ``` Executes provided block under lock with raw pointer to the data stored in the buffer. Block is executed under the spinlock, and must be short. kotlin get get === [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [MutableData](index) / <get> **Platform and version requirements:** Native (1.3) ``` operator fun get(index: Int): Byte ``` Get a byte from the mutable data. Throws ------ `IndexOutOfBoundsException` - if index is beyond range. kotlin WorkerBoundReference WorkerBoundReference ==================== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [WorkerBoundReference](index) **Platform and version requirements:** Native (1.3) ``` class WorkerBoundReference<out T : Any> ``` A shared reference to a Kotlin object that doesn't freeze the referred object when it gets frozen itself. After freezing can be safely passed between workers, but <value> can only be accessed on the worker [WorkerBoundReference](index) was created on, unless the referred object is frozen too. Note: Garbage collector currently cannot free any reference cycles with frozen [WorkerBoundReference](index) in them. To resolve such cycles consider using [AtomicReference](../-atomic-reference/index)`<WorkerBoundReference?>` which can be explicitly nulled out. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) A shared reference to a Kotlin object that doesn't freeze the referred object when it gets frozen itself. ``` WorkerBoundReference(value: T) ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <value> The referenced value. ``` val value: T ``` **Platform and version requirements:** Native (1.3) #### [valueOrNull](value-or-null) The referenced value or null if referred object is not frozen and current worker is different from the one created this. ``` val valueOrNull: T? ``` **Platform and version requirements:** Native (1.3) #### <worker> Worker that <value> is bound to. ``` val worker: Worker ``` kotlin worker worker ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [WorkerBoundReference](index) / <worker> **Platform and version requirements:** Native (1.3) ``` val worker: Worker ``` Worker that <value> is bound to. kotlin valueOrNull valueOrNull =========== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [WorkerBoundReference](index) / [valueOrNull](value-or-null) **Platform and version requirements:** Native (1.3) ``` val valueOrNull: T? ``` The referenced value or null if referred object is not frozen and current worker is different from the one created this. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [WorkerBoundReference](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` WorkerBoundReference(value: T) ``` A shared reference to a Kotlin object that doesn't freeze the referred object when it gets frozen itself. After freezing can be safely passed between workers, but <value> can only be accessed on the worker [WorkerBoundReference](index) was created on, unless the referred object is frozen too. Note: Garbage collector currently cannot free any reference cycles with frozen [WorkerBoundReference](index) in them. To resolve such cycles consider using [AtomicReference](../-atomic-reference/index)`<WorkerBoundReference?>` which can be explicitly nulled out. kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [WorkerBoundReference](index) / <value> **Platform and version requirements:** Native (1.3) ``` val value: T ``` The referenced value. Exceptions ---------- `IncorrectDereferenceException` - if referred object is not frozen and current worker is different from the one created this. kotlin FreezingException FreezingException ================= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FreezingException](index) **Platform and version requirements:** Native (1.3) ``` class FreezingException : RuntimeException ``` Exception thrown whenever freezing is not possible. Parameters ---------- `toFreeze` - an object intended to be frozen. `blocker` - an object preventing freezing, usually one marked with [ensureNeverFrozen](../ensure-never-frozen) earlier. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Exception thrown whenever freezing is not possible. ``` FreezingException(toFreeze: Any, blocker: Any) ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getStackTraceAddresses](../../kotlin.native/get-stack-trace-addresses) Returns a list of stack trace addresses representing the stack trace pertaining to this throwable. ``` fun Throwable.getStackTraceAddresses(): List<Long> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FreezingException](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` FreezingException(toFreeze: Any, blocker: Any) ``` Exception thrown whenever freezing is not possible. Parameters ---------- `toFreeze` - an object intended to be frozen. `blocker` - an object preventing freezing, usually one marked with [ensureNeverFrozen](../ensure-never-frozen) earlier. kotlin ThreadLocal ThreadLocal =========== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [ThreadLocal](index) **Platform and version requirements:** Native (1.3) ``` @Target([AnnotationTarget.PROPERTY, AnnotationTarget.CLASS]) annotation class ThreadLocal ``` Marks a top level property with a backing field or an object as thread local. The object remains mutable and it is possible to change its state, but every thread will have a distinct copy of this object, so changes in one thread are not reflected in another. The annotation has effect only in Kotlin/Native platform. PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES. Constructors ------------ **Platform and version requirements:** Native (1.0) #### [<init>](-init-) Marks a top level property with a backing field or an object as thread local. The object remains mutable and it is possible to change its state, but every thread will have a distinct copy of this object, so changes in one thread are not reflected in another. ``` <init>() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [ThreadLocal](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` <init>() ``` Marks a top level property with a backing field or an object as thread local. The object remains mutable and it is possible to change its state, but every thread will have a distinct copy of this object, so changes in one thread are not reflected in another. The annotation has effect only in Kotlin/Native platform. PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES. kotlin compareAndSet compareAndSet ============= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicInt](index) / [compareAndSet](compare-and-set) **Platform and version requirements:** Native (1.3) ``` fun compareAndSet(expected: Int, new: Int): Boolean ``` Compares value with [expected](compare-and-set#kotlin.native.concurrent.AtomicInt%24compareAndSet(kotlin.Int,%20kotlin.Int)/expected) and replaces it with [new](compare-and-set#kotlin.native.concurrent.AtomicInt%24compareAndSet(kotlin.Int,%20kotlin.Int)/new) value if values matches. Parameters ---------- `expected` - the expected value `new` - the new value **Return** true if successful kotlin AtomicInt AtomicInt ========= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicInt](index) **Platform and version requirements:** Native (1.3) ``` class AtomicInt ``` Wrapper around [Int](../../kotlin/-int/index#kotlin.Int) with atomic synchronized operations. Legacy MM: Atomic values and freezing: this type is unique with regard to freezing. Namely, it provides mutating operations, while can participate in frozen subgraphs. So shared frozen objects can have mutable fields of [AtomicInt](index) type. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Wrapper around [Int](../../kotlin/-int/index#kotlin.Int) with atomic synchronized operations. ``` AtomicInt(value_: Int) ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <value> The value being held by this class. ``` var value: Int ``` Functions --------- **Platform and version requirements:** Native (1.3) #### [addAndGet](add-and-get) Increments the value by [delta](add-and-get#kotlin.native.concurrent.AtomicInt%24addAndGet(kotlin.Int)/delta) and returns the new value. ``` fun addAndGet(delta: Int): Int ``` **Platform and version requirements:** Native (1.3) #### [compareAndSet](compare-and-set) Compares value with [expected](compare-and-set#kotlin.native.concurrent.AtomicInt%24compareAndSet(kotlin.Int,%20kotlin.Int)/expected) and replaces it with [new](compare-and-set#kotlin.native.concurrent.AtomicInt%24compareAndSet(kotlin.Int,%20kotlin.Int)/new) value if values matches. ``` fun compareAndSet(expected: Int, new: Int): Boolean ``` **Platform and version requirements:** Native (1.3) #### [compareAndSwap](compare-and-swap) Compares value with [expected](compare-and-swap#kotlin.native.concurrent.AtomicInt%24compareAndSwap(kotlin.Int,%20kotlin.Int)/expected) and replaces it with [new](compare-and-swap#kotlin.native.concurrent.AtomicInt%24compareAndSwap(kotlin.Int,%20kotlin.Int)/new) value if values matches. ``` fun compareAndSwap(expected: Int, new: Int): Int ``` **Platform and version requirements:** Native (1.3) #### <decrement> Decrements value by one. ``` fun decrement() ``` **Platform and version requirements:** Native (1.3) #### <increment> Increments value by one. ``` fun increment() ``` **Platform and version requirements:** Native (1.3) #### [toString](to-string) Returns the string representation of this object. ``` fun toString(): String ``` kotlin addAndGet addAndGet ========= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicInt](index) / [addAndGet](add-and-get) **Platform and version requirements:** Native (1.3) ``` fun addAndGet(delta: Int): Int ``` Increments the value by [delta](add-and-get#kotlin.native.concurrent.AtomicInt%24addAndGet(kotlin.Int)/delta) and returns the new value. Parameters ---------- `delta` - the value to add **Return** the new value kotlin decrement decrement ========= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicInt](index) / <decrement> **Platform and version requirements:** Native (1.3) ``` fun decrement() ``` Decrements value by one. kotlin compareAndSwap compareAndSwap ============== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicInt](index) / [compareAndSwap](compare-and-swap) **Platform and version requirements:** Native (1.3) ``` fun compareAndSwap(expected: Int, new: Int): Int ``` Compares value with [expected](compare-and-swap#kotlin.native.concurrent.AtomicInt%24compareAndSwap(kotlin.Int,%20kotlin.Int)/expected) and replaces it with [new](compare-and-swap#kotlin.native.concurrent.AtomicInt%24compareAndSwap(kotlin.Int,%20kotlin.Int)/new) value if values matches. Parameters ---------- `expected` - the expected value `new` - the new value **Return** the old value kotlin increment increment ========= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicInt](index) / <increment> **Platform and version requirements:** Native (1.3) ``` fun increment() ``` Increments value by one. kotlin toString toString ======== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicInt](index) / [toString](to-string) **Platform and version requirements:** Native (1.3) ``` fun toString(): String ``` Returns the string representation of this object. **Return** the string representation kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicInt](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` AtomicInt(value_: Int) ``` Wrapper around [Int](../../kotlin/-int/index#kotlin.Int) with atomic synchronized operations. Legacy MM: Atomic values and freezing: this type is unique with regard to freezing. Namely, it provides mutating operations, while can participate in frozen subgraphs. So shared frozen objects can have mutable fields of [AtomicInt](index) type. kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicInt](index) / <value> **Platform and version requirements:** Native (1.3) ``` var value: Int ``` The value being held by this class. kotlin compareAndSet compareAndSet ============= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicNativePtr](index) / [compareAndSet](compare-and-set) **Platform and version requirements:** Native (1.3) ``` fun compareAndSet(     expected: NativePtr,     new: NativePtr ): Boolean ``` Compares value with [expected](compare-and-set#kotlin.native.concurrent.AtomicNativePtr%24compareAndSet(kotlin.native.internal.NativePtr,%20kotlin.native.internal.NativePtr)/expected) and replaces it with [new](compare-and-set#kotlin.native.concurrent.AtomicNativePtr%24compareAndSet(kotlin.native.internal.NativePtr,%20kotlin.native.internal.NativePtr)/new) value if values matches. Parameters ---------- `expected` - the expected value `new` - the new value **Return** true if successful kotlin AtomicNativePtr AtomicNativePtr =============== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicNativePtr](index) **Platform and version requirements:** Native (1.3) ``` class AtomicNativePtr ``` Wrapper around [kotlinx.cinterop.NativePtr](../../kotlinx.cinterop/-native-ptr) with atomic synchronized operations. Legacy MM: Atomic values and freezing: this type is unique with regard to freezing. Namely, it provides mutating operations, while can participate in frozen subgraphs. So shared frozen objects can have mutable fields of [AtomicNativePtr](index) type. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Wrapper around [kotlinx.cinterop.NativePtr](../../kotlinx.cinterop/-native-ptr) with atomic synchronized operations. ``` AtomicNativePtr(value_: NativePtr) ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <value> The value being held by this class. ``` var value: NativePtr ``` Functions --------- **Platform and version requirements:** Native (1.3) #### [compareAndSet](compare-and-set) Compares value with [expected](compare-and-set#kotlin.native.concurrent.AtomicNativePtr%24compareAndSet(kotlin.native.internal.NativePtr,%20kotlin.native.internal.NativePtr)/expected) and replaces it with [new](compare-and-set#kotlin.native.concurrent.AtomicNativePtr%24compareAndSet(kotlin.native.internal.NativePtr,%20kotlin.native.internal.NativePtr)/new) value if values matches. ``` fun compareAndSet(     expected: NativePtr,     new: NativePtr ): Boolean ``` **Platform and version requirements:** Native (1.3) #### [compareAndSwap](compare-and-swap) Compares value with [expected](compare-and-swap#kotlin.native.concurrent.AtomicNativePtr%24compareAndSwap(kotlin.native.internal.NativePtr,%20kotlin.native.internal.NativePtr)/expected) and replaces it with [new](compare-and-swap#kotlin.native.concurrent.AtomicNativePtr%24compareAndSwap(kotlin.native.internal.NativePtr,%20kotlin.native.internal.NativePtr)/new) value if values matches. ``` fun compareAndSwap(     expected: NativePtr,     new: NativePtr ): NativePtr ``` **Platform and version requirements:** Native (1.3) #### [toString](to-string) Returns the string representation of this object. ``` fun toString(): String ``` kotlin compareAndSwap compareAndSwap ============== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicNativePtr](index) / [compareAndSwap](compare-and-swap) **Platform and version requirements:** Native (1.3) ``` fun compareAndSwap(     expected: NativePtr,     new: NativePtr ): NativePtr ``` Compares value with [expected](compare-and-swap#kotlin.native.concurrent.AtomicNativePtr%24compareAndSwap(kotlin.native.internal.NativePtr,%20kotlin.native.internal.NativePtr)/expected) and replaces it with [new](compare-and-swap#kotlin.native.concurrent.AtomicNativePtr%24compareAndSwap(kotlin.native.internal.NativePtr,%20kotlin.native.internal.NativePtr)/new) value if values matches. Parameters ---------- `expected` - the expected value `new` - the new value **Return** the old value kotlin toString toString ======== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicNativePtr](index) / [toString](to-string) **Platform and version requirements:** Native (1.3) ``` fun toString(): String ``` Returns the string representation of this object. **Return** string representation of this object kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicNativePtr](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` AtomicNativePtr(value_: NativePtr) ``` Wrapper around [kotlinx.cinterop.NativePtr](../../kotlinx.cinterop/-native-ptr) with atomic synchronized operations. Legacy MM: Atomic values and freezing: this type is unique with regard to freezing. Namely, it provides mutating operations, while can participate in frozen subgraphs. So shared frozen objects can have mutable fields of [AtomicNativePtr](index) type.
programming_docs
kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicNativePtr](index) / <value> **Platform and version requirements:** Native (1.3) ``` var value: NativePtr ``` The value being held by this class. kotlin dispose dispose ======= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Continuation2](index) / <dispose> **Platform and version requirements:** Native (1.3) ``` fun dispose() ``` kotlin Continuation2 Continuation2 ============= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Continuation2](index) **Platform and version requirements:** Native (1.3) ``` class Continuation2<T1, T2> : (T1, T2) -> Unit ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` Continuation2(     block: (p1: T1, p2: T2) -> Unit,     invoker: CPointer<CFunction<(COpaquePointer?) -> Unit>>,     singleShot: Boolean = false) ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <dispose> ``` fun dispose() ``` **Platform and version requirements:** Native (1.3) #### <invoke> ``` operator fun invoke(p1: T1, p2: T2) ``` kotlin invoke invoke ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Continuation2](index) / <invoke> **Platform and version requirements:** Native (1.3) ``` operator fun invoke(p1: T1, p2: T2) ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Continuation2](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` Continuation2(     block: (p1: T1, p2: T2) -> Unit,     invoker: CPointer<CFunction<(COpaquePointer?) -> Unit>>,     singleShot: Boolean = false) ``` kotlin compareAndSet compareAndSet ============= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicLong](index) / [compareAndSet](compare-and-set) **Platform and version requirements:** Native (1.3) ``` fun compareAndSet(expected: Long, new: Long): Boolean ``` Compares value with [expected](compare-and-set#kotlin.native.concurrent.AtomicLong%24compareAndSet(kotlin.Long,%20kotlin.Long)/expected) and replaces it with [new](compare-and-set#kotlin.native.concurrent.AtomicLong%24compareAndSet(kotlin.Long,%20kotlin.Long)/new) value if values matches. Parameters ---------- `expected` - the expected value `new` - the new value **Return** true if successful, false if state is unchanged kotlin AtomicLong AtomicLong ========== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicLong](index) **Platform and version requirements:** Native (1.3) ``` class AtomicLong ``` Wrapper around [Long](../../kotlin/-long/index#kotlin.Long) with atomic synchronized operations. Legacy MM: Atomic values and freezing: this type is unique with regard to freezing. Namely, it provides mutating operations, while can participate in frozen subgraphs. So shared frozen objects can have mutable fields of [AtomicLong](index) type. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Wrapper around [Long](../../kotlin/-long/index#kotlin.Long) with atomic synchronized operations. ``` AtomicLong(value_: Long = 0) ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <value> The value being held by this class. ``` var value: Long ``` Functions --------- **Platform and version requirements:** Native (1.3) #### [addAndGet](add-and-get) Increments the value by [delta](add-and-get#kotlin.native.concurrent.AtomicLong%24addAndGet(kotlin.Long)/delta) and returns the new value. ``` fun addAndGet(delta: Long): Long ``` ``` fun addAndGet(delta: Int): Long ``` **Platform and version requirements:** Native (1.3) #### [compareAndSet](compare-and-set) Compares value with [expected](compare-and-set#kotlin.native.concurrent.AtomicLong%24compareAndSet(kotlin.Long,%20kotlin.Long)/expected) and replaces it with [new](compare-and-set#kotlin.native.concurrent.AtomicLong%24compareAndSet(kotlin.Long,%20kotlin.Long)/new) value if values matches. ``` fun compareAndSet(expected: Long, new: Long): Boolean ``` **Platform and version requirements:** Native (1.3) #### [compareAndSwap](compare-and-swap) Compares value with [expected](compare-and-swap#kotlin.native.concurrent.AtomicLong%24compareAndSwap(kotlin.Long,%20kotlin.Long)/expected) and replaces it with [new](compare-and-swap#kotlin.native.concurrent.AtomicLong%24compareAndSwap(kotlin.Long,%20kotlin.Long)/new) value if values matches. ``` fun compareAndSwap(expected: Long, new: Long): Long ``` **Platform and version requirements:** Native (1.3) #### <decrement> Decrements value by one. ``` fun decrement() ``` **Platform and version requirements:** Native (1.3) #### <increment> Increments value by one. ``` fun increment() ``` **Platform and version requirements:** Native (1.3) #### [toString](to-string) Returns the string representation of this object. ``` fun toString(): String ``` kotlin addAndGet addAndGet ========= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicLong](index) / [addAndGet](add-and-get) **Platform and version requirements:** Native (1.3) ``` fun addAndGet(delta: Long): Long ``` ``` fun addAndGet(delta: Int): Long ``` Increments the value by [delta](add-and-get#kotlin.native.concurrent.AtomicLong%24addAndGet(kotlin.Long)/delta) and returns the new value. Parameters ---------- `delta` - the value to add **Return** the new value kotlin decrement decrement ========= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicLong](index) / <decrement> **Platform and version requirements:** Native (1.3) ``` fun decrement() ``` Decrements value by one. kotlin compareAndSwap compareAndSwap ============== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicLong](index) / [compareAndSwap](compare-and-swap) **Platform and version requirements:** Native (1.3) ``` fun compareAndSwap(expected: Long, new: Long): Long ``` Compares value with [expected](compare-and-swap#kotlin.native.concurrent.AtomicLong%24compareAndSwap(kotlin.Long,%20kotlin.Long)/expected) and replaces it with [new](compare-and-swap#kotlin.native.concurrent.AtomicLong%24compareAndSwap(kotlin.Long,%20kotlin.Long)/new) value if values matches. Parameters ---------- `expected` - the expected value `new` - the new value **Return** the old value kotlin increment increment ========= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicLong](index) / <increment> **Platform and version requirements:** Native (1.3) ``` fun increment() ``` Increments value by one. kotlin toString toString ======== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicLong](index) / [toString](to-string) **Platform and version requirements:** Native (1.3) ``` fun toString(): String ``` Returns the string representation of this object. **Return** the string representation of this object kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicLong](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` AtomicLong(value_: Long = 0) ``` Wrapper around [Long](../../kotlin/-long/index#kotlin.Long) with atomic synchronized operations. Legacy MM: Atomic values and freezing: this type is unique with regard to freezing. Namely, it provides mutating operations, while can participate in frozen subgraphs. So shared frozen objects can have mutable fields of [AtomicLong](index) type. kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicLong](index) / <value> **Platform and version requirements:** Native (1.3) ``` var value: Long ``` The value being held by this class. kotlin FutureState FutureState =========== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FutureState](index) **Platform and version requirements:** Native (1.3) ``` enum class FutureState ``` State of the future object. Enum Values ----------- **Platform and version requirements:** Native (1.3) #### [INVALID](-i-n-v-a-l-i-d) **Platform and version requirements:** Native (1.3) #### [SCHEDULED](-s-c-h-e-d-u-l-e-d) Future is scheduled for execution. **Platform and version requirements:** Native (1.3) #### [COMPUTED](-c-o-m-p-u-t-e-d) Future result is computed. **Platform and version requirements:** Native (1.3) #### [CANCELLED](-c-a-n-c-e-l-l-e-d) Future is cancelled. **Platform and version requirements:** Native (1.3) #### [THROWN](-t-h-r-o-w-n) Computation thrown an exception. Properties ---------- **Platform and version requirements:** Native (1.3) #### <value> ``` val value: Int ``` kotlin THROWN THROWN ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FutureState](index) / [THROWN](-t-h-r-o-w-n) **Platform and version requirements:** Native (1.3) ``` THROWN ``` Computation thrown an exception. kotlin COMPUTED COMPUTED ======== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FutureState](index) / [COMPUTED](-c-o-m-p-u-t-e-d) **Platform and version requirements:** Native (1.3) ``` COMPUTED ``` Future result is computed. kotlin INVALID INVALID ======= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FutureState](index) / [INVALID](-i-n-v-a-l-i-d) **Platform and version requirements:** Native (1.3) ``` INVALID ``` kotlin SCHEDULED SCHEDULED ========= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FutureState](index) / [SCHEDULED](-s-c-h-e-d-u-l-e-d) **Platform and version requirements:** Native (1.3) ``` SCHEDULED ``` Future is scheduled for execution. kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FutureState](index) / <value> **Platform and version requirements:** Native (1.3) ``` val value: Int ``` kotlin CANCELLED CANCELLED ========= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FutureState](index) / [CANCELLED](-c-a-n-c-e-l-l-e-d) **Platform and version requirements:** Native (1.3) ``` CANCELLED ``` Future is cancelled. kotlin Future Future ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Future](index) **Platform and version requirements:** Native (1.3) ``` class Future<T> ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <id> ``` val id: Int ``` **Platform and version requirements:** Native (1.3) #### <result> The result of the future computation. Blocks execution until the future is ready. Second attempt to get will result in an error. ``` val result: T ``` **Platform and version requirements:** Native (1.3) #### <state> A [FutureState](../-future-state/index) of this future ``` val state: FutureState ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <consume> Blocks execution until the future is ready. ``` fun <R> consume(code: (T) -> R): R ``` **Platform and version requirements:** Native (1.3) #### [toString](to-string) Returns a string representation of the object. ``` fun toString(): String ``` kotlin id id == [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Future](index) / <id> **Platform and version requirements:** Native (1.3) ``` val id: Int ``` kotlin toString toString ======== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Future](index) / [toString](to-string) **Platform and version requirements:** Native (1.3) ``` fun toString(): String ``` Returns a string representation of the object. kotlin result result ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Future](index) / <result> **Platform and version requirements:** Native (1.3) ``` val result: T ``` The result of the future computation. Blocks execution until the future is ready. Second attempt to get will result in an error. kotlin state state ===== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Future](index) / <state> **Platform and version requirements:** Native (1.3) ``` val state: FutureState ``` A [FutureState](../-future-state/index) of this future kotlin consume consume ======= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Future](index) / <consume> **Platform and version requirements:** Native (1.3) ``` inline fun <R> consume(code: (T) -> R): R ``` Blocks execution until the future is ready. Exceptions ---------- `IllegalStateException` - if future is in [FutureState.INVALID](../-future-state/-i-n-v-a-l-i-d), [FutureState.CANCELLED](../-future-state/-c-a-n-c-e-l-l-e-d) or [FutureState.THROWN](../-future-state/-t-h-r-o-w-n) state **Return** the execution result of [code](consume#kotlin.native.concurrent.Future%24consume(kotlin.Function1((kotlin.native.concurrent.Future.T,%20kotlin.native.concurrent.Future.consume.R)))/code) consumed future's computaiton kotlin SharedImmutable SharedImmutable =============== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [SharedImmutable](index) **Platform and version requirements:** Native (1.3) ``` @Target([AnnotationTarget.PROPERTY]) annotation class SharedImmutable ``` ##### For Common Note: this annotation has effect only in Kotlin/Native with legacy memory manager. Marks a top level property with a backing field as immutable. It is possible to share the value of such property between multiple threads, but it becomes deeply frozen, so no changes can be made to its state or the state of objects it refers to. The annotation has effect only in Kotlin/Native platform. PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES. Since 1.7.20 usage of this annotation is deprecated. See https://kotlinlang.org/docs/native-migration-guide.html for details. ##### For Native Note: this annotation has effect only in Kotlin/Native with legacy memory manager. Marks a top level property with a backing field as immutable. It is possible to share the value of such property between multiple threads, but it becomes deeply frozen, so no changes can be made to its state or the state of objects it refers to. PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES. Since 1.7.20 usage of this annotation is deprecated. See https://kotlinlang.org/docs/native-migration-guide.html for details. Constructors ------------ **Platform and version requirements:** Native (1.0) #### [<init>](-init-) Note: this annotation has effect only in Kotlin/Native with legacy memory manager. ``` <init>() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [SharedImmutable](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` <init>() ``` ##### For Common Note: this annotation has effect only in Kotlin/Native with legacy memory manager. Marks a top level property with a backing field as immutable. It is possible to share the value of such property between multiple threads, but it becomes deeply frozen, so no changes can be made to its state or the state of objects it refers to. The annotation has effect only in Kotlin/Native platform. PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES. Since 1.7.20 usage of this annotation is deprecated. See https://kotlinlang.org/docs/native-migration-guide.html for details. ##### For Native Note: this annotation has effect only in Kotlin/Native with legacy memory manager. Marks a top level property with a backing field as immutable. It is possible to share the value of such property between multiple threads, but it becomes deeply frozen, so no changes can be made to its state or the state of objects it refers to. PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES. Since 1.7.20 usage of this annotation is deprecated. See https://kotlinlang.org/docs/native-migration-guide.html for details. kotlin compareAndSet compareAndSet ============= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicReference](index) / [compareAndSet](compare-and-set) **Platform and version requirements:** Native (1.3) ``` fun compareAndSet(expected: T, new: T): Boolean ``` Compares value with [expected](compare-and-set#kotlin.native.concurrent.AtomicReference%24compareAndSet(kotlin.native.concurrent.AtomicReference.T,%20kotlin.native.concurrent.AtomicReference.T)/expected) and replaces it with [new](compare-and-set#kotlin.native.concurrent.AtomicReference%24compareAndSet(kotlin.native.concurrent.AtomicReference.T,%20kotlin.native.concurrent.AtomicReference.T)/new) value if values matches. Note that comparison is identity-based, not value-based. Parameters ---------- `expected` - the expected value `new` - the new value **Return** true if successful kotlin AtomicReference AtomicReference =============== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicReference](index) **Platform and version requirements:** Native (1.3) ``` class AtomicReference<T> ``` Wrapper around Kotlin object with atomic operations. Legacy MM: An atomic reference to a frozen Kotlin object. Can be used in concurrent scenarious but frequently shall be of nullable type and be zeroed out once no longer needed. Otherwise memory leak could happen. To detect such leaks kotlin.native.internal.GC.detectCycles in debug mode could be helpful. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Creates a new atomic reference pointing to given ref. ``` AtomicReference(value: T) ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <value> The referenced value. Gets the value or sets the new value. Legacy MM: if new value is not null, it must be frozen or permanent object. ``` var value: T ``` Functions --------- **Platform and version requirements:** Native (1.3) #### [compareAndSet](compare-and-set) Compares value with [expected](compare-and-set#kotlin.native.concurrent.AtomicReference%24compareAndSet(kotlin.native.concurrent.AtomicReference.T,%20kotlin.native.concurrent.AtomicReference.T)/expected) and replaces it with [new](compare-and-set#kotlin.native.concurrent.AtomicReference%24compareAndSet(kotlin.native.concurrent.AtomicReference.T,%20kotlin.native.concurrent.AtomicReference.T)/new) value if values matches. Note that comparison is identity-based, not value-based. ``` fun compareAndSet(expected: T, new: T): Boolean ``` **Platform and version requirements:** Native (1.3) #### [compareAndSwap](compare-and-swap) Compares value with [expected](compare-and-swap#kotlin.native.concurrent.AtomicReference%24compareAndSwap(kotlin.native.concurrent.AtomicReference.T,%20kotlin.native.concurrent.AtomicReference.T)/expected) and replaces it with [new](compare-and-swap#kotlin.native.concurrent.AtomicReference%24compareAndSwap(kotlin.native.concurrent.AtomicReference.T,%20kotlin.native.concurrent.AtomicReference.T)/new) value if values matches. Note that comparison is identity-based, not value-based. ``` fun compareAndSwap(expected: T, new: T): T ``` **Platform and version requirements:** Native (1.3) #### [toString](to-string) Returns the string representation of this object. ``` fun toString(): String ```
programming_docs
kotlin compareAndSwap compareAndSwap ============== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicReference](index) / [compareAndSwap](compare-and-swap) **Platform and version requirements:** Native (1.3) ``` fun compareAndSwap(expected: T, new: T): T ``` Compares value with [expected](compare-and-swap#kotlin.native.concurrent.AtomicReference%24compareAndSwap(kotlin.native.concurrent.AtomicReference.T,%20kotlin.native.concurrent.AtomicReference.T)/expected) and replaces it with [new](compare-and-swap#kotlin.native.concurrent.AtomicReference%24compareAndSwap(kotlin.native.concurrent.AtomicReference.T,%20kotlin.native.concurrent.AtomicReference.T)/new) value if values matches. Note that comparison is identity-based, not value-based. Legacy MM: if [new](compare-and-swap#kotlin.native.concurrent.AtomicReference%24compareAndSwap(kotlin.native.concurrent.AtomicReference.T,%20kotlin.native.concurrent.AtomicReference.T)/new) value is not null, it must be frozen or permanent object. Parameters ---------- `expected` - the expected value `new` - the new value Exceptions ---------- `InvalidMutabilityException` - with legacy MM if the value is not frozen or a permanent object **Return** the old value kotlin toString toString ======== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicReference](index) / [toString](to-string) **Platform and version requirements:** Native (1.3) ``` fun toString(): String ``` Returns the string representation of this object. **Return** string representation of this object kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicReference](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` AtomicReference(value: T) ``` Creates a new atomic reference pointing to given ref. Exceptions ---------- `InvalidMutabilityException` - with legacy MM if reference is not frozen. kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [AtomicReference](index) / <value> **Platform and version requirements:** Native (1.3) ``` var value: T ``` The referenced value. Gets the value or sets the new value. Legacy MM: if new value is not null, it must be frozen or permanent object. Exceptions ---------- `InvalidMutabilityException` - with legacy MM if the value is not frozen or a permanent object kotlin TransferMode TransferMode ============ [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [TransferMode](index) **Platform and version requirements:** Native (1.3) ``` enum class TransferMode ``` Note: modern Kotlin/Native memory manager allows to share objects between threads without additional ceremonies, so TransferMode has effect only in legacy memory manager. Object Transfer Basics. ----------------------- Objects can be passed between threads in one of two possible modes. * [SAFE](-s-a-f-e) - object subgraph is checked to be not reachable by other globals or locals, and passed if so, otherwise an exception is thrown * [UNSAFE](-u-n-s-a-f-e) - object is blindly passed to another worker, if there are references left in the passing worker - it may lead to crash or program malfunction Safe mode checks if object is no longer used in passing worker, using memory-management specific algorithm (ARC implementation relies on trial deletion on object graph rooted in passed object), and throws an [IllegalStateException](../../kotlin/-illegal-state-exception/index#kotlin.IllegalStateException) if object graph rooted in transferred object is reachable by some other means, Unsafe mode is intended for most performance critical operations, where object graph ownership is expected to be correct (such as application debugged earlier in [SAFE](-s-a-f-e) mode), just transfers ownership without further checks. Note, that for some cases cycle collection need to be done to ensure that dead cycles do not affect reachability of passed object graph. **See Also** kotlin.native.internal.GC.collect ### Enum Values **Platform and version requirements:** Native (1.3) #### [SAFE](-s-a-f-e) Reachibility check is performed. **Platform and version requirements:** Native (1.3) #### [UNSAFE](-u-n-s-a-f-e) Skip reachibility check, can lead to mysterious crashes in an application. USE UNSAFE MODE ONLY IF ABSOLUTELY SURE WHAT YOU'RE DOING!!! ### Properties **Platform and version requirements:** Native (1.3) #### <value> ``` val value: Int ``` kotlin SAFE SAFE ==== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [TransferMode](index) / [SAFE](-s-a-f-e) **Platform and version requirements:** Native (1.3) ``` SAFE ``` Reachibility check is performed. kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [TransferMode](index) / <value> **Platform and version requirements:** Native (1.3) ``` val value: Int ``` kotlin UNSAFE UNSAFE ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [TransferMode](index) / [UNSAFE](-u-n-s-a-f-e) **Platform and version requirements:** Native (1.3) ``` UNSAFE ``` Skip reachibility check, can lead to mysterious crashes in an application. USE UNSAFE MODE ONLY IF ABSOLUTELY SURE WHAT YOU'RE DOING!!! kotlin Worker Worker ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) **Platform and version requirements:** Native (1.3) ``` class Worker ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <id> ``` val id: Int ``` **Platform and version requirements:** Native (1.3) #### <name> Name of the worker, as specified in [Worker.start](start) or "worker $id" by default, ``` val name: String ``` **Platform and version requirements:** Native (1.3) #### [platformThreadId](platform-thread-id) Get platform thread id of the worker thread. ``` val platformThreadId: ULong ``` Functions --------- **Platform and version requirements:** Native (1.3) #### [asCPointer](as-c-pointer) Convert worker to a COpaquePointer value that could be passed via native void\* pointer. Can be used as an argument of [Worker.fromCPointer](from-c-pointer). ``` fun asCPointer(): COpaquePointer? ``` **Platform and version requirements:** Native (1.3) #### <execute> Plan job for further execution in the worker. Execute is a two-phase operation: ``` fun <T1, T2> execute(     mode: TransferMode,     producer: () -> T1,     job: (T1) -> T2 ): Future<T2> ``` **Platform and version requirements:** Native (1.3) #### [executeAfter](execute-after) Plan job for further execution in the worker. ``` fun executeAfter(     afterMicroseconds: Long = 0,     operation: () -> Unit) ``` **Platform and version requirements:** Native (1.3) #### <park> Park execution of the current worker until a new request arrives or timeout specified in [timeoutMicroseconds](park#kotlin.native.concurrent.Worker%24park(kotlin.Long,%20kotlin.Boolean)/timeoutMicroseconds) elapsed. If [process](park#kotlin.native.concurrent.Worker%24park(kotlin.Long,%20kotlin.Boolean)/process) is true, pending queue elements are processed, including delayed requests. Note that multiple requests could be processed this way. ``` fun park(     timeoutMicroseconds: Long,     process: Boolean = false ): Boolean ``` **Platform and version requirements:** Native (1.3) #### [processQueue](process-queue) Process pending job(s) on the queue of this worker. Note that jobs scheduled with [executeAfter](execute-after) using non-zero timeout are not processed this way. If termination request arrives while processing the queue via this API, worker is marked as terminated and will exit once the current request is done with. ``` fun processQueue(): Boolean ``` **Platform and version requirements:** Native (1.3) #### [requestTermination](request-termination) Requests termination of the worker. ``` fun requestTermination(     processScheduledJobs: Boolean = true ): Future<Unit> ``` **Platform and version requirements:** Native (1.3) #### [toString](to-string) String representation of the worker. ``` fun toString(): String ``` Companion Object Properties --------------------------- **Platform and version requirements:** Native (1.3) #### [activeWorkers](active-workers) Get a list of all unterminated workers. ``` val activeWorkers: List<Worker> ``` **Platform and version requirements:** Native (1.3) #### <current> Return the current worker. Worker context is accessible to any valid Kotlin context, but only actual active worker produced with [Worker.start](start) automatically processes execution requests. For other situations [processQueue](process-queue) must be called explicitly to process request queue. ``` val current: Worker ``` Companion Object Functions -------------------------- **Platform and version requirements:** Native (1.3) #### [fromCPointer](from-c-pointer) Create worker object from a C pointer. ``` fun fromCPointer(pointer: COpaquePointer?): Worker ``` **Platform and version requirements:** Native (1.3) #### <start> Start new scheduling primitive, such as thread, to accept new tasks via `execute` interface. Typically new worker may be needed for computations offload to another core, for IO it may be better to use non-blocking IO combined with more lightweight coroutines. ``` fun start(     errorReporting: Boolean = true,     name: String? = null ): Worker ``` kotlin park park ==== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / <park> **Platform and version requirements:** Native (1.3) ``` fun park(     timeoutMicroseconds: Long,     process: Boolean = false ): Boolean ``` Park execution of the current worker until a new request arrives or timeout specified in [timeoutMicroseconds](park#kotlin.native.concurrent.Worker%24park(kotlin.Long,%20kotlin.Boolean)/timeoutMicroseconds) elapsed. If [process](park#kotlin.native.concurrent.Worker%24park(kotlin.Long,%20kotlin.Boolean)/process) is true, pending queue elements are processed, including delayed requests. Note that multiple requests could be processed this way. Parameters ---------- `timeoutMicroseconds` - defines how long to park worker if no requests arrive, waits forever if -1. `process` - defines if arrived request(s) shall be processed. Exceptions ---------- `IllegalStateException` - if this request is executed on non-current [Worker](index). `IllegalArgumentException` - if timeout value is incorrect. **Return** if [process](park#kotlin.native.concurrent.Worker%24park(kotlin.Long,%20kotlin.Boolean)/process) is `true`: if request(s) was processed `true` and `false` otherwise. if [process](park#kotlin.native.concurrent.Worker%24park(kotlin.Long,%20kotlin.Boolean)/process) is `false`: `true` if request(s) has arrived and `false` if timeout happens. kotlin id id == [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / <id> **Platform and version requirements:** Native (1.3) ``` val id: Int ``` kotlin processQueue processQueue ============ [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / [processQueue](process-queue) **Platform and version requirements:** Native (1.3) ``` fun processQueue(): Boolean ``` Process pending job(s) on the queue of this worker. Note that jobs scheduled with [executeAfter](execute-after) using non-zero timeout are not processed this way. If termination request arrives while processing the queue via this API, worker is marked as terminated and will exit once the current request is done with. Exceptions ---------- `IllegalStateException` - if this request is executed on non-current [Worker](index). **Return** `true` if request(s) was processed and `false` otherwise. kotlin current current ======= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / <current> **Platform and version requirements:** Native (1.3) ``` val current: Worker ``` Return the current worker. Worker context is accessible to any valid Kotlin context, but only actual active worker produced with [Worker.start](start) automatically processes execution requests. For other situations [processQueue](process-queue) must be called explicitly to process request queue. **Return** current worker object, usable across multiple concurrent contexts. kotlin platformThreadId platformThreadId ================ [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / [platformThreadId](platform-thread-id) **Platform and version requirements:** Native (1.3) ``` @ExperimentalStdlibApi val platformThreadId: ULong ``` Get platform thread id of the worker thread. Usually returns `pthread_t` casted to ULong. kotlin executeAfter executeAfter ============ [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / [executeAfter](execute-after) **Platform and version requirements:** Native (1.3) ``` fun executeAfter(     afterMicroseconds: Long = 0,     operation: () -> Unit) ``` Plan job for further execution in the worker. With -Xworker-exception-handling=use-hook, if the worker was created with `errorReporting` set to true, any exception escaping from [operation](execute-after#kotlin.native.concurrent.Worker%24executeAfter(kotlin.Long,%20kotlin.Function0((kotlin.Unit)))/operation) will be handled by [processUnhandledException](../../kotlin.native/process-unhandled-exception). Legacy MM: [operation](execute-after#kotlin.native.concurrent.Worker%24executeAfter(kotlin.Long,%20kotlin.Function0((kotlin.Unit)))/operation) parameter must be either frozen, or execution to be planned on the current worker. Otherwise [IllegalStateException](../../kotlin/-illegal-state-exception/index#kotlin.IllegalStateException) will be thrown. Parameters ---------- `afterMicroseconds` - defines after how many microseconds delay execution shall happen, 0 means immediately, Exceptions ---------- `IllegalArgumentException` - on negative values of [afterMicroseconds](execute-after#kotlin.native.concurrent.Worker%24executeAfter(kotlin.Long,%20kotlin.Function0((kotlin.Unit)))/afterMicroseconds). `IllegalStateException` - if [operation](execute-after#kotlin.native.concurrent.Worker%24executeAfter(kotlin.Long,%20kotlin.Function0((kotlin.Unit)))/operation) parameter is not frozen and worker is not current. kotlin requestTermination requestTermination ================== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / [requestTermination](request-termination) **Platform and version requirements:** Native (1.3) ``` fun requestTermination(     processScheduledJobs: Boolean = true ): Future<Unit> ``` Requests termination of the worker. Parameters ---------- `processScheduledJobs` - controls is we shall wait until all scheduled jobs processed, or terminate immediately. If there are jobs to be execucted with [executeAfter](execute-after) their execution is awaited for. kotlin start start ===== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / <start> **Platform and version requirements:** Native (1.3) ``` fun start(     errorReporting: Boolean = true,     name: String? = null ): Worker ``` Start new scheduling primitive, such as thread, to accept new tasks via `execute` interface. Typically new worker may be needed for computations offload to another core, for IO it may be better to use non-blocking IO combined with more lightweight coroutines. Parameters ---------- `errorReporting` - controls if an uncaught exceptions in the worker will be reported. `name` - defines the optional name of this worker, if none - default naming is used. **Return** worker object, usable across multiple concurrent contexts. kotlin execute execute ======= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / <execute> **Platform and version requirements:** Native (1.3) ``` fun <T1, T2> execute(     mode: TransferMode,     producer: () -> T1,     job: (T1) -> T2 ): Future<T2> ``` Plan job for further execution in the worker. Execute is a two-phase operation: 1. [producer](execute#kotlin.native.concurrent.Worker%24execute(kotlin.native.concurrent.TransferMode,%20kotlin.Function0((kotlin.native.concurrent.Worker.execute.T1)),%20kotlin.Function1((kotlin.native.concurrent.Worker.execute.T1,%20kotlin.native.concurrent.Worker.execute.T2)))/producer) function is executed on the caller's thread. 2. the result of [producer](execute#kotlin.native.concurrent.Worker%24execute(kotlin.native.concurrent.TransferMode,%20kotlin.Function0((kotlin.native.concurrent.Worker.execute.T1)),%20kotlin.Function1((kotlin.native.concurrent.Worker.execute.T1,%20kotlin.native.concurrent.Worker.execute.T2)))/producer) and [job](execute#kotlin.native.concurrent.Worker%24execute(kotlin.native.concurrent.TransferMode,%20kotlin.Function0((kotlin.native.concurrent.Worker.execute.T1)),%20kotlin.Function1((kotlin.native.concurrent.Worker.execute.T1,%20kotlin.native.concurrent.Worker.execute.T2)))/job) function pointer is being added to jobs queue of the selected worker. Note that [job](execute#kotlin.native.concurrent.Worker%24execute(kotlin.native.concurrent.TransferMode,%20kotlin.Function0((kotlin.native.concurrent.Worker.execute.T1)),%20kotlin.Function1((kotlin.native.concurrent.Worker.execute.T1,%20kotlin.native.concurrent.Worker.execute.T2)))/job) must not capture any state itself. Parameter [mode](execute#kotlin.native.concurrent.Worker%24execute(kotlin.native.concurrent.TransferMode,%20kotlin.Function0((kotlin.native.concurrent.Worker.execute.T1)),%20kotlin.Function1((kotlin.native.concurrent.Worker.execute.T1,%20kotlin.native.concurrent.Worker.execute.T2)))/mode) has no effect. Behavior is more complex in case of legacy memory manager: * first [producer](execute#kotlin.native.concurrent.Worker%24execute(kotlin.native.concurrent.TransferMode,%20kotlin.Function0((kotlin.native.concurrent.Worker.execute.T1)),%20kotlin.Function1((kotlin.native.concurrent.Worker.execute.T1,%20kotlin.native.concurrent.Worker.execute.T2)))/producer) function is executed, and resulting object and whatever it refers to is analyzed for being an isolated object subgraph, if in checked mode. * Afterwards, this disconnected object graph and [job](execute#kotlin.native.concurrent.Worker%24execute(kotlin.native.concurrent.TransferMode,%20kotlin.Function0((kotlin.native.concurrent.Worker.execute.T1)),%20kotlin.Function1((kotlin.native.concurrent.Worker.execute.T1,%20kotlin.native.concurrent.Worker.execute.T2)))/job) function pointer is being added to jobs queue of the selected worker. Note that [job](execute#kotlin.native.concurrent.Worker%24execute(kotlin.native.concurrent.TransferMode,%20kotlin.Function0((kotlin.native.concurrent.Worker.execute.T1)),%20kotlin.Function1((kotlin.native.concurrent.Worker.execute.T1,%20kotlin.native.concurrent.Worker.execute.T2)))/job) must not capture any state itself, so that whole state is explicitly stored in object produced by [producer](execute#kotlin.native.concurrent.Worker%24execute(kotlin.native.concurrent.TransferMode,%20kotlin.Function0((kotlin.native.concurrent.Worker.execute.T1)),%20kotlin.Function1((kotlin.native.concurrent.Worker.execute.T1,%20kotlin.native.concurrent.Worker.execute.T2)))/producer). Scheduled job is being executed by the worker, and result of such a execution is being disconnected from worker's object graph. Whoever will consume the future, can use result of worker's computations. Note, that some technically disjoint subgraphs may lead to `kotlin.IllegalStateException` so `kotlin.native.internal.GC.collect()` could be called in the end of `producer` and `job` if garbage cyclic structures or other uncollected objects refer to the value being transferred. **Return** the future with the computation result of [job](execute#kotlin.native.concurrent.Worker%24execute(kotlin.native.concurrent.TransferMode,%20kotlin.Function0((kotlin.native.concurrent.Worker.execute.T1)),%20kotlin.Function1((kotlin.native.concurrent.Worker.execute.T1,%20kotlin.native.concurrent.Worker.execute.T2)))/job).
programming_docs
kotlin toString toString ======== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / [toString](to-string) **Platform and version requirements:** Native (1.3) ``` fun toString(): String ``` String representation of the worker. kotlin fromCPointer fromCPointer ============ [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / [fromCPointer](from-c-pointer) **Platform and version requirements:** Native (1.3) ``` fun fromCPointer(pointer: COpaquePointer?): Worker ``` **Deprecated:** Use kotlinx.cinterop.StableRef instead Create worker object from a C pointer. This function is deprecated. See [Worker.asCPointer](as-c-pointer) for more details. Parameters ---------- `pointer` - value returned earlier by [Worker.asCPointer](as-c-pointer) kotlin asCPointer asCPointer ========== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / [asCPointer](as-c-pointer) **Platform and version requirements:** Native (1.3) ``` fun asCPointer(): COpaquePointer? ``` **Deprecated:** Use kotlinx.cinterop.StableRef instead Convert worker to a COpaquePointer value that could be passed via native void\* pointer. Can be used as an argument of [Worker.fromCPointer](from-c-pointer). This function is deprecated. Use `kotlinx.cinterop.StableRef.create(worker).asCPointer()` instead. The result can be unwrapped with `pointer.asStableRef<Worker>().get()`. [StableRef](../../kotlinx.cinterop/-stable-ref/index) should be eventually disposed manually with [StableRef.dispose](../../kotlinx.cinterop/-stable-ref/dispose). **Return** worker identifier as C pointer. kotlin name name ==== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / <name> **Platform and version requirements:** Native (1.3) ``` val name: String ``` Name of the worker, as specified in [Worker.start](start) or "worker $id" by default, Exceptions ---------- `IllegalStateException` - if this request is executed on an invalid worker. kotlin activeWorkers activeWorkers ============= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Worker](index) / [activeWorkers](active-workers) **Platform and version requirements:** Native (1.3) ``` @ExperimentalStdlibApi val activeWorkers: List<Worker> ``` Get a list of all unterminated workers. Thread safety: If some other thread calls [Worker.requestTermination](request-termination) at the same time then this may return a [Worker](index) that's already terminated. kotlin InvalidMutabilityException InvalidMutabilityException ========================== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [InvalidMutabilityException](index) **Platform and version requirements:** Native (1.3) ``` class InvalidMutabilityException : RuntimeException ``` Exception thrown whenever we attempt to mutate frozen objects. Parameters ---------- `where` - a frozen object that was attempted to mutate Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Exception thrown whenever we attempt to mutate frozen objects. ``` InvalidMutabilityException(message: String) ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [getStackTraceAddresses](../../kotlin.native/get-stack-trace-addresses) Returns a list of stack trace addresses representing the stack trace pertaining to this throwable. ``` fun Throwable.getStackTraceAddresses(): List<Long> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [InvalidMutabilityException](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` InvalidMutabilityException(message: String) ``` Exception thrown whenever we attempt to mutate frozen objects. Parameters ---------- `where` - a frozen object that was attempted to mutate kotlin dispose dispose ======= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Continuation1](index) / <dispose> **Platform and version requirements:** Native (1.3) ``` fun dispose() ``` kotlin Continuation1 Continuation1 ============= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Continuation1](index) **Platform and version requirements:** Native (1.3) ``` class Continuation1<T1> : (T1) -> Unit ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` Continuation1(     block: (p1: T1) -> Unit,     invoker: CPointer<CFunction<(COpaquePointer?) -> Unit>>,     singleShot: Boolean = false) ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <dispose> ``` fun dispose() ``` **Platform and version requirements:** Native (1.3) #### <invoke> ``` operator fun invoke(p1: T1) ``` kotlin invoke invoke ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Continuation1](index) / <invoke> **Platform and version requirements:** Native (1.3) ``` operator fun invoke(p1: T1) ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Continuation1](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` Continuation1(     block: (p1: T1) -> Unit,     invoker: CPointer<CFunction<(COpaquePointer?) -> Unit>>,     singleShot: Boolean = false) ``` kotlin compareAndSet compareAndSet ============= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FreezableAtomicReference](index) / [compareAndSet](compare-and-set) **Platform and version requirements:** Native (1.3) ``` fun compareAndSet(expected: T, new: T): Boolean ``` Compares value with [expected](compare-and-set#kotlin.native.concurrent.FreezableAtomicReference%24compareAndSet(kotlin.native.concurrent.FreezableAtomicReference.T,%20kotlin.native.concurrent.FreezableAtomicReference.T)/expected) and replaces it with [new](compare-and-set#kotlin.native.concurrent.FreezableAtomicReference%24compareAndSet(kotlin.native.concurrent.FreezableAtomicReference.T,%20kotlin.native.concurrent.FreezableAtomicReference.T)/new) value if values matches. Note that comparison is identity-based, not value-based. Parameters ---------- `expected` - the expected value `new` - the new value **Return** true if successful kotlin FreezableAtomicReference FreezableAtomicReference ======================== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FreezableAtomicReference](index) **Platform and version requirements:** Native (1.3) ``` class FreezableAtomicReference<T> ``` Note: this class is useful only with legacy memory manager. Please use [AtomicReference](../-atomic-reference/index) instead. An atomic reference to a Kotlin object. Can be used in concurrent scenarious, but must be frozen first, otherwise behaves as regular box for the value. If frozen, shall be zeroed out once no longer needed. Otherwise memory leak could happen. To detect such leaks kotlin.native.internal.GC.detectCycles in debug mode could be helpful. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Note: this class is useful only with legacy memory manager. Please use [AtomicReference](../-atomic-reference/index) instead. ``` FreezableAtomicReference(value_: T) ``` Properties ---------- **Platform and version requirements:** Native (1.3) #### <value> The referenced value. Gets the value or sets the new value. If new value is not null, and `this` is frozen - it must be frozen or permanent object. ``` var value: T ``` Functions --------- **Platform and version requirements:** Native (1.3) #### [compareAndSet](compare-and-set) Compares value with [expected](compare-and-set#kotlin.native.concurrent.FreezableAtomicReference%24compareAndSet(kotlin.native.concurrent.FreezableAtomicReference.T,%20kotlin.native.concurrent.FreezableAtomicReference.T)/expected) and replaces it with [new](compare-and-set#kotlin.native.concurrent.FreezableAtomicReference%24compareAndSet(kotlin.native.concurrent.FreezableAtomicReference.T,%20kotlin.native.concurrent.FreezableAtomicReference.T)/new) value if values matches. Note that comparison is identity-based, not value-based. ``` fun compareAndSet(expected: T, new: T): Boolean ``` **Platform and version requirements:** Native (1.3) #### [compareAndSwap](compare-and-swap) Compares value with [expected](compare-and-swap#kotlin.native.concurrent.FreezableAtomicReference%24compareAndSwap(kotlin.native.concurrent.FreezableAtomicReference.T,%20kotlin.native.concurrent.FreezableAtomicReference.T)/expected) and replaces it with [new](compare-and-swap#kotlin.native.concurrent.FreezableAtomicReference%24compareAndSwap(kotlin.native.concurrent.FreezableAtomicReference.T,%20kotlin.native.concurrent.FreezableAtomicReference.T)/new) value if values matches. Legacy MM: If [new](compare-and-swap#kotlin.native.concurrent.FreezableAtomicReference%24compareAndSwap(kotlin.native.concurrent.FreezableAtomicReference.T,%20kotlin.native.concurrent.FreezableAtomicReference.T)/new) value is not null and object is frozen, it must be frozen or permanent object. ``` fun compareAndSwap(expected: T, new: T): T ``` **Platform and version requirements:** Native (1.3) #### [toString](to-string) Returns the string representation of this object. ``` fun toString(): String ``` kotlin compareAndSwap compareAndSwap ============== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FreezableAtomicReference](index) / [compareAndSwap](compare-and-swap) **Platform and version requirements:** Native (1.3) ``` fun compareAndSwap(expected: T, new: T): T ``` Compares value with [expected](compare-and-swap#kotlin.native.concurrent.FreezableAtomicReference%24compareAndSwap(kotlin.native.concurrent.FreezableAtomicReference.T,%20kotlin.native.concurrent.FreezableAtomicReference.T)/expected) and replaces it with [new](compare-and-swap#kotlin.native.concurrent.FreezableAtomicReference%24compareAndSwap(kotlin.native.concurrent.FreezableAtomicReference.T,%20kotlin.native.concurrent.FreezableAtomicReference.T)/new) value if values matches. Legacy MM: If [new](compare-and-swap#kotlin.native.concurrent.FreezableAtomicReference%24compareAndSwap(kotlin.native.concurrent.FreezableAtomicReference.T,%20kotlin.native.concurrent.FreezableAtomicReference.T)/new) value is not null and object is frozen, it must be frozen or permanent object. Parameters ---------- `expected` - the expected value `new` - the new value Exceptions ---------- `InvalidMutabilityException` - with legacy MM if the value is not frozen or a permanent object **Return** the old value kotlin toString toString ======== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FreezableAtomicReference](index) / [toString](to-string) **Platform and version requirements:** Native (1.3) ``` fun toString(): String ``` Returns the string representation of this object. **Return** string representation of this object kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FreezableAtomicReference](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` FreezableAtomicReference(value_: T) ``` Note: this class is useful only with legacy memory manager. Please use [AtomicReference](../-atomic-reference/index) instead. An atomic reference to a Kotlin object. Can be used in concurrent scenarious, but must be frozen first, otherwise behaves as regular box for the value. If frozen, shall be zeroed out once no longer needed. Otherwise memory leak could happen. To detect such leaks kotlin.native.internal.GC.detectCycles in debug mode could be helpful. kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [FreezableAtomicReference](index) / <value> **Platform and version requirements:** Native (1.3) ``` var value: T ``` The referenced value. Gets the value or sets the new value. If new value is not null, and `this` is frozen - it must be frozen or permanent object. Exceptions ---------- `InvalidMutabilityException` - if the value is not frozen or a permanent object kotlin DetachedObjectGraph DetachedObjectGraph =================== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [DetachedObjectGraph](index) **Platform and version requirements:** Native (1.3) ``` class DetachedObjectGraph<T> ``` Detached object graph encapsulates transferrable detached subgraph which cannot be accessed externally, until it is attached with the [attach](../attach) extension function. Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) Creates stable pointer to object, ensuring associated object subgraph is disjoint in specified mode ([TransferMode.SAFE](../-transfer-mode/-s-a-f-e) by default). Raw value returned by [asCPointer](as-c-pointer) could be stored to a C variable or passed to another Kotlin machine. ``` DetachedObjectGraph(     mode: TransferMode = TransferMode.SAFE,     producer: () -> T) ``` Restores detached object graph from the value stored earlier in a C raw pointer. ``` DetachedObjectGraph(pointer: COpaquePointer?) ``` Functions --------- **Platform and version requirements:** Native (1.3) #### [asCPointer](as-c-pointer) Returns raw C pointer value, usable for interoperability with C scenarious. ``` fun asCPointer(): COpaquePointer? ``` Extension Functions ------------------- **Platform and version requirements:** Native (1.3) #### [attach](../attach) Attaches previously detached object subgraph created by [DetachedObjectGraph](index). Please note, that once object graph is attached, the DetachedObjectGraph.stable pointer does not make sense anymore, and shall be discarded, so attach of one DetachedObjectGraph object can only happen once. ``` fun <T> DetachedObjectGraph<T>.attach(): T ``` kotlin asCPointer asCPointer ========== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [DetachedObjectGraph](index) / [asCPointer](as-c-pointer) **Platform and version requirements:** Native (1.3) ``` fun asCPointer(): COpaquePointer? ``` Returns raw C pointer value, usable for interoperability with C scenarious. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [DetachedObjectGraph](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` DetachedObjectGraph(     mode: TransferMode = TransferMode.SAFE,     producer: () -> T) ``` Creates stable pointer to object, ensuring associated object subgraph is disjoint in specified mode ([TransferMode.SAFE](../-transfer-mode/-s-a-f-e) by default). Raw value returned by [asCPointer](as-c-pointer) could be stored to a C variable or passed to another Kotlin machine. **Platform and version requirements:** Native (1.3) ``` DetachedObjectGraph(pointer: COpaquePointer?) ``` Restores detached object graph from the value stored earlier in a C raw pointer. kotlin dispose dispose ======= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Continuation0](index) / <dispose> **Platform and version requirements:** Native (1.3) ``` fun dispose() ``` kotlin Continuation0 Continuation0 ============= [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Continuation0](index) **Platform and version requirements:** Native (1.3) ``` class Continuation0 : () -> Unit ``` Constructors ------------ **Platform and version requirements:** Native (1.3) #### [<init>](-init-) ``` Continuation0(     block: () -> Unit,     invoker: CPointer<CFunction<(COpaquePointer?) -> Unit>>,     singleShot: Boolean = false) ``` Functions --------- **Platform and version requirements:** Native (1.3) #### <dispose> ``` fun dispose() ``` **Platform and version requirements:** Native (1.3) #### <invoke> ``` operator fun invoke() ``` kotlin invoke invoke ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Continuation0](index) / <invoke> **Platform and version requirements:** Native (1.3) ``` operator fun invoke() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.native.concurrent](../index) / [Continuation0](index) / [<init>](-init-) **Platform and version requirements:** Native (1.3) ``` Continuation0(     block: () -> Unit,     invoker: CPointer<CFunction<(COpaquePointer?) -> Unit>>,     singleShot: Boolean = false) ``` kotlin javaPrimitiveType javaPrimitiveType ================= [kotlin-stdlib](../../../../../index) / [kotlin.jvm](index) / [javaPrimitiveType](java-primitive-type) **Platform and version requirements:** JVM (1.0) ``` val <T : Any> KClass<T>.javaPrimitiveType: Class<T>? ``` Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance representing the primitive type corresponding to the given [KClass](../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) if it exists. kotlin Package kotlin.jvm Package kotlin.jvm ================== [kotlin-stdlib](../../../../../index) / [kotlin.jvm](index) Functions and annotations specific to the Java platform. Types ----- **Platform and version requirements:** JVM (1.6), JRE8 (1.6) #### [JvmRepeatable](-jvm-repeatable) Makes the annotation class repeatable in Java and Kotlin. A repeatable annotation can be applied more than once on the same element. ``` typealias JvmRepeatable = Repeatable ``` Annotations ----------- **Platform and version requirements:** JVM (1.2) #### [JvmDefault](-jvm-default/index) Specifies that a JVM default method should be generated for non-abstract Kotlin interface member. ``` annotation class JvmDefault ``` **Platform and version requirements:** JVM (1.6) #### [JvmDefaultWithCompatibility](-jvm-default-with-compatibility/index) Forces the compiler to generate compatibility accessors for the annotated interface in the `DefaultImpls` class. Please note that if an interface is annotated with this annotation for binary compatibility, public derived Kotlin interfaces should also be annotated with it, because their `DefaultImpls` methods will be used to access implementations from the `DefaultImpls` class of the original interface. ``` annotation class JvmDefaultWithCompatibility ``` **Platform and version requirements:** JVM (1.4) #### [JvmDefaultWithoutCompatibility](-jvm-default-without-compatibility/index) Prevents the compiler from generating compatibility accessors for the annotated class or interface, and suppresses any related compatibility warnings. In other words, this annotation makes the compiler generate the annotated class or interface in the `-Xjvm-default=all` mode, where only JVM default methods are generated, without `DefaultImpls`. ``` annotation class JvmDefaultWithoutCompatibility ``` **Platform and version requirements:** JVM (1.0) #### [JvmField](-jvm-field/index) Instructs the Kotlin compiler not to generate getters/setters for this property and expose it as a field. ``` annotation class JvmField ``` **Platform and version requirements:** JVM (1.5) #### [JvmInline](-jvm-inline/index) Specifies that given value class is inline class. ``` annotation class JvmInline ``` **Platform and version requirements:** JVM (1.0) #### [JvmMultifileClass](-jvm-multifile-class/index) Instructs the Kotlin compiler to generate a multifile class with top-level functions and properties declared in this file as one of its parts. Name of the corresponding multifile class is provided by the [JvmName](-jvm-name/index#kotlin.jvm.JvmName) annotation. ``` annotation class JvmMultifileClass ``` **Platform and version requirements:** JVM (1.0) #### [JvmName](-jvm-name/index) Specifies the name for the Java class or method which is generated from this element. ``` annotation class JvmName ``` **Platform and version requirements:** JVM (1.0) #### [JvmOverloads](-jvm-overloads/index) Instructs the Kotlin compiler to generate overloads for this function that substitute default parameter values. ``` annotation class JvmOverloads ``` **Platform and version requirements:** JVM (1.5) #### [JvmRecord](-jvm-record/index) Instructs compiler to mark the class as a record and generate relevant toString/equals/hashCode methods ``` annotation class JvmRecord ``` **Platform and version requirements:** JVM (1.8) #### [JvmSerializableLambda](-jvm-serializable-lambda/index) Makes the annotated lambda function implement `java.io.Serializable`, generates a pretty `toString` implementation and adds reflection metadata. ``` annotation class JvmSerializableLambda ``` **Platform and version requirements:** JVM (1.0) #### [JvmStatic](-jvm-static/index) Specifies that an additional static method needs to be generated from this element if it's a function. If this element is a property, additional static getter/setter methods should be generated. ``` annotation class JvmStatic ``` **Platform and version requirements:** JVM (1.0) #### [JvmSuppressWildcards](-jvm-suppress-wildcards/index) Instructs compiler to generate or omit wildcards for type arguments corresponding to parameters with declaration-site variance, for example such as `Collection<out T>` has. ``` annotation class JvmSuppressWildcards ``` **Platform and version requirements:** JVM (1.0) #### [JvmSynthetic](-jvm-synthetic/index) Sets `ACC_SYNTHETIC` flag on the annotated target in the Java bytecode. ``` annotation class JvmSynthetic ``` **Platform and version requirements:** JVM (1.0) #### [JvmWildcard](-jvm-wildcard/index) Instructs compiler to generate wildcard for annotated type arguments corresponding to parameters with declaration-site variance. ``` annotation class JvmWildcard ``` **Platform and version requirements:** JVM (1.0) #### [PurelyImplements](-purely-implements/index) Instructs the Kotlin compiler to treat annotated Java class as pure implementation of given Kotlin interface. "Pure" means here that each type parameter of class becomes non-platform type argument of that interface. ``` annotation class PurelyImplements ``` **Platform and version requirements:** JVM (1.0) #### [Strictfp](-strictfp/index) Marks the JVM method generated from the annotated function as `strictfp`, meaning that the precision of floating point operations performed inside the method needs to be restricted in order to achieve better portability. ``` annotation class Strictfp ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### [Synchronized](-synchronized/index) Marks the JVM method generated from the annotated function as `synchronized`, meaning that the method will be protected from concurrent execution by multiple threads by the monitor of the instance (or, for static methods, the class) on which the method is defined. ``` annotation class Synchronized ``` **Platform and version requirements:** JVM (1.0) #### [Throws](-throws/index) This annotation indicates what exceptions should be declared by a function when compiled to a JVM method. ``` annotation class Throws ``` **Platform and version requirements:** JVM (1.0) #### [Transient](-transient/index) Marks the JVM backing field of the annotated property as `transient`, meaning that it is not part of the default serialized form of the object. ``` annotation class Transient ``` **Platform and version requirements:** JVM (1.0), JS (1.0) #### [Volatile](-volatile/index) Marks the JVM backing field of the annotated property as `volatile`, meaning that writes to this field are immediately made visible to other threads. ``` annotation class Volatile ``` Exceptions ---------- **Platform and version requirements:** JVM (1.0) #### [KotlinReflectionNotSupportedError](-kotlin-reflection-not-supported-error/index) ``` open class KotlinReflectionNotSupportedError : Error ``` Extensions for External Classes ------------------------------- **Platform and version requirements:** JVM (1.0) #### [java.lang.Class](java.lang.-class/index) Properties ---------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](annotation-class) Returns a [KClass](../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` **Platform and version requirements:** JVM (1.7) #### [declaringJavaClass](declaring-java-class) Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance of the enum the given constant belongs to. ``` val <E : Enum<E>> Enum<E>.declaringJavaClass: Class<E> ``` **Platform and version requirements:** JVM (1.0) #### <java> Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance corresponding to the given [KClass](../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance. ``` val <T> KClass<T>.java: Class<T> ``` **Platform and version requirements:** JVM (1.0) #### [javaClass](java-class) Returns the runtime Java class of this object. ``` val <T : Any> T.javaClass: Class<T> ``` ``` val <T : Any> KClass<T>.javaClass: Class<KClass<T>> ``` **Platform and version requirements:** JVM (1.0) #### [javaObjectType](java-object-type) Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance corresponding to the given [KClass](../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance. In case of primitive types it returns corresponding wrapper classes. ``` val <T : Any> KClass<T>.javaObjectType: Class<T> ``` **Platform and version requirements:** JVM (1.0) #### [javaPrimitiveType](java-primitive-type) Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance representing the primitive type corresponding to the given [KClass](../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) if it exists. ``` val <T : Any> KClass<T>.javaPrimitiveType: Class<T>? ``` Functions --------- **Platform and version requirements:** JVM (1.0) #### [isArrayOf](is-array-of) Checks if array can contain element of type [T](is-array-of#T). ``` fun <T : Any> Array<*>.isArrayOf(): Boolean ```
programming_docs
kotlin JvmRepeatable JvmRepeatable ============= [kotlin-stdlib](../../../../../index) / [kotlin.jvm](index) / [JvmRepeatable](-jvm-repeatable) **Platform and version requirements:** JVM (1.6), JRE8 (1.6) ``` typealias JvmRepeatable = Repeatable ``` Makes the annotation class repeatable in Java and Kotlin. A repeatable annotation can be applied more than once on the same element. kotlin declaringJavaClass declaringJavaClass ================== [kotlin-stdlib](../../../../../index) / [kotlin.jvm](index) / [declaringJavaClass](declaring-java-class) **Platform and version requirements:** JVM (1.7) ``` inline val <E : Enum<E>> Enum<E>.declaringJavaClass: Class<E> ``` Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance of the enum the given constant belongs to. **See Also** [java.lang.Enum.getDeclaringClass](https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#getDeclaringClass--) kotlin isArrayOf isArrayOf ========= [kotlin-stdlib](../../../../../index) / [kotlin.jvm](index) / [isArrayOf](is-array-of) **Platform and version requirements:** JVM (1.0) ``` fun <reified T : Any> Array<*>.isArrayOf(): Boolean ``` Checks if array can contain element of type [T](is-array-of#T). kotlin annotationClass annotationClass =============== [kotlin-stdlib](../../../../../index) / [kotlin.jvm](index) / [annotationClass](annotation-class) **Platform and version requirements:** JVM (1.0) ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` Returns a [KClass](../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. kotlin javaObjectType javaObjectType ============== [kotlin-stdlib](../../../../../index) / [kotlin.jvm](index) / [javaObjectType](java-object-type) **Platform and version requirements:** JVM (1.0) ``` val <T : Any> KClass<T>.javaObjectType: Class<T> ``` Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance corresponding to the given [KClass](../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance. In case of primitive types it returns corresponding wrapper classes. kotlin java java ==== [kotlin-stdlib](../../../../../index) / [kotlin.jvm](index) / <java> **Platform and version requirements:** JVM (1.0) ``` val <T> KClass<T>.java: Class<T> ``` Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance corresponding to the given [KClass](../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance. kotlin javaClass javaClass ========= [kotlin-stdlib](../../../../../index) / [kotlin.jvm](index) / [javaClass](java-class) **Platform and version requirements:** JVM (1.0) ``` inline val <T : Any> T.javaClass: Class<T> ``` Returns the runtime Java class of this object. **Platform and version requirements:** JVM (1.0) ``` inline val <T : Any> KClass<T>.javaClass: Class<KClass<T>> ``` **Deprecated:** Use 'java' property to get Java class corresponding to this Kotlin class or cast this instance to Any if you really want to get the runtime Java class of this implementation of KClass. kotlin PurelyImplements PurelyImplements ================ [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [PurelyImplements](index) **Platform and version requirements:** JVM (1.0) ``` @Target([AnnotationTarget.CLASS]) annotation class PurelyImplements ``` Instructs the Kotlin compiler to treat annotated Java class as pure implementation of given Kotlin interface. "Pure" means here that each type parameter of class becomes non-platform type argument of that interface. Example: ``` class MyList<T> extends AbstractList<T> { ... } ``` Methods defined in `MyList<T>` use `T` as platform, i.e. it's possible to perform unsafe operation in Kotlin: ``` MyList<Int>().add(null) // compiles ``` ``` @PurelyImplements("kotlin.collections.MutableList") class MyPureList<T> extends AbstractList<T> { ... } ``` Methods defined in `MyPureList<T>` overriding methods in `MutableList` use `T` as non-platform types: ``` MyPureList<Int>().add(null) // Error MyPureList<Int?>().add(null) // Ok ``` Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Instructs the Kotlin compiler to treat annotated Java class as pure implementation of given Kotlin interface. "Pure" means here that each type parameter of class becomes non-platform type argument of that interface. ``` PurelyImplements(value: String) ``` Properties ---------- **Platform and version requirements:** JVM (1.0) #### <value> ``` val value: String ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [PurelyImplements](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` PurelyImplements(value: String) ``` Instructs the Kotlin compiler to treat annotated Java class as pure implementation of given Kotlin interface. "Pure" means here that each type parameter of class becomes non-platform type argument of that interface. Example: ``` class MyList<T> extends AbstractList<T> { ... } ``` Methods defined in `MyList<T>` use `T` as platform, i.e. it's possible to perform unsafe operation in Kotlin: ``` MyList<Int>().add(null) // compiles ``` ``` @PurelyImplements("kotlin.collections.MutableList") class MyPureList<T> extends AbstractList<T> { ... } ``` Methods defined in `MyPureList<T>` overriding methods in `MutableList` use `T` as non-platform types: ``` MyPureList<Int>().add(null) // Error MyPureList<Int?>().add(null) // Ok ``` kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [PurelyImplements](index) / <value> **Platform and version requirements:** JVM (1.0) ``` val value: String ``` kotlin JvmStatic JvmStatic ========= [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmStatic](index) **Platform and version requirements:** JVM (1.0) ``` @Target([AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER]) annotation class JvmStatic ``` Specifies that an additional static method needs to be generated from this element if it's a function. If this element is a property, additional static getter/setter methods should be generated. See the [Kotlin language documentation](../../../../../../docs/java-to-kotlin-interop#static-methods) for more information. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Specifies that an additional static method needs to be generated from this element if it's a function. If this element is a property, additional static getter/setter methods should be generated. ``` <init>() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmStatic](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` <init>() ``` Specifies that an additional static method needs to be generated from this element if it's a function. If this element is a property, additional static getter/setter methods should be generated. See the [Kotlin language documentation](../../../../../../docs/java-to-kotlin-interop#static-methods) for more information. kotlin JvmField JvmField ======== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmField](index) **Platform and version requirements:** JVM (1.0) ``` @Target([AnnotationTarget.FIELD]) annotation class JvmField ``` Instructs the Kotlin compiler not to generate getters/setters for this property and expose it as a field. See the [Kotlin language documentation](../../../../../../docs/java-to-kotlin-interop#instance-fields) for more information. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Instructs the Kotlin compiler not to generate getters/setters for this property and expose it as a field. ``` <init>() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmField](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` <init>() ``` Instructs the Kotlin compiler not to generate getters/setters for this property and expose it as a field. See the [Kotlin language documentation](../../../../../../docs/java-to-kotlin-interop#instance-fields) for more information. kotlin JvmInline JvmInline ========= [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmInline](index) **Platform and version requirements:** JVM (1.5) ``` @Target([AnnotationTarget.CLASS]) annotation class JvmInline ``` Specifies that given value class is inline class. Adding and removing the annotation is binary incompatible change, since inline classes' methods and functions with inline classes in their signature are mangled. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Specifies that given value class is inline class. ``` <init>() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmInline](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` <init>() ``` Specifies that given value class is inline class. Adding and removing the annotation is binary incompatible change, since inline classes' methods and functions with inline classes in their signature are mangled. kotlin Strictfp Strictfp ======== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [Strictfp](index) **Platform and version requirements:** JVM (1.0) ``` @Target([AnnotationTarget.FUNCTION, AnnotationTarget.CONSTRUCTOR, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.CLASS]) annotation class Strictfp ``` Marks the JVM method generated from the annotated function as `strictfp`, meaning that the precision of floating point operations performed inside the method needs to be restricted in order to achieve better portability. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Marks the JVM method generated from the annotated function as `strictfp`, meaning that the precision of floating point operations performed inside the method needs to be restricted in order to achieve better portability. ``` <init>() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [Strictfp](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` <init>() ``` Marks the JVM method generated from the annotated function as `strictfp`, meaning that the precision of floating point operations performed inside the method needs to be restricted in order to achieve better portability. kotlin Throws Throws ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [Throws](index) **Platform and version requirements:** JVM (1.0) ``` @Target([AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.CONSTRUCTOR]) annotation class Throws ``` This annotation indicates what exceptions should be declared by a function when compiled to a JVM method. Example: ``` @Throws(IOException::class) fun readFile(name: String): String {...} ``` will be translated to ``` String readFile(String name) throws IOException {...} ``` Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) This annotation indicates what exceptions should be declared by a function when compiled to a JVM method. ``` Throws(vararg exceptionClasses: KClass<out Throwable>) ``` Properties ---------- **Platform and version requirements:** JVM (1.0) #### [exceptionClasses](exception-classes) the list of checked exception classes that may be thrown by the function. ``` vararg val exceptionClasses: Array<out KClass<out Throwable>> ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin exceptionClasses exceptionClasses ================ [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [Throws](index) / [exceptionClasses](exception-classes) **Platform and version requirements:** JVM (1.0) ``` vararg val exceptionClasses: Array<out KClass<out Throwable>> ``` the list of checked exception classes that may be thrown by the function. Property -------- `exceptionClasses` - the list of checked exception classes that may be thrown by the function. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [Throws](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` Throws(vararg exceptionClasses: KClass<out Throwable>) ``` This annotation indicates what exceptions should be declared by a function when compiled to a JVM method. Example: ``` @Throws(IOException::class) fun readFile(name: String): String {...} ``` will be translated to ``` String readFile(String name) throws IOException {...} ``` kotlin JvmMultifileClass JvmMultifileClass ================= [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmMultifileClass](index) **Platform and version requirements:** JVM (1.0) ``` @Target([AnnotationTarget.FILE]) annotation class JvmMultifileClass ``` Instructs the Kotlin compiler to generate a multifile class with top-level functions and properties declared in this file as one of its parts. Name of the corresponding multifile class is provided by the [JvmName](../-jvm-name/index#kotlin.jvm.JvmName) annotation. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Instructs the Kotlin compiler to generate a multifile class with top-level functions and properties declared in this file as one of its parts. Name of the corresponding multifile class is provided by the [JvmName](../-jvm-name/index#kotlin.jvm.JvmName) annotation. ``` <init>() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmMultifileClass](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` <init>() ``` Instructs the Kotlin compiler to generate a multifile class with top-level functions and properties declared in this file as one of its parts. Name of the corresponding multifile class is provided by the [JvmName](../-jvm-name/index#kotlin.jvm.JvmName) annotation. kotlin kotlin kotlin ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [java.lang.Class](index) / <kotlin> **Platform and version requirements:** JVM (1.0) ``` val <T : Any> Class<T>.kotlin: KClass<T> ``` Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the given Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance. kotlin Extensions for java.lang.Class Extensions for java.lang.Class ============================== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [java.lang.Class](index) **Platform and version requirements:** JVM (1.0) #### <kotlin> Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the given Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance. ``` val <T : Any> Class<T>.kotlin: KClass<T> ``` kotlin JvmOverloads JvmOverloads ============ [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmOverloads](index) **Platform and version requirements:** JVM (1.0) ``` @Target([AnnotationTarget.FUNCTION, AnnotationTarget.CONSTRUCTOR]) annotation class JvmOverloads ``` Instructs the Kotlin compiler to generate overloads for this function that substitute default parameter values. If a method has N parameters and M of which have default values, M overloads are generated: the first one takes N-1 parameters (all but the last one that takes a default value), the second takes N-2 parameters, and so on. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Instructs the Kotlin compiler to generate overloads for this function that substitute default parameter values. ``` <init>() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmOverloads](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` <init>() ``` Instructs the Kotlin compiler to generate overloads for this function that substitute default parameter values. If a method has N parameters and M of which have default values, M overloads are generated: the first one takes N-1 parameters (all but the last one that takes a default value), the second takes N-2 parameters, and so on.
programming_docs
kotlin JvmDefaultWithCompatibility JvmDefaultWithCompatibility =========================== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmDefaultWithCompatibility](index) **Platform and version requirements:** JVM (1.6) ``` @Target([AnnotationTarget.CLASS]) annotation class JvmDefaultWithCompatibility ``` Forces the compiler to generate compatibility accessors for the annotated interface in the `DefaultImpls` class. Please note that if an interface is annotated with this annotation for binary compatibility, public derived Kotlin interfaces should also be annotated with it, because their `DefaultImpls` methods will be used to access implementations from the `DefaultImpls` class of the original interface. Used only with `-Xjvm-default=all`. For more details refer to `-Xjvm-default` documentation. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Forces the compiler to generate compatibility accessors for the annotated interface in the `DefaultImpls` class. Please note that if an interface is annotated with this annotation for binary compatibility, public derived Kotlin interfaces should also be annotated with it, because their `DefaultImpls` methods will be used to access implementations from the `DefaultImpls` class of the original interface. ``` JvmDefaultWithCompatibility() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmDefaultWithCompatibility](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` JvmDefaultWithCompatibility() ``` Forces the compiler to generate compatibility accessors for the annotated interface in the `DefaultImpls` class. Please note that if an interface is annotated with this annotation for binary compatibility, public derived Kotlin interfaces should also be annotated with it, because their `DefaultImpls` methods will be used to access implementations from the `DefaultImpls` class of the original interface. Used only with `-Xjvm-default=all`. For more details refer to `-Xjvm-default` documentation. kotlin Transient Transient ========= [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [Transient](index) **Platform and version requirements:** JVM (1.0) ``` @Target([AnnotationTarget.FIELD]) annotation class Transient ``` Marks the JVM backing field of the annotated property as `transient`, meaning that it is not part of the default serialized form of the object. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Marks the JVM backing field of the annotated property as `transient`, meaning that it is not part of the default serialized form of the object. ``` <init>() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [Transient](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` <init>() ``` Marks the JVM backing field of the annotated property as `transient`, meaning that it is not part of the default serialized form of the object. kotlin JvmWildcard JvmWildcard =========== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmWildcard](index) **Platform and version requirements:** JVM (1.0) ``` @Target([AnnotationTarget.TYPE]) annotation class JvmWildcard ``` Instructs compiler to generate wildcard for annotated type arguments corresponding to parameters with declaration-site variance. It may be helpful only if declaration seems to be inconvenient to use from Java without wildcard. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Instructs compiler to generate wildcard for annotated type arguments corresponding to parameters with declaration-site variance. ``` <init>() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmWildcard](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` <init>() ``` Instructs compiler to generate wildcard for annotated type arguments corresponding to parameters with declaration-site variance. It may be helpful only if declaration seems to be inconvenient to use from Java without wildcard. kotlin KotlinReflectionNotSupportedError KotlinReflectionNotSupportedError ================================= [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [KotlinReflectionNotSupportedError](index) **Platform and version requirements:** JVM (1.0) ``` open class KotlinReflectionNotSupportedError : Error ``` Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) ``` KotlinReflectionNotSupportedError() ``` ``` KotlinReflectionNotSupportedError(message: String?) ``` ``` KotlinReflectionNotSupportedError(     message: String?,     cause: Throwable?) ``` ``` KotlinReflectionNotSupportedError(cause: Throwable?) ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [stackTrace](../../kotlin/stack-trace) Returns an array of stack trace elements representing the stack trace pertaining to this throwable. ``` val Throwable.stackTrace: Array<StackTraceElement> ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0) #### [printStackTrace](../../kotlin/print-stack-trace) Prints the [detailed description](../../kotlin/stack-trace-to-string#kotlin%24stackTraceToString(kotlin.Throwable)) of this throwable to the specified [writer](../../kotlin/print-stack-trace#kotlin%24printStackTrace(kotlin.Throwable,%20java.io.PrintWriter)/writer). ``` fun Throwable.printStackTrace(writer: PrintWriter) ``` Prints the [detailed description](../../kotlin/stack-trace-to-string#kotlin%24stackTraceToString(kotlin.Throwable)) of this throwable to the specified [stream](../../kotlin/print-stack-trace#kotlin%24printStackTrace(kotlin.Throwable,%20java.io.PrintStream)/stream). ``` fun Throwable.printStackTrace(stream: PrintStream) ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [KotlinReflectionNotSupportedError](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` KotlinReflectionNotSupportedError() ``` ``` KotlinReflectionNotSupportedError(message: String?) ``` ``` KotlinReflectionNotSupportedError(     message: String?,     cause: Throwable?) ``` ``` KotlinReflectionNotSupportedError(cause: Throwable?) ``` kotlin JvmRecord JvmRecord ========= [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmRecord](index) **Platform and version requirements:** JVM (1.5) ``` @Target([AnnotationTarget.CLASS]) annotation class JvmRecord ``` Instructs compiler to mark the class as a record and generate relevant toString/equals/hashCode methods Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Instructs compiler to mark the class as a record and generate relevant toString/equals/hashCode methods ``` <init>() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmRecord](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` <init>() ``` Instructs compiler to mark the class as a record and generate relevant toString/equals/hashCode methods kotlin JvmSerializableLambda JvmSerializableLambda ===================== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmSerializableLambda](index) **Platform and version requirements:** JVM (1.8) ``` @Target([AnnotationTarget.EXPRESSION]) annotation class JvmSerializableLambda ``` Makes the annotated lambda function implement `java.io.Serializable`, generates a pretty `toString` implementation and adds reflection metadata. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Makes the annotated lambda function implement `java.io.Serializable`, generates a pretty `toString` implementation and adds reflection metadata. ``` JvmSerializableLambda() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmSerializableLambda](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` JvmSerializableLambda() ``` Makes the annotated lambda function implement `java.io.Serializable`, generates a pretty `toString` implementation and adds reflection metadata. kotlin JvmSuppressWildcards JvmSuppressWildcards ==================== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmSuppressWildcards](index) **Platform and version requirements:** JVM (1.0) ``` @Target([AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY, AnnotationTarget.TYPE]) annotation class JvmSuppressWildcards ``` Instructs compiler to generate or omit wildcards for type arguments corresponding to parameters with declaration-site variance, for example such as `Collection<out T>` has. If the innermost applied `@JvmSuppressWildcards` has `suppress=true`, the type is generated without wildcards. If the innermost applied `@JvmSuppressWildcards` has `suppress=false`, the type is generated with wildcards. It may be helpful only if declaration seems to be inconvenient to use from Java. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Instructs compiler to generate or omit wildcards for type arguments corresponding to parameters with declaration-site variance, for example such as `Collection<out T>` has. ``` <init>(suppress: Boolean = true) ``` Properties ---------- **Platform and version requirements:** JVM (1.0) #### <suppress> ``` val suppress: Boolean ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmSuppressWildcards](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` <init>(suppress: Boolean = true) ``` Instructs compiler to generate or omit wildcards for type arguments corresponding to parameters with declaration-site variance, for example such as `Collection<out T>` has. If the innermost applied `@JvmSuppressWildcards` has `suppress=true`, the type is generated without wildcards. If the innermost applied `@JvmSuppressWildcards` has `suppress=false`, the type is generated with wildcards. It may be helpful only if declaration seems to be inconvenient to use from Java. kotlin suppress suppress ======== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmSuppressWildcards](index) / <suppress> **Platform and version requirements:** JVM (1.0) ``` val suppress: Boolean ``` kotlin Synchronized Synchronized ============ [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [Synchronized](index) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` @Target([AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER]) annotation class Synchronized ``` Marks the JVM method generated from the annotated function as `synchronized`, meaning that the method will be protected from concurrent execution by multiple threads by the monitor of the instance (or, for static methods, the class) on which the method is defined. Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0) #### [<init>](-init-) Marks the JVM method generated from the annotated function as `synchronized`, meaning that the method will be protected from concurrent execution by multiple threads by the monitor of the instance (or, for static methods, the class) on which the method is defined. ``` <init>() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [Synchronized](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` <init>() ``` Marks the JVM method generated from the annotated function as `synchronized`, meaning that the method will be protected from concurrent execution by multiple threads by the monitor of the instance (or, for static methods, the class) on which the method is defined. kotlin JvmDefault JvmDefault ========== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmDefault](index) **Platform and version requirements:** JVM (1.2) ``` @Target([AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY]) annotation class JvmDefault ``` **Deprecated:** Switch to new -Xjvm-default modes: `all` or `all-compatibility` Specifies that a JVM default method should be generated for non-abstract Kotlin interface member. Usages of this annotation require an explicit compilation argument to be specified: either `-Xjvm-default=enable` or `-Xjvm-default=compatibility`. * with `-Xjvm-default=enable`, only default method in interface is generated for each @[JvmDefault](index) method. In this mode, annotating an existing method with @[JvmDefault](index) can break binary compatibility, because it will effectively remove the method from the `DefaultImpls` class. * with `-Xjvm-default=compatibility`, in addition to the default interface method, a compatibility accessor is generated in the `DefaultImpls` class, that calls the default interface method via a synthetic accessor. In this mode, annotating an existing method with @[JvmDefault](index) is binary compatible, but results in more methods in bytecode. Removing this annotation from an interface member is a binary incompatible change in both modes. Generation of default methods is only possible with JVM target bytecode version 1.8 (`-jvm-target 1.8`) or higher. @[JvmDefault](index) methods are excluded from interface delegation. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Specifies that a JVM default method should be generated for non-abstract Kotlin interface member. ``` JvmDefault() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmDefault](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` JvmDefault() ``` Specifies that a JVM default method should be generated for non-abstract Kotlin interface member. Usages of this annotation require an explicit compilation argument to be specified: either `-Xjvm-default=enable` or `-Xjvm-default=compatibility`. * with `-Xjvm-default=enable`, only default method in interface is generated for each @[JvmDefault](index) method. In this mode, annotating an existing method with @[JvmDefault](index) can break binary compatibility, because it will effectively remove the method from the `DefaultImpls` class. * with `-Xjvm-default=compatibility`, in addition to the default interface method, a compatibility accessor is generated in the `DefaultImpls` class, that calls the default interface method via a synthetic accessor. In this mode, annotating an existing method with @[JvmDefault](index) is binary compatible, but results in more methods in bytecode. Removing this annotation from an interface member is a binary incompatible change in both modes. Generation of default methods is only possible with JVM target bytecode version 1.8 (`-jvm-target 1.8`) or higher. @[JvmDefault](index) methods are excluded from interface delegation. kotlin Volatile Volatile ======== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [Volatile](index) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` @Target([AnnotationTarget.FIELD]) annotation class Volatile ``` Marks the JVM backing field of the annotated property as `volatile`, meaning that writes to this field are immediately made visible to other threads. Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0) #### [<init>](-init-) Marks the JVM backing field of the annotated property as `volatile`, meaning that writes to this field are immediately made visible to other threads. ``` <init>() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [Volatile](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.1) ``` <init>() ``` Marks the JVM backing field of the annotated property as `volatile`, meaning that writes to this field are immediately made visible to other threads.
programming_docs
kotlin JvmDefaultWithoutCompatibility JvmDefaultWithoutCompatibility ============================== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmDefaultWithoutCompatibility](index) **Platform and version requirements:** JVM (1.4) ``` @Target([AnnotationTarget.CLASS]) annotation class JvmDefaultWithoutCompatibility ``` Prevents the compiler from generating compatibility accessors for the annotated class or interface, and suppresses any related compatibility warnings. In other words, this annotation makes the compiler generate the annotated class or interface in the `-Xjvm-default=all` mode, where only JVM default methods are generated, without `DefaultImpls`. Annotating an existing class with this annotation is a binary incompatible change. Therefore this annotation makes the most sense for *new* classes in libraries which opted into the compatibility mode. Used only with `-Xjvm-default=compatibility|all-compatibility`. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Prevents the compiler from generating compatibility accessors for the annotated class or interface, and suppresses any related compatibility warnings. In other words, this annotation makes the compiler generate the annotated class or interface in the `-Xjvm-default=all` mode, where only JVM default methods are generated, without `DefaultImpls`. ``` JvmDefaultWithoutCompatibility() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmDefaultWithoutCompatibility](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` JvmDefaultWithoutCompatibility() ``` Prevents the compiler from generating compatibility accessors for the annotated class or interface, and suppresses any related compatibility warnings. In other words, this annotation makes the compiler generate the annotated class or interface in the `-Xjvm-default=all` mode, where only JVM default methods are generated, without `DefaultImpls`. Annotating an existing class with this annotation is a binary incompatible change. Therefore this annotation makes the most sense for *new* classes in libraries which opted into the compatibility mode. Used only with `-Xjvm-default=compatibility|all-compatibility`. kotlin JvmSynthetic JvmSynthetic ============ [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmSynthetic](index) **Platform and version requirements:** JVM (1.0) ``` @Target([AnnotationTarget.FILE, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.FIELD]) annotation class JvmSynthetic ``` Sets `ACC_SYNTHETIC` flag on the annotated target in the Java bytecode. Synthetic targets become inaccessible for Java sources at compile time while still being accessible for Kotlin sources. Marking target as synthetic is a binary compatible change, already compiled Java code will be able to access such target. This annotation is intended for *rare cases* when API designer needs to hide Kotlin-specific target from Java API while keeping it a part of Kotlin API so the resulting API is idiomatic for both languages. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Sets `ACC_SYNTHETIC` flag on the annotated target in the Java bytecode. ``` <init>() ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmSynthetic](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` <init>() ``` Sets `ACC_SYNTHETIC` flag on the annotated target in the Java bytecode. Synthetic targets become inaccessible for Java sources at compile time while still being accessible for Kotlin sources. Marking target as synthetic is a binary compatible change, already compiled Java code will be able to access such target. This annotation is intended for *rare cases* when API designer needs to hide Kotlin-specific target from Java API while keeping it a part of Kotlin API so the resulting API is idiomatic for both languages. kotlin JvmName JvmName ======= [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmName](index) **Platform and version requirements:** ``` @Target([AnnotationTarget.FILE, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER]) annotation class JvmName ``` **Platform and version requirements:** JVM (1.0) ``` @Target([AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.FILE]) annotation class JvmName ``` Specifies the name for the Java class or method which is generated from this element. See the [Kotlin language documentation](../../../../../../docs/java-to-kotlin-interop#handling-signature-clashes-with-jvmname) for more information. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) Specifies the name for the Java class or method which is generated from this element. ``` <init>(name: String) ``` Properties ---------- **Platform and version requirements:** JVM (1.0) #### <name> the name of the element. ``` val name: String ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [annotationClass](../annotation-class) Returns a [KClass](../../kotlin.reflect/-k-class/index#kotlin.reflect.KClass) instance corresponding to the annotation type of this annotation. ``` val <T : Annotation> T.annotationClass: KClass<out T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmName](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` <init>(name: String) ``` Specifies the name for the Java class or method which is generated from this element. See the [Kotlin language documentation](../../../../../../docs/java-to-kotlin-interop#handling-signature-clashes-with-jvmname) for more information. kotlin name name ==== [kotlin-stdlib](../../../../../../index) / [kotlin.jvm](../index) / [JvmName](index) / <name> **Platform and version requirements:** JVM (1.0) ``` val name: String ``` the name of the element. Property -------- `name` - the name of the element. kotlin parseInt parseInt ======== [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / [parseInt](parse-int) **Platform and version requirements:** JS (1.1) ``` fun parseInt(s: String): Int ``` **Deprecated:** Use toInt() instead. ``` fun parseInt(s: String, radix: Int = definedExternally): Int ``` **Deprecated:** Use toInt(radix) instead. kotlin reset reset ===== [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / <reset> **Platform and version requirements:** JS (1.1) ``` fun RegExp.reset() ``` Resets the regular expression so that subsequent [RegExp.test](-reg-exp/test) and [RegExp.exec](-reg-exp/exec) calls will match starting with the beginning of the input string. kotlin kotlin kotlin ====== [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / <kotlin> **Platform and version requirements:** JS (1.1) ``` val <T : Any> JsClass<T>.kotlin: KClass<T> ``` Obtains a `KClass` instance for the given constructor reference. kotlin asArray asArray ======= [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / [asArray](as-array) **Platform and version requirements:** JS (1.1) ``` fun RegExpMatch.asArray(): Array<out String?> ``` Converts the result of [RegExp.exec](-reg-exp/exec) to an array where the first element contains the entire matched text and each subsequent element is the text matched by each capturing parenthesis. kotlin eval eval ==== [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / <eval> **Platform and version requirements:** JS (1.1) ``` fun eval(expr: String): dynamic ``` Exposes the JavaScript [eval function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) to Kotlin. kotlin Package kotlin.js Package kotlin.js ================= [kotlin-stdlib](../../../../../index) / [kotlin.js](index) Functions and other APIs specific to the JavaScript platform. Types ----- **Platform and version requirements:** JS (1.1) #### [Console](-console/index) Exposes the [console API](https://developer.mozilla.org/en/DOM/console) to Kotlin. ``` interface Console ``` **Platform and version requirements:** JS (1.1) #### [Date](-date/index) Exposes the [Date API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) to Kotlin. ``` class Date ``` **Platform and version requirements:** JS (1.1) #### [JsClass](-js-class/index) Represents the constructor of a class. Instances of `JsClass` can be passed to JavaScript APIs that expect a constructor reference. ``` interface JsClass<T : Any> ``` **Platform and version requirements:** JS (1.1) #### [Json](-json/index) An interface for indexing access to a collection of key-value pairs, where type of key is String and type of value is Any?. ``` interface Json ``` **Platform and version requirements:** JS (1.1) #### [JSON](-j-s-o-n/index) Exposes the JavaScript [JSON object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) to Kotlin. ``` object JSON ``` **Platform and version requirements:** JS (1.1) #### [Promise](-promise/index) Exposes the JavaScript [Promise object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) to Kotlin. ``` open class Promise<out T> ``` **Platform and version requirements:** JS (1.1) #### [RegExp](-reg-exp/index) Exposes the JavaScript [RegExp object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp) to Kotlin. ``` class RegExp ``` **Platform and version requirements:** JS (1.1) #### [RegExpMatch](-reg-exp-match/index) Represents the return value of [RegExp.exec](-reg-exp/exec). ``` interface RegExpMatch ``` Annotations ----------- **Platform and version requirements:** JS (1.6) #### [EagerInitialization](-eager-initialization/index) Forces a top-level property to be initialized eagerly, opposed to lazily on the first access to file and/or property. ``` annotation class EagerInitialization ``` **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) #### [ExperimentalJsExport](-experimental-js-export/index) Marks experimental JS export annotations. ``` annotation class ExperimentalJsExport ``` **Platform and version requirements:** JS (1.3) #### [JsExport](-js-export/index) Exports top-level declaration on JS platform. ``` annotation class JsExport ``` **Platform and version requirements:** JS (1.1) #### [JsModule](-js-module/index) Denotes an `external` declaration that must be imported from native JavaScript library. ``` annotation class JsModule ``` **Platform and version requirements:** JS (1.0) #### [JsName](-js-name/index) Gives a declaration (a function, a property or a class) specific name in JavaScript. ``` annotation class JsName ``` **Platform and version requirements:** JS (1.1) #### [JsNonModule](-js-non-module/index) Denotes an `external` declaration that can be used without module system. ``` annotation class JsNonModule ``` **Platform and version requirements:** JS (1.1) #### [JsQualifier](-js-qualifier/index) Adds prefix to `external` declarations in a source file. ``` annotation class JsQualifier ``` **Platform and version requirements:** JS (1.1) #### [nativeGetter](native-getter/index) ``` annotation class nativeGetter ``` **Platform and version requirements:** JS (1.1) #### [nativeInvoke](native-invoke/index) ``` annotation class nativeInvoke ``` **Platform and version requirements:** JS (1.1) #### [nativeSetter](native-setter/index) ``` annotation class nativeSetter ``` Properties ---------- **Platform and version requirements:** JS (1.1) #### <console> Exposes the [console API](https://developer.mozilla.org/en/DOM/console) to Kotlin. ``` val console: Console ``` **Platform and version requirements:** JS (1.1) #### [definedExternally](defined-externally) The property that can be used as a placeholder for statements and values that are defined in JavaScript. ``` val definedExternally: Nothing ``` **Platform and version requirements:** JS (1.1) #### <js> Obtains a constructor reference for the given `KClass`. ``` val <T : Any> KClass<T>.js: JsClass<T> ``` **Platform and version requirements:** JS (1.1) #### <kotlin> Obtains a `KClass` instance for the given constructor reference. ``` val <T : Any> JsClass<T>.kotlin: KClass<T> ``` **Platform and version requirements:** JS (1.1) #### [noImpl](no-impl) ``` val noImpl: Nothing ``` **Platform and version requirements:** JS (1.1) #### <undefined> Exposes the JavaScript [undefined property](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) to Kotlin. ``` val undefined: Nothing? ``` Functions --------- **Platform and version requirements:** JS (1.1) #### <add> Adds key-value pairs from [other](add#kotlin.js%24add(kotlin.js.Json,%20kotlin.js.Json)/other) to [this](add/-this-). Returns the original receiver. ``` fun Json.add(other: Json): Json ``` **Platform and version requirements:** JS (1.1) #### [asArray](as-array) Converts the result of [RegExp.exec](-reg-exp/exec) to an array where the first element contains the entire matched text and each subsequent element is the text matched by each capturing parenthesis. ``` fun RegExpMatch.asArray(): Array<out String?> ``` **Platform and version requirements:** JS (1.1) #### [asDynamic](as-dynamic) Reinterprets this value as a value of the [dynamic type](../../../../../docs/dynamic-type). ``` fun Any?.asDynamic(): dynamic ``` **Platform and version requirements:** JS (1.1) #### [dateLocaleOptions](date-locale-options) ``` fun dateLocaleOptions(     init: LocaleOptions.() -> Unit ): LocaleOptions ``` **Platform and version requirements:** JS (1.1) #### <eval> Exposes the JavaScript [eval function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) to Kotlin. ``` fun eval(expr: String): dynamic ``` **Platform and version requirements:** JS (1.1) #### <get> Returns the entire text matched by [RegExp.exec](-reg-exp/exec) if the [index](get#kotlin.js%24get(kotlin.js.RegExpMatch,%20kotlin.Int)/index) parameter is 0, or the text matched by the capturing parenthesis at the given index. ``` operator fun RegExpMatch.get(index: Int): String? ``` **Platform and version requirements:** JS (1.1) #### <iterator> Allows to iterate this `dynamic` object in the following cases: ``` operator fun dynamic.iterator(): Iterator<dynamic> ``` **Platform and version requirements:** JS (1.1) #### <js> Puts the given piece of a JavaScript code right into the calling function. The compiler replaces call to `js(...)` code with the string constant provided as a parameter. ``` fun js(code: String): dynamic ``` **Platform and version requirements:** JS (1.1) #### <json> Returns a simple JavaScript object (as [Json](-json/index)) using provided key-value pairs as names and values of its properties. ``` fun json(vararg pairs: Pair<String, Any?>): Json ``` **Platform and version requirements:** JS (1.1) #### [jsTypeOf](js-type-of) Function corresponding to JavaScript's `typeof` operator ``` fun jsTypeOf(a: Any?): String ``` **Platform and version requirements:** JS (1.1) #### [parseFloat](parse-float) ``` fun parseFloat(     s: String,     radix: Int = definedExternally ): Double ``` **Platform and version requirements:** JS (1.1) #### [parseInt](parse-int) ``` fun parseInt(s: String): Int ``` ``` fun parseInt(s: String, radix: Int = definedExternally): Int ``` **Platform and version requirements:** JS (1.1) #### <reset> Resets the regular expression so that subsequent [RegExp.test](-reg-exp/test) and [RegExp.exec](-reg-exp/exec) calls will match starting with the beginning of the input string. ``` fun RegExp.reset() ``` **Platform and version requirements:** JS (1.1) #### <then> ``` fun <T, S> Promise<Promise<T>>.then(     onFulfilled: ((T) -> S)? ): Promise<S> ``` ``` fun <T, S> Promise<Promise<T>>.then(     onFulfilled: ((T) -> S)?,     onRejected: ((Throwable) -> S)? ): Promise<S> ``` **Platform and version requirements:** JS (1.1) #### [unsafeCast](unsafe-cast) Reinterprets this value as a value of the specified type [T](unsafe-cast#T) without any actual type checking. ``` fun <T> Any?.unsafeCast(): T ``` Reinterprets this `dynamic` value as a value of the specified type [T](unsafe-cast#T) without any actual type checking. ``` fun <T> dynamic.unsafeCast(): T ``` kotlin definedExternally definedExternally ================= [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / [definedExternally](defined-externally) **Platform and version requirements:** JS (1.1) ``` val definedExternally: Nothing ``` The property that can be used as a placeholder for statements and values that are defined in JavaScript. This property can be used in two cases: * To represent body of an external function. In most cases Kotlin does not require to provide bodies of external functions and properties, but if for some reason you want to (for example, due to limitation of your coding style guides), you should use `definedExternally`. * To represent value of default argument. There's two forms of using `definedExternally`: 1. `= definedExternally` (for functions, properties and parameters). 2. `{ definedExternally }` (for functions and property getters/setters). This property can't be used from normal code. Examples: ``` external fun foo(): String = definedExternally external fun bar(x: Int) { definedExternally } external fun baz(z: Any = definedExternally): Array<Any> external val prop: Float = definedExternally ``` kotlin undefined undefined ========= [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / <undefined> **Platform and version requirements:** JS (1.1) ``` val undefined: Nothing? ``` Exposes the JavaScript [undefined property](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) to Kotlin. kotlin json json ==== [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / <json> **Platform and version requirements:** JS (1.1) ``` fun json(vararg pairs: Pair<String, Any?>): Json ``` Returns a simple JavaScript object (as [Json](-json/index)) using provided key-value pairs as names and values of its properties. kotlin add add === [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / <add> **Platform and version requirements:** JS (1.1) ``` fun Json.add(other: Json): Json ``` Adds key-value pairs from [other](add#kotlin.js%24add(kotlin.js.Json,%20kotlin.js.Json)/other) to [this](add/-this-). Returns the original receiver.
programming_docs
kotlin then then ==== [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / <then> **Platform and version requirements:** JS (1.1) ``` inline fun <T, S> Promise<Promise<T>>.then(     noinline onFulfilled: ((T) -> S)? ): Promise<S> ``` ``` inline fun <T, S> Promise<Promise<T>>.then(     noinline onFulfilled: ((T) -> S)?,     noinline onRejected: ((Throwable) -> S)? ): Promise<S> ``` kotlin dateLocaleOptions dateLocaleOptions ================= [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / [dateLocaleOptions](date-locale-options) **Platform and version requirements:** JS (1.1) ``` inline fun dateLocaleOptions(     init: LocaleOptions.() -> Unit ): LocaleOptions ``` kotlin parseFloat parseFloat ========== [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / [parseFloat](parse-float) **Platform and version requirements:** JS (1.1) ``` fun parseFloat(     s: String,     radix: Int = definedExternally ): Double ``` **Deprecated:** Use toDouble() instead. kotlin noImpl noImpl ====== [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / [noImpl](no-impl) **Platform and version requirements:** JS (1.1) ``` val noImpl: Nothing ``` **Deprecated:** Use `definedExternally` instead kotlin iterator iterator ======== [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / <iterator> **Platform and version requirements:** JS (1.1) ``` operator fun dynamic.iterator(): Iterator<dynamic> ``` Allows to iterate this `dynamic` object in the following cases: * when it has an `iterator` function, * when it is an array * when it is an instance of [kotlin.collections.Iterable](../kotlin.collections/-iterable/index#kotlin.collections.Iterable) kotlin jsTypeOf jsTypeOf ======== [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / [jsTypeOf](js-type-of) **Platform and version requirements:** JS (1.1) ``` fun jsTypeOf(a: Any?): String ``` Function corresponding to JavaScript's `typeof` operator kotlin js js == [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / <js> **Platform and version requirements:** JS (1.1) ``` fun js(code: String): dynamic ``` Puts the given piece of a JavaScript code right into the calling function. The compiler replaces call to `js(...)` code with the string constant provided as a parameter. Example: ``` fun logToConsole(message: String): Unit { js("console.log(message)") } ``` Parameters ---------- `code` - the piece of JavaScript code to put to the generated code. Must be a compile-time constant, otherwise compiler produces error message. You can safely refer to local variables of calling function (but not to local variables of outer functions), including parameters. You can't refer to functions, properties and classes by their short names. **Platform and version requirements:** JS (1.1) ``` val <T : Any> KClass<T>.js: JsClass<T> ``` Obtains a constructor reference for the given `KClass`. kotlin console console ======= [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / <console> **Platform and version requirements:** JS (1.1) ``` val console: Console ``` Exposes the [console API](https://developer.mozilla.org/en/DOM/console) to Kotlin. kotlin unsafeCast unsafeCast ========== [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / [unsafeCast](unsafe-cast) **Platform and version requirements:** JS (1.1) ``` fun <T> Any?.unsafeCast(): T ``` Reinterprets this value as a value of the specified type [T](unsafe-cast#T) without any actual type checking. **Platform and version requirements:** JS (1.1) ``` fun <T> dynamic.unsafeCast(): T ``` Reinterprets this `dynamic` value as a value of the specified type [T](unsafe-cast#T) without any actual type checking. kotlin get get === [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / <get> **Platform and version requirements:** JS (1.1) ``` operator fun RegExpMatch.get(index: Int): String? ``` Returns the entire text matched by [RegExp.exec](-reg-exp/exec) if the [index](get#kotlin.js%24get(kotlin.js.RegExpMatch,%20kotlin.Int)/index) parameter is 0, or the text matched by the capturing parenthesis at the given index. kotlin asDynamic asDynamic ========= [kotlin-stdlib](../../../../../index) / [kotlin.js](index) / [asDynamic](as-dynamic) **Platform and version requirements:** JS (1.1) ``` fun Any?.asDynamic(): dynamic ``` Reinterprets this value as a value of the [dynamic type](../../../../../docs/dynamic-type). kotlin toLocaleString toLocaleString ============== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [toLocaleString](to-locale-string) **Platform and version requirements:** JS (1.1) ``` fun toLocaleString(     locales: Array<String> = definedExternally,     options: LocaleOptions = definedExternally ): String ``` ``` fun toLocaleString(     locales: String,     options: LocaleOptions = definedExternally ): String ``` kotlin getFullYear getFullYear =========== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getFullYear](get-full-year) **Platform and version requirements:** JS (1.1) ``` fun getFullYear(): Int ``` kotlin toLocaleDateString toLocaleDateString ================== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [toLocaleDateString](to-locale-date-string) **Platform and version requirements:** JS (1.1) ``` fun toLocaleDateString(     locales: Array<String> = definedExternally,     options: LocaleOptions = definedExternally ): String ``` ``` fun toLocaleDateString(     locales: String,     options: LocaleOptions = definedExternally ): String ``` kotlin getMinutes getMinutes ========== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getMinutes](get-minutes) **Platform and version requirements:** JS (1.1) ``` fun getMinutes(): Int ``` kotlin toLocaleTimeString toLocaleTimeString ================== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [toLocaleTimeString](to-locale-time-string) **Platform and version requirements:** JS (1.1) ``` fun toLocaleTimeString(     locales: Array<String> = definedExternally,     options: LocaleOptions = definedExternally ): String ``` ``` fun toLocaleTimeString(     locales: String,     options: LocaleOptions = definedExternally ): String ``` kotlin Date Date ==== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) **Platform and version requirements:** JS (1.1) ``` class Date ``` Exposes the [Date API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) to Kotlin. Types ----- **Platform and version requirements:** JS (1.1) #### [LocaleOptions](-locale-options/index) ``` interface LocaleOptions ``` Constructors ------------ **Platform and version requirements:** JS (1.1) #### [<init>](-init-) ``` Date(milliseconds: Number) ``` ``` Date(dateString: String) ``` ``` Date(year: Int, month: Int) ``` ``` Date(year: Int, month: Int, day: Int) ``` ``` Date(year: Int, month: Int, day: Int, hour: Int) ``` ``` Date(year: Int, month: Int, day: Int, hour: Int, minute: Int) ``` ``` Date(     year: Int,     month: Int,     day: Int,     hour: Int,     minute: Int,     second: Int) ``` ``` Date(     year: Int,     month: Int,     day: Int,     hour: Int,     minute: Int,     second: Int,     millisecond: Number) ``` Exposes the [Date API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) to Kotlin. ``` Date() ``` Functions --------- **Platform and version requirements:** JS (1.1) #### [getDate](get-date) ``` fun getDate(): Int ``` **Platform and version requirements:** JS (1.1) #### [getDay](get-day) ``` fun getDay(): Int ``` **Platform and version requirements:** JS (1.1) #### [getFullYear](get-full-year) ``` fun getFullYear(): Int ``` **Platform and version requirements:** JS (1.1) #### [getHours](get-hours) ``` fun getHours(): Int ``` **Platform and version requirements:** JS (1.1) #### [getMilliseconds](get-milliseconds) ``` fun getMilliseconds(): Int ``` **Platform and version requirements:** JS (1.1) #### [getMinutes](get-minutes) ``` fun getMinutes(): Int ``` **Platform and version requirements:** JS (1.1) #### [getMonth](get-month) ``` fun getMonth(): Int ``` **Platform and version requirements:** JS (1.1) #### [getSeconds](get-seconds) ``` fun getSeconds(): Int ``` **Platform and version requirements:** JS (1.1) #### [getTime](get-time) ``` fun getTime(): Double ``` **Platform and version requirements:** JS (1.1) #### [getTimezoneOffset](get-timezone-offset) ``` fun getTimezoneOffset(): Int ``` **Platform and version requirements:** JS (1.1) #### [getUTCDate](get-u-t-c-date) ``` fun getUTCDate(): Int ``` **Platform and version requirements:** JS (1.1) #### [getUTCDay](get-u-t-c-day) ``` fun getUTCDay(): Int ``` **Platform and version requirements:** JS (1.1) #### [getUTCFullYear](get-u-t-c-full-year) ``` fun getUTCFullYear(): Int ``` **Platform and version requirements:** JS (1.1) #### [getUTCHours](get-u-t-c-hours) ``` fun getUTCHours(): Int ``` **Platform and version requirements:** JS (1.1) #### [getUTCMilliseconds](get-u-t-c-milliseconds) ``` fun getUTCMilliseconds(): Int ``` **Platform and version requirements:** JS (1.1) #### [getUTCMinutes](get-u-t-c-minutes) ``` fun getUTCMinutes(): Int ``` **Platform and version requirements:** JS (1.1) #### [getUTCMonth](get-u-t-c-month) ``` fun getUTCMonth(): Int ``` **Platform and version requirements:** JS (1.1) #### [getUTCSeconds](get-u-t-c-seconds) ``` fun getUTCSeconds(): Int ``` **Platform and version requirements:** JS (1.1) #### [toDateString](to-date-string) ``` fun toDateString(): String ``` **Platform and version requirements:** JS (1.1) #### [toISOString](to-i-s-o-string) ``` fun toISOString(): String ``` **Platform and version requirements:** JS (1.1) #### [toJSON](to-j-s-o-n) ``` fun toJSON(): Json ``` **Platform and version requirements:** JS (1.1) #### [toLocaleDateString](to-locale-date-string) ``` fun toLocaleDateString(     locales: Array<String> = definedExternally,     options: LocaleOptions = definedExternally ): String ``` ``` fun toLocaleDateString(     locales: String,     options: LocaleOptions = definedExternally ): String ``` **Platform and version requirements:** JS (1.1) #### [toLocaleString](to-locale-string) ``` fun toLocaleString(     locales: Array<String> = definedExternally,     options: LocaleOptions = definedExternally ): String ``` ``` fun toLocaleString(     locales: String,     options: LocaleOptions = definedExternally ): String ``` **Platform and version requirements:** JS (1.1) #### [toLocaleTimeString](to-locale-time-string) ``` fun toLocaleTimeString(     locales: Array<String> = definedExternally,     options: LocaleOptions = definedExternally ): String ``` ``` fun toLocaleTimeString(     locales: String,     options: LocaleOptions = definedExternally ): String ``` **Platform and version requirements:** JS (1.1) #### [toTimeString](to-time-string) ``` fun toTimeString(): String ``` **Platform and version requirements:** JS (1.1) #### [toUTCString](to-u-t-c-string) ``` fun toUTCString(): String ``` Companion Object Functions -------------------------- **Platform and version requirements:** JS (1.1) #### <now> ``` fun now(): Double ``` **Platform and version requirements:** JS (1.1) #### <parse> ``` fun parse(dateString: String): Double ``` **Platform and version requirements:** JS (1.1) #### [UTC](-u-t-c) ``` fun UTC(year: Int, month: Int): Double ``` ``` fun UTC(year: Int, month: Int, day: Int): Double ``` ``` fun UTC(year: Int, month: Int, day: Int, hour: Int): Double ``` ``` fun UTC(     year: Int,     month: Int,     day: Int,     hour: Int,     minute: Int ): Double ``` ``` fun UTC(     year: Int,     month: Int,     day: Int,     hour: Int,     minute: Int,     second: Int ): Double ``` ``` fun UTC(     year: Int,     month: Int,     day: Int,     hour: Int,     minute: Int,     second: Int,     millisecond: Number ): Double ``` kotlin now now === [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / <now> **Platform and version requirements:** JS (1.1) ``` fun now(): Double ``` kotlin getDate getDate ======= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getDate](get-date) **Platform and version requirements:** JS (1.1) ``` fun getDate(): Int ``` kotlin toISOString toISOString =========== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [toISOString](to-i-s-o-string) **Platform and version requirements:** JS (1.1) ``` fun toISOString(): String ``` kotlin getUTCDate getUTCDate ========== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getUTCDate](get-u-t-c-date) **Platform and version requirements:** JS (1.1) ``` fun getUTCDate(): Int ``` kotlin getMonth getMonth ======== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getMonth](get-month) **Platform and version requirements:** JS (1.1) ``` fun getMonth(): Int ``` kotlin getUTCMinutes getUTCMinutes ============= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getUTCMinutes](get-u-t-c-minutes) **Platform and version requirements:** JS (1.1) ``` fun getUTCMinutes(): Int ``` kotlin UTC UTC === [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [UTC](-u-t-c) **Platform and version requirements:** JS (1.1) ``` fun UTC(year: Int, month: Int): Double ``` ``` fun UTC(year: Int, month: Int, day: Int): Double ``` ``` fun UTC(year: Int, month: Int, day: Int, hour: Int): Double ``` ``` fun UTC(     year: Int,     month: Int,     day: Int,     hour: Int,     minute: Int ): Double ``` ``` fun UTC(     year: Int,     month: Int,     day: Int,     hour: Int,     minute: Int,     second: Int ): Double ``` ``` fun UTC(     year: Int,     month: Int,     day: Int,     hour: Int,     minute: Int,     second: Int,     millisecond: Number ): Double ``` kotlin getUTCMonth getUTCMonth =========== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getUTCMonth](get-u-t-c-month) **Platform and version requirements:** JS (1.1) ``` fun getUTCMonth(): Int ``` kotlin getUTCFullYear getUTCFullYear ============== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getUTCFullYear](get-u-t-c-full-year) **Platform and version requirements:** JS (1.1) ``` fun getUTCFullYear(): Int ``` kotlin toUTCString toUTCString =========== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [toUTCString](to-u-t-c-string) **Platform and version requirements:** JS (1.1) ``` fun toUTCString(): String ``` kotlin toDateString toDateString ============ [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [toDateString](to-date-string) **Platform and version requirements:** JS (1.1) ``` fun toDateString(): String ``` kotlin getUTCMilliseconds getUTCMilliseconds ================== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getUTCMilliseconds](get-u-t-c-milliseconds) **Platform and version requirements:** JS (1.1) ``` fun getUTCMilliseconds(): Int ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [<init>](-init-) **Platform and version requirements:** JS (1.1) ``` Date(milliseconds: Number) ``` ``` Date(dateString: String) ``` ``` Date(year: Int, month: Int) ``` ``` Date(year: Int, month: Int, day: Int) ``` ``` Date(year: Int, month: Int, day: Int, hour: Int) ``` ``` Date(year: Int, month: Int, day: Int, hour: Int, minute: Int) ``` ``` Date(     year: Int,     month: Int,     day: Int,     hour: Int,     minute: Int,     second: Int) ``` ``` Date(     year: Int,     month: Int,     day: Int,     hour: Int,     minute: Int,     second: Int,     millisecond: Number) ``` **Platform and version requirements:** JS (1.1) ``` Date() ``` Exposes the [Date API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) to Kotlin. kotlin getUTCSeconds getUTCSeconds ============= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getUTCSeconds](get-u-t-c-seconds) **Platform and version requirements:** JS (1.1) ``` fun getUTCSeconds(): Int ``` kotlin toTimeString toTimeString ============ [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [toTimeString](to-time-string) **Platform and version requirements:** JS (1.1) ``` fun toTimeString(): String ``` kotlin getTime getTime ======= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getTime](get-time) **Platform and version requirements:** JS (1.1) ``` fun getTime(): Double ``` kotlin toJSON toJSON ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [toJSON](to-j-s-o-n) **Platform and version requirements:** JS (1.1) ``` fun toJSON(): Json ``` kotlin getUTCDay getUTCDay ========= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getUTCDay](get-u-t-c-day) **Platform and version requirements:** JS (1.1) ``` fun getUTCDay(): Int ``` kotlin getHours getHours ======== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getHours](get-hours) **Platform and version requirements:** JS (1.1) ``` fun getHours(): Int ``` kotlin parse parse ===== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / <parse> **Platform and version requirements:** JS (1.1) ``` fun parse(dateString: String): Double ``` kotlin getSeconds getSeconds ========== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getSeconds](get-seconds) **Platform and version requirements:** JS (1.1) ``` fun getSeconds(): Int ``` kotlin getDay getDay ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getDay](get-day) **Platform and version requirements:** JS (1.1) ``` fun getDay(): Int ``` kotlin getUTCHours getUTCHours =========== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getUTCHours](get-u-t-c-hours) **Platform and version requirements:** JS (1.1) ``` fun getUTCHours(): Int ``` kotlin getTimezoneOffset getTimezoneOffset ================= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getTimezoneOffset](get-timezone-offset) **Platform and version requirements:** JS (1.1) ``` fun getTimezoneOffset(): Int ``` kotlin getMilliseconds getMilliseconds =============== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Date](index) / [getMilliseconds](get-milliseconds) **Platform and version requirements:** JS (1.1) ``` fun getMilliseconds(): Int ``` kotlin LocaleOptions LocaleOptions ============= [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) **Platform and version requirements:** JS (1.1) ``` interface LocaleOptions ``` Properties ---------- **Platform and version requirements:** JS (1.1) #### <day> ``` abstract var day: String? ``` **Platform and version requirements:** JS (1.1) #### <era> ``` abstract var era: String? ``` **Platform and version requirements:** JS (1.1) #### [formatMatcher](format-matcher) ``` abstract var formatMatcher: String? ``` **Platform and version requirements:** JS (1.1) #### <hour> ``` abstract var hour: String? ``` **Platform and version requirements:** JS (1.1) #### <hour12> ``` abstract var hour12: Boolean? ``` **Platform and version requirements:** JS (1.1) #### [localeMatcher](locale-matcher) ``` abstract var localeMatcher: String? ``` **Platform and version requirements:** JS (1.1) #### <minute> ``` abstract var minute: String? ``` **Platform and version requirements:** JS (1.1) #### <month> ``` abstract var month: String? ``` **Platform and version requirements:** JS (1.1) #### <second> ``` abstract var second: String? ``` **Platform and version requirements:** JS (1.1) #### [timeZone](time-zone) ``` abstract var timeZone: String? ``` **Platform and version requirements:** JS (1.1) #### [timeZoneName](time-zone-name) ``` abstract var timeZoneName: String? ``` **Platform and version requirements:** JS (1.1) #### <weekday> ``` abstract var weekday: String? ``` **Platform and version requirements:** JS (1.1) #### <year> ``` abstract var year: String? ```
programming_docs
kotlin minute minute ====== [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) / <minute> **Platform and version requirements:** JS (1.1) ``` abstract var minute: String? ``` kotlin era era === [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) / <era> **Platform and version requirements:** JS (1.1) ``` abstract var era: String? ``` kotlin day day === [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) / <day> **Platform and version requirements:** JS (1.1) ``` abstract var day: String? ``` kotlin formatMatcher formatMatcher ============= [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) / [formatMatcher](format-matcher) **Platform and version requirements:** JS (1.1) ``` abstract var formatMatcher: String? ``` kotlin year year ==== [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) / <year> **Platform and version requirements:** JS (1.1) ``` abstract var year: String? ``` kotlin hour12 hour12 ====== [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) / <hour12> **Platform and version requirements:** JS (1.1) ``` abstract var hour12: Boolean? ``` kotlin hour hour ==== [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) / <hour> **Platform and version requirements:** JS (1.1) ``` abstract var hour: String? ``` kotlin weekday weekday ======= [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) / <weekday> **Platform and version requirements:** JS (1.1) ``` abstract var weekday: String? ``` kotlin timeZoneName timeZoneName ============ [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) / [timeZoneName](time-zone-name) **Platform and version requirements:** JS (1.1) ``` abstract var timeZoneName: String? ``` kotlin timeZone timeZone ======== [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) / [timeZone](time-zone) **Platform and version requirements:** JS (1.1) ``` abstract var timeZone: String? ``` kotlin localeMatcher localeMatcher ============= [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) / [localeMatcher](locale-matcher) **Platform and version requirements:** JS (1.1) ``` abstract var localeMatcher: String? ``` kotlin second second ====== [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) / <second> **Platform and version requirements:** JS (1.1) ``` abstract var second: String? ``` kotlin month month ===== [kotlin-stdlib](../../../../../../../index) / [kotlin.js](../../index) / [Date](../index) / [LocaleOptions](index) / <month> **Platform and version requirements:** JS (1.1) ``` abstract var month: String? ``` kotlin RegExp RegExp ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [RegExp](index) **Platform and version requirements:** JS (1.1) ``` class RegExp ``` Exposes the JavaScript [RegExp object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp) to Kotlin. Constructors ------------ **Platform and version requirements:** JS (1.1) #### [<init>](-init-) Exposes the JavaScript [RegExp object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp) to Kotlin. ``` RegExp(pattern: String, flags: String? = definedExternally) ``` Properties ---------- **Platform and version requirements:** JS (1.1) #### <global> ``` val global: Boolean ``` **Platform and version requirements:** JS (1.1) #### [ignoreCase](ignore-case) ``` val ignoreCase: Boolean ``` **Platform and version requirements:** JS (1.1) #### [lastIndex](last-index) The lastIndex is a read/write integer property of regular expressions that specifies the index at which to start the next match. ``` var lastIndex: Int ``` **Platform and version requirements:** JS (1.1) #### <multiline> ``` val multiline: Boolean ``` Functions --------- **Platform and version requirements:** JS (1.1) #### <exec> ``` fun exec(str: String): RegExpMatch? ``` **Platform and version requirements:** JS (1.1) #### <test> ``` fun test(str: String): Boolean ``` **Platform and version requirements:** JS (1.1) #### [toString](to-string) ``` fun toString(): String ``` Extension Functions ------------------- **Platform and version requirements:** JS (1.1) #### [reset](../reset) Resets the regular expression so that subsequent [RegExp.test](test) and [RegExp.exec](exec) calls will match starting with the beginning of the input string. ``` fun RegExp.reset() ``` kotlin global global ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [RegExp](index) / <global> **Platform and version requirements:** JS (1.1) ``` val global: Boolean ``` kotlin multiline multiline ========= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [RegExp](index) / <multiline> **Platform and version requirements:** JS (1.1) ``` val multiline: Boolean ``` kotlin test test ==== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [RegExp](index) / <test> **Platform and version requirements:** JS (1.1) ``` fun test(str: String): Boolean ``` kotlin toString toString ======== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [RegExp](index) / [toString](to-string) **Platform and version requirements:** JS (1.1) ``` fun toString(): String ``` kotlin lastIndex lastIndex ========= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [RegExp](index) / [lastIndex](last-index) **Platform and version requirements:** JS (1.1) ``` var lastIndex: Int ``` The lastIndex is a read/write integer property of regular expressions that specifies the index at which to start the next match. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [RegExp](index) / [<init>](-init-) **Platform and version requirements:** JS (1.1) ``` RegExp(pattern: String, flags: String? = definedExternally) ``` Exposes the JavaScript [RegExp object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp) to Kotlin. kotlin exec exec ==== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [RegExp](index) / <exec> **Platform and version requirements:** JS (1.1) ``` fun exec(str: String): RegExpMatch? ``` kotlin ignoreCase ignoreCase ========== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [RegExp](index) / [ignoreCase](ignore-case) **Platform and version requirements:** JS (1.1) ``` val ignoreCase: Boolean ``` kotlin JsQualifier JsQualifier =========== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsQualifier](index) **Platform and version requirements:** JS (1.1) ``` @Target([AnnotationTarget.FILE]) annotation class JsQualifier ``` Adds prefix to `external` declarations in a source file. JavaScript does not have concept of packages (namespaces). They are usually emulated by nested objects. The compiler turns references to `external` declarations either to plain unprefixed names (in case of *plain* modules) or to plain imports. However, if a JavaScript library provides its declarations in packages, you won't be satisfied with this. You can tell the compiler to generate additional prefix before references to `external` declarations using the `@JsQualifier(...)` annotation. Note that a file marked with the `@JsQualifier(...)` annotation can't contain non-`external` declarations. Example: ``` @file:JsQualifier("my.jsPackageName") package some.kotlinPackage external fun foo(x: Int) external fun bar(): String ``` Constructors ------------ **Platform and version requirements:** JS (1.1) #### [<init>](-init-) Adds prefix to `external` declarations in a source file. ``` JsQualifier(value: String) ``` Properties ---------- **Platform and version requirements:** JS (1.1) #### <value> the qualifier to add to the declarations in the generated code. It must be a sequence of valid JavaScript identifiers separated by the `.` character. Examples of valid qualifiers are: `foo`, `bar.Baz`, `_.$0.f`. ``` val value: String ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsQualifier](index) / [<init>](-init-) **Platform and version requirements:** JS (1.1) ``` JsQualifier(value: String) ``` Adds prefix to `external` declarations in a source file. JavaScript does not have concept of packages (namespaces). They are usually emulated by nested objects. The compiler turns references to `external` declarations either to plain unprefixed names (in case of *plain* modules) or to plain imports. However, if a JavaScript library provides its declarations in packages, you won't be satisfied with this. You can tell the compiler to generate additional prefix before references to `external` declarations using the `@JsQualifier(...)` annotation. Note that a file marked with the `@JsQualifier(...)` annotation can't contain non-`external` declarations. Example: ``` @file:JsQualifier("my.jsPackageName") package some.kotlinPackage external fun foo(x: Int) external fun bar(): String ``` kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsQualifier](index) / <value> **Platform and version requirements:** JS (1.1) ``` val value: String ``` the qualifier to add to the declarations in the generated code. It must be a sequence of valid JavaScript identifiers separated by the `.` character. Examples of valid qualifiers are: `foo`, `bar.Baz`, `_.$0.f`. Property -------- `value` - the qualifier to add to the declarations in the generated code. It must be a sequence of valid JavaScript identifiers separated by the `.` character. Examples of valid qualifiers are: `foo`, `bar.Baz`, `_.$0.f`. **See Also** [JsModule](../-js-module/index) kotlin all all === [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Promise](index) / <all> **Platform and version requirements:** JS (1.1) ``` fun <S> all(     promise: Array<out Promise<S>> ): Promise<Array<out S>> ``` kotlin Promise Promise ======= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Promise](index) **Platform and version requirements:** JS (1.1) ``` open class Promise<out T> ``` Exposes the JavaScript [Promise object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) to Kotlin. Constructors ------------ **Platform and version requirements:** JS (1.1) #### [<init>](-init-) Exposes the JavaScript [Promise object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) to Kotlin. ``` Promise(     executor: (resolve: (T) -> Unit, reject: (Throwable) -> Unit) -> Unit) ``` Functions --------- **Platform and version requirements:** JS (1.1) #### <catch> ``` open fun <S> catch(onRejected: (Throwable) -> S): Promise<S> ``` **Platform and version requirements:** JS (1.1) #### <finally> ``` open fun finally(onFinally: () -> Unit): Promise<T> ``` **Platform and version requirements:** JS (1.1) #### <then> ``` open fun <S> then(onFulfilled: ((T) -> S)?): Promise<S> ``` ``` open fun <S> then(     onFulfilled: ((T) -> S)?,     onRejected: ((Throwable) -> S)? ): Promise<S> ``` Companion Object Functions -------------------------- **Platform and version requirements:** JS (1.1) #### <all> ``` fun <S> all(     promise: Array<out Promise<S>> ): Promise<Array<out S>> ``` **Platform and version requirements:** JS (1.1) #### <race> ``` fun <S> race(promise: Array<out Promise<S>>): Promise<S> ``` **Platform and version requirements:** JS (1.1) #### <reject> ``` fun reject(e: Throwable): Promise<Nothing> ``` **Platform and version requirements:** JS (1.1) #### <resolve> ``` fun <S> resolve(e: S): Promise<S> ``` ``` fun <S> resolve(e: Promise<S>): Promise<S> ``` Extension Functions ------------------- **Platform and version requirements:** JS (1.1) #### [then](../then) ``` fun <T, S> Promise<Promise<T>>.then(     onFulfilled: ((T) -> S)? ): Promise<S> ``` ``` fun <T, S> Promise<Promise<T>>.then(     onFulfilled: ((T) -> S)?,     onRejected: ((Throwable) -> S)? ): Promise<S> ``` kotlin finally finally ======= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Promise](index) / <finally> **Platform and version requirements:** JS (1.1) ``` open fun finally(onFinally: () -> Unit): Promise<T> ``` kotlin race race ==== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Promise](index) / <race> **Platform and version requirements:** JS (1.1) ``` fun <S> race(promise: Array<out Promise<S>>): Promise<S> ``` kotlin then then ==== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Promise](index) / <then> **Platform and version requirements:** JS (1.1) ``` open fun <S> then(onFulfilled: ((T) -> S)?): Promise<S> ``` ``` open fun <S> then(     onFulfilled: ((T) -> S)?,     onRejected: ((Throwable) -> S)? ): Promise<S> ``` kotlin catch catch ===== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Promise](index) / <catch> **Platform and version requirements:** JS (1.1) ``` open fun <S> catch(onRejected: (Throwable) -> S): Promise<S> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Promise](index) / [<init>](-init-) **Platform and version requirements:** JS (1.1) ``` Promise(     executor: (resolve: (T) -> Unit, reject: (Throwable) -> Unit) -> Unit) ``` Exposes the JavaScript [Promise object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) to Kotlin. kotlin reject reject ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Promise](index) / <reject> **Platform and version requirements:** JS (1.1) ``` fun reject(e: Throwable): Promise<Nothing> ``` kotlin resolve resolve ======= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Promise](index) / <resolve> **Platform and version requirements:** JS (1.1) ``` fun <S> resolve(e: S): Promise<S> ``` ``` fun <S> resolve(e: Promise<S>): Promise<S> ``` kotlin JsClass JsClass ======= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsClass](index) **Platform and version requirements:** JS (1.1) ``` interface JsClass<T : Any> ``` Represents the constructor of a class. Instances of `JsClass` can be passed to JavaScript APIs that expect a constructor reference. Properties ---------- **Platform and version requirements:** JS (1.1) #### <name> Returns the unqualified name of the class represented by this instance. ``` abstract val name: String ``` Extension Properties -------------------- **Platform and version requirements:** JS (1.1) #### [kotlin](../kotlin) Obtains a `KClass` instance for the given constructor reference. ``` val <T : Any> JsClass<T>.kotlin: KClass<T> ``` kotlin name name ==== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsClass](index) / <name> **Platform and version requirements:** JS (1.1) ``` abstract val name: String ``` Returns the unqualified name of the class represented by this instance. kotlin JsNonModule JsNonModule =========== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsNonModule](index) **Platform and version requirements:** JS (1.1) ``` @Target([AnnotationTarget.CLASS, AnnotationTarget.PROPERTY, AnnotationTarget.FUNCTION, AnnotationTarget.FILE]) annotation class JsNonModule ``` Denotes an `external` declaration that can be used without module system. By default, an `external` declaration is available regardless your target module system. However, by applying [JsModule](../-js-module/index) annotation you can make a declaration unavailable to *plain* module system. Some JavaScript libraries are distributed both as a standalone downloadable piece of JavaScript and as a module available as an npm package. To tell the Kotlin compiler to accept both cases, you can augment [JsModule](../-js-module/index) with the `@JsNonModule` annotation. For example: ``` @JsModule("jquery") @JsNonModule @JsName("$") external abstract class JQuery() { // some declarations here } @JsModule("jquery") @JsNonModule @JsName("$") external fun JQuery(element: Element): JQuery ``` **See Also** [JsModule](../-js-module/index) Constructors ------------ **Platform and version requirements:** JS (1.1) #### [<init>](-init-) Denotes an `external` declaration that can be used without module system. ``` JsNonModule() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsNonModule](index) / [<init>](-init-) **Platform and version requirements:** JS (1.1) ``` JsNonModule() ``` Denotes an `external` declaration that can be used without module system. By default, an `external` declaration is available regardless your target module system. However, by applying [JsModule](../-js-module/index) annotation you can make a declaration unavailable to *plain* module system. Some JavaScript libraries are distributed both as a standalone downloadable piece of JavaScript and as a module available as an npm package. To tell the Kotlin compiler to accept both cases, you can augment [JsModule](../-js-module/index) with the `@JsNonModule` annotation. For example: ``` @JsModule("jquery") @JsNonModule @JsName("$") external abstract class JQuery() { // some declarations here } @JsModule("jquery") @JsNonModule @JsName("$") external fun JQuery(element: Element): JQuery ``` **See Also** [JsModule](../-js-module/index) kotlin ExperimentalJsExport ExperimentalJsExport ==================== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [ExperimentalJsExport](index) **Platform and version requirements:** JVM (1.4), JS (1.4), Native (1.4) ``` annotation class ExperimentalJsExport ``` Marks experimental JS export annotations. Note that behavior of these annotations will likely be changed in the future. Usages of such annotations will be reported as warnings unless an explicit opt-in with the [OptIn](../../kotlin/-opt-in/index) annotation, e.g. `@OptIn(ExperimentalJsExport::class)`, or with the `-opt-in=kotlin.js.ExperimentalJsExport` compiler option is given. Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [<init>](-init-) Marks experimental JS export annotations. ``` ExperimentalJsExport() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [ExperimentalJsExport](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` ExperimentalJsExport() ``` Marks experimental JS export annotations. Note that behavior of these annotations will likely be changed in the future. Usages of such annotations will be reported as warnings unless an explicit opt-in with the [OptIn](../../kotlin/-opt-in/index) annotation, e.g. `@OptIn(ExperimentalJsExport::class)`, or with the `-opt-in=kotlin.js.ExperimentalJsExport` compiler option is given.
programming_docs
kotlin warn warn ==== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Console](index) / <warn> **Platform and version requirements:** JS (1.1) ``` abstract fun warn(vararg o: Any?) ``` kotlin Console Console ======= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Console](index) **Platform and version requirements:** JS (1.1) ``` interface Console ``` Exposes the [console API](https://developer.mozilla.org/en/DOM/console) to Kotlin. Functions --------- **Platform and version requirements:** JS (1.1) #### <dir> ``` abstract fun dir(o: Any) ``` **Platform and version requirements:** JS (1.1) #### <error> ``` abstract fun error(vararg o: Any?) ``` **Platform and version requirements:** JS (1.1) #### <info> ``` abstract fun info(vararg o: Any?) ``` **Platform and version requirements:** JS (1.1) #### <log> ``` abstract fun log(vararg o: Any?) ``` **Platform and version requirements:** JS (1.1) #### <warn> ``` abstract fun warn(vararg o: Any?) ``` kotlin info info ==== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Console](index) / <info> **Platform and version requirements:** JS (1.1) ``` abstract fun info(vararg o: Any?) ``` kotlin log log === [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Console](index) / <log> **Platform and version requirements:** JS (1.1) ``` abstract fun log(vararg o: Any?) ``` kotlin error error ===== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Console](index) / <error> **Platform and version requirements:** JS (1.1) ``` abstract fun error(vararg o: Any?) ``` kotlin dir dir === [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Console](index) / <dir> **Platform and version requirements:** JS (1.1) ``` abstract fun dir(o: Any) ``` kotlin JsExport JsExport ======== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsExport](index) **Platform and version requirements:** JS (1.3) ``` @ExperimentalJsExport @Target([AnnotationTarget.CLASS, AnnotationTarget.PROPERTY, AnnotationTarget.FUNCTION, AnnotationTarget.FILE]) annotation class JsExport ``` Exports top-level declaration on JS platform. Compiled module exposes declarations that are marked with this annotation without name mangling. This annotation can be applied to either files or top-level declarations. It is currently prohibited to export the following kinds of declarations: * `expect` declarations * inline functions with reified type parameters * suspend functions * secondary constructors without `@JsName` * extension properties * enum classes * annotation classes Signatures of exported declarations must only contain "exportable" types: * `dynamic`, `Any`, `String`, `Boolean`, `Byte`, `Short`, `Int`, `Float`, `Double` * `BooleanArray`, `ByteArray`, `ShortArray`, `IntArray`, `FloatArray`, `DoubleArray` * `Array<exportable-type>` * Function types with exportable parameters and return types * `external` or `@JsExport` classes and interfaces * Nullable counterparts of types above * Unit return type. Must not be nullable This annotation is experimental, meaning that restrictions mentioned above are subject to change. Constructors ------------ **Platform and version requirements:** JS (1.0) #### [<init>](-init-) Exports top-level declaration on JS platform. ``` <init>() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsExport](index) / [<init>](-init-) **Platform and version requirements:** JS (1.1) ``` <init>() ``` Exports top-level declaration on JS platform. Compiled module exposes declarations that are marked with this annotation without name mangling. This annotation can be applied to either files or top-level declarations. It is currently prohibited to export the following kinds of declarations: * `expect` declarations * inline functions with reified type parameters * suspend functions * secondary constructors without `@JsName` * extension properties * enum classes * annotation classes Signatures of exported declarations must only contain "exportable" types: * `dynamic`, `Any`, `String`, `Boolean`, `Byte`, `Short`, `Int`, `Float`, `Double` * `BooleanArray`, `ByteArray`, `ShortArray`, `IntArray`, `FloatArray`, `DoubleArray` * `Array<exportable-type>` * Function types with exportable parameters and return types * `external` or `@JsExport` classes and interfaces * Nullable counterparts of types above * Unit return type. Must not be nullable This annotation is experimental, meaning that restrictions mentioned above are subject to change. kotlin EagerInitialization EagerInitialization =================== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [EagerInitialization](index) **Platform and version requirements:** JS (1.6) ``` @ExperimentalStdlibApi @Target([AnnotationTarget.PROPERTY]) annotation class EagerInitialization ``` **Deprecated:** This annotation is a temporal migration assistance and may be removed in the future releases, please consider filing an issue about the case where it is needed Forces a top-level property to be initialized eagerly, opposed to lazily on the first access to file and/or property. Constructors ------------ **Platform and version requirements:** JS (1.1) #### [<init>](-init-) Forces a top-level property to be initialized eagerly, opposed to lazily on the first access to file and/or property. ``` EagerInitialization() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [EagerInitialization](index) / [<init>](-init-) **Platform and version requirements:** JS (1.1) ``` EagerInitialization() ``` Forces a top-level property to be initialized eagerly, opposed to lazily on the first access to file and/or property. kotlin JsName JsName ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsName](index) **Platform and version requirements:** JS (1.1) ``` @Target([AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY, AnnotationTarget.CONSTRUCTOR, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER]) annotation class JsName ``` ##### For Common Gives a declaration (a function, a property or a class) specific name in JavaScript. ##### For JS Gives a declaration (a function, a property or a class) specific name in JavaScript. This may be useful in the following cases: * There are two functions for which the compiler gives same name in JavaScript, you can mark one with `@JsName(...)` to prevent the compiler from reporting error. * You are writing a JavaScript library in Kotlin. The compiler produces mangled names for functions with parameters, which is unnatural for usual JavaScript developer. You can put `@JsName(...)` on functions you want to be available from JavaScript. * For some reason you want to rename declaration, e.g. there's common term in JavaScript for a concept provided by the declaration, which in uncommon in Kotlin. Example: ``` class Person(val name: String) { fun hello() { println("Hello $name!") } @JsName("helloWithGreeting") fun hello(greeting: String) { println("$greeting $name!") } } ``` Constructors ------------ **Platform and version requirements:** JS (1.0) #### [<init>](-init-) Gives a declaration (a function, a property or a class) specific name in JavaScript. ``` <init>(name: String) ``` Properties ---------- **Platform and version requirements:** JS (1.0) #### <name> the name which compiler uses both for declaration itself and for all references to the declaration. It's required to denote a valid JavaScript identifier. ``` val name: String ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsName](index) / [<init>](-init-) **Platform and version requirements:** JS (1.1) ``` <init>(name: String) ``` ##### For Common Gives a declaration (a function, a property or a class) specific name in JavaScript. ##### For JS Gives a declaration (a function, a property or a class) specific name in JavaScript. This may be useful in the following cases: * There are two functions for which the compiler gives same name in JavaScript, you can mark one with `@JsName(...)` to prevent the compiler from reporting error. * You are writing a JavaScript library in Kotlin. The compiler produces mangled names for functions with parameters, which is unnatural for usual JavaScript developer. You can put `@JsName(...)` on functions you want to be available from JavaScript. * For some reason you want to rename declaration, e.g. there's common term in JavaScript for a concept provided by the declaration, which in uncommon in Kotlin. Example: ``` class Person(val name: String) { fun hello() { println("Hello $name!") } @JsName("helloWithGreeting") fun hello(greeting: String) { println("$greeting $name!") } } ``` kotlin name name ==== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsName](index) / <name> **Platform and version requirements:** JS (1.1) ``` val name: String ``` the name which compiler uses both for declaration itself and for all references to the declaration. It's required to denote a valid JavaScript identifier. Property -------- `name` - the name which compiler uses both for declaration itself and for all references to the declaration. It's required to denote a valid JavaScript identifier. kotlin RegExpMatch RegExpMatch =========== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [RegExpMatch](index) **Platform and version requirements:** JS (1.1) ``` interface RegExpMatch ``` Represents the return value of [RegExp.exec](../-reg-exp/exec). Properties ---------- **Platform and version requirements:** JS (1.1) #### [index](--index--) ``` abstract val index: Int ``` **Platform and version requirements:** JS (1.1) #### <input> ``` abstract val input: String ``` **Platform and version requirements:** JS (1.1) #### <length> ``` abstract val length: Int ``` Extension Functions ------------------- **Platform and version requirements:** JS (1.1) #### [asArray](../as-array) Converts the result of [RegExp.exec](../-reg-exp/exec) to an array where the first element contains the entire matched text and each subsequent element is the text matched by each capturing parenthesis. ``` fun RegExpMatch.asArray(): Array<out String?> ``` **Platform and version requirements:** JS (1.1) #### [get](../get) Returns the entire text matched by [RegExp.exec](../-reg-exp/exec) if the [index](../get#kotlin.js%24get(kotlin.js.RegExpMatch,%20kotlin.Int)/index) parameter is 0, or the text matched by the capturing parenthesis at the given index. ``` operator fun RegExpMatch.get(index: Int): String? ``` kotlin length length ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [RegExpMatch](index) / <length> **Platform and version requirements:** JS (1.1) ``` abstract val length: Int ``` kotlin index index ===== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [RegExpMatch](index) / [index](--index--) **Platform and version requirements:** JS (1.1) ``` abstract val index: Int ``` kotlin input input ===== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [RegExpMatch](index) / <input> **Platform and version requirements:** JS (1.1) ``` abstract val input: String ``` kotlin nativeInvoke nativeInvoke ============ [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [nativeInvoke](index) **Platform and version requirements:** JS (1.1) ``` @Target([AnnotationTarget.FUNCTION]) annotation class nativeInvoke ``` **Deprecated:** Use inline extension function with body using dynamic Constructors ------------ **Platform and version requirements:** JS (1.1) #### [<init>](-init-) ``` nativeInvoke() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [nativeInvoke](index) / [<init>](-init-) **Platform and version requirements:** JS (1.1) ``` nativeInvoke() ``` kotlin nativeSetter nativeSetter ============ [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [nativeSetter](index) **Platform and version requirements:** JS (1.1) ``` @Target([AnnotationTarget.FUNCTION]) annotation class nativeSetter ``` **Deprecated:** Use inline extension function with body using dynamic Constructors ------------ **Platform and version requirements:** JS (1.1) #### [<init>](-init-) ``` nativeSetter() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [nativeSetter](index) / [<init>](-init-) **Platform and version requirements:** JS (1.1) ``` nativeSetter() ``` kotlin nativeGetter nativeGetter ============ [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [nativeGetter](index) **Platform and version requirements:** JS (1.1) ``` @Target([AnnotationTarget.FUNCTION]) annotation class nativeGetter ``` **Deprecated:** Use inline extension function with body using dynamic Constructors ------------ **Platform and version requirements:** JS (1.1) #### [<init>](-init-) ``` nativeGetter() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [nativeGetter](index) / [<init>](-init-) **Platform and version requirements:** JS (1.1) ``` nativeGetter() ``` kotlin JSON JSON ==== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JSON](index) **Platform and version requirements:** JS (1.1) ``` object JSON ``` Exposes the JavaScript [JSON object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) to Kotlin. Functions --------- **Platform and version requirements:** JS (1.1) #### <parse> ``` fun <T> parse(text: String): T ``` ``` fun <T> parse(     text: String,     reviver: (key: String, value: Any?) -> Any? ): T ``` **Platform and version requirements:** JS (1.1) #### <stringify> ``` fun stringify(o: Any?): String ``` ``` fun stringify(     o: Any?,     replacer: (key: String, value: Any?) -> Any? ): String ``` ``` fun stringify(     o: Any?,     replacer: ((key: String, value: Any?) -> Any?)? = definedExternally,     space: Int ): String ``` ``` fun stringify(     o: Any?,     replacer: ((key: String, value: Any?) -> Any?)? = definedExternally,     space: String ): String ``` ``` fun stringify(o: Any?, replacer: Array<String>): String ``` ``` fun stringify(     o: Any?,     replacer: Array<String>,     space: Int ): String ``` ``` fun stringify(     o: Any?,     replacer: Array<String>,     space: String ): String ``` kotlin stringify stringify ========= [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JSON](index) / <stringify> **Platform and version requirements:** JS (1.1) ``` fun stringify(o: Any?): String ``` ``` fun stringify(     o: Any?,     replacer: (key: String, value: Any?) -> Any? ): String ``` ``` fun stringify(     o: Any?,     replacer: ((key: String, value: Any?) -> Any?)? = definedExternally,     space: Int ): String ``` ``` fun stringify(     o: Any?,     replacer: ((key: String, value: Any?) -> Any?)? = definedExternally,     space: String ): String ``` ``` fun stringify(o: Any?, replacer: Array<String>): String ``` ``` fun stringify(     o: Any?,     replacer: Array<String>,     space: Int ): String ``` ``` fun stringify(     o: Any?,     replacer: Array<String>,     space: String ): String ``` kotlin parse parse ===== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JSON](index) / <parse> **Platform and version requirements:** JS (1.1) ``` fun <T> parse(text: String): T ``` ``` fun <T> parse(     text: String,     reviver: (key: String, value: Any?) -> Any? ): T ``` kotlin Json Json ==== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Json](index) **Platform and version requirements:** JS (1.1) ``` interface Json ``` An interface for indexing access to a collection of key-value pairs, where type of key is String and type of value is Any?. Functions --------- **Platform and version requirements:** JS (1.1) #### <get> Calls to the function will be translated to indexing operation (square brackets) on the receiver with [propertyName](get#kotlin.js.Json%24get(kotlin.String)/propertyName) as the argument. ``` abstract operator fun get(propertyName: String): Any? ``` **Platform and version requirements:** JS (1.1) #### <set> Calls of the function will be translated to an assignment of [value](set#kotlin.js.Json%24set(kotlin.String,%20kotlin.Any?)/value) to the receiver indexed (with square brackets/index operation) with [propertyName](set#kotlin.js.Json%24set(kotlin.String,%20kotlin.Any?)/propertyName). ``` abstract operator fun set(propertyName: String, value: Any?) ``` Extension Functions ------------------- **Platform and version requirements:** JS (1.1) #### [add](../add) Adds key-value pairs from [other](../add#kotlin.js%24add(kotlin.js.Json,%20kotlin.js.Json)/other) to [this](../add/-this-). Returns the original receiver. ``` fun Json.add(other: Json): Json ``` kotlin set set === [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Json](index) / <set> **Platform and version requirements:** JS (1.1) ``` abstract operator fun set(propertyName: String, value: Any?) ``` Calls of the function will be translated to an assignment of [value](set#kotlin.js.Json%24set(kotlin.String,%20kotlin.Any?)/value) to the receiver indexed (with square brackets/index operation) with [propertyName](set#kotlin.js.Json%24set(kotlin.String,%20kotlin.Any?)/propertyName). E.g. for the following code: ``` fun test(j: Json, p: String, newValue: Any) { j["prop"] = 1 j.set(p, newValue) } ``` will be generated: ``` function test(j, p, newValue) { j["prop"] = 1; j[p] = newValue; } } ``` kotlin get get === [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [Json](index) / <get> **Platform and version requirements:** JS (1.1) ``` abstract operator fun get(propertyName: String): Any? ``` Calls to the function will be translated to indexing operation (square brackets) on the receiver with [propertyName](get#kotlin.js.Json%24get(kotlin.String)/propertyName) as the argument. E.g. for next code: ``` fun test(j: Json, p: String) = j["prop"] + j.get(p) ``` will be generated: ``` function test(j, p) { return j["prop"] + j[p]; } ``` kotlin JsModule JsModule ======== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsModule](index) **Platform and version requirements:** JS (1.1) ``` @Target([AnnotationTarget.CLASS, AnnotationTarget.PROPERTY, AnnotationTarget.FUNCTION, AnnotationTarget.FILE]) annotation class JsModule ``` Denotes an `external` declaration that must be imported from native JavaScript library. The compiler produces the code relevant for the target module system, for example, in case of CommonJS, it will import the declaration via the `require(...)` function. The annotation can be used on top-level external declarations (classes, properties, functions) and files. In case of file (which can't be `external`) the following rule applies: all the declarations in the file must be `external`. By applying `@JsModule(...)` on a file you tell the compiler to import a JavaScript object that contain all the declarations from the file. Example: ``` @JsModule("jquery") external abstract class JQuery() { // some declarations here } @JsModule("jquery") external fun JQuery(element: Element): JQuery ``` Constructors ------------ **Platform and version requirements:** JS (1.1) #### [<init>](-init-) Denotes an `external` declaration that must be imported from native JavaScript library. ``` JsModule(import: String) ``` Properties ---------- **Platform and version requirements:** JS (1.1) #### <import> name of a module to import declaration from. It is not interpreted by the Kotlin compiler, it's passed as is directly to the target module system. ``` val import: String ```
programming_docs
kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsModule](index) / [<init>](-init-) **Platform and version requirements:** JS (1.1) ``` JsModule(import: String) ``` Denotes an `external` declaration that must be imported from native JavaScript library. The compiler produces the code relevant for the target module system, for example, in case of CommonJS, it will import the declaration via the `require(...)` function. The annotation can be used on top-level external declarations (classes, properties, functions) and files. In case of file (which can't be `external`) the following rule applies: all the declarations in the file must be `external`. By applying `@JsModule(...)` on a file you tell the compiler to import a JavaScript object that contain all the declarations from the file. Example: ``` @JsModule("jquery") external abstract class JQuery() { // some declarations here } @JsModule("jquery") external fun JQuery(element: Element): JQuery ``` kotlin import import ====== [kotlin-stdlib](../../../../../../index) / [kotlin.js](../index) / [JsModule](index) / <import> **Platform and version requirements:** JS (1.1) ``` val import: String ``` name of a module to import declaration from. It is not interpreted by the Kotlin compiler, it's passed as is directly to the target module system. Property -------- `import` - name of a module to import declaration from. It is not interpreted by the Kotlin compiler, it's passed as is directly to the target module system. **See Also** [JsNonModule](../-js-non-module/index) kotlin localStorage localStorage ============ [kotlin-stdlib](../../../../../index) / [kotlinx.browser](index) / [localStorage](local-storage) **Platform and version requirements:** JS (1.4) ``` val localStorage: Storage ``` kotlin window window ====== [kotlin-stdlib](../../../../../index) / [kotlinx.browser](index) / <window> **Platform and version requirements:** JS (1.4) ``` val window: Window ``` kotlin Package kotlinx.browser Package kotlinx.browser ======================= [kotlin-stdlib](../../../../../index) / [kotlinx.browser](index) Properties ---------- **Platform and version requirements:** JS (1.4) #### <document> ``` val document: Document ``` **Platform and version requirements:** JS (1.4) #### [localStorage](local-storage) ``` val localStorage: Storage ``` **Platform and version requirements:** JS (1.4) #### [sessionStorage](session-storage) ``` val sessionStorage: Storage ``` **Platform and version requirements:** JS (1.4) #### <window> ``` val window: Window ``` kotlin sessionStorage sessionStorage ============== [kotlin-stdlib](../../../../../index) / [kotlinx.browser](index) / [sessionStorage](session-storage) **Platform and version requirements:** JS (1.4) ``` val sessionStorage: Storage ``` kotlin document document ======== [kotlin-stdlib](../../../../../index) / [kotlinx.browser](index) / <document> **Platform and version requirements:** JS (1.4) ``` val document: Document ``` kotlin isText isText ====== [kotlin-stdlib](../../../../../index) / [kotlinx.dom](index) / [isText](is-text) **Platform and version requirements:** JS (1.4) ``` val Node.isText: Boolean ``` Gets a value indicating whether this node is a TEXT\_NODE or a CDATA\_SECTION\_NODE. kotlin Package kotlinx.dom Package kotlinx.dom =================== [kotlin-stdlib](../../../../../index) / [kotlinx.dom](index) Properties ---------- **Platform and version requirements:** JS (1.4) #### [isElement](is-element) Gets a value indicating whether this node is an [Element](https://kotlinlang.org/api/latest/jvm/stdlib/org.w3c.dom/-element/index.html). ``` val Node.isElement: Boolean ``` **Platform and version requirements:** JS (1.4) #### [isText](is-text) Gets a value indicating whether this node is a TEXT\_NODE or a CDATA\_SECTION\_NODE. ``` val Node.isText: Boolean ``` Functions --------- **Platform and version requirements:** JS (1.4) #### [addClass](add-class) Adds CSS class to element. Has no effect if all specified classes are already in class attribute of the element ``` fun Element.addClass(vararg cssClasses: String): Boolean ``` **Platform and version requirements:** JS (1.4) #### [appendElement](append-element) Appends a newly created element with the specified [name](append-element#kotlinx.dom%24appendElement(org.w3c.dom.Element,%20kotlin.String,%20kotlin.Function1((org.w3c.dom.Element,%20kotlin.Unit)))/name) to this element. ``` fun Element.appendElement(     name: String,     init: Element.() -> Unit ): Element ``` **Platform and version requirements:** JS (1.4) #### [appendText](append-text) Creates text node and append it to the element. ``` fun Element.appendText(text: String): Element ``` **Platform and version requirements:** JS (1.4) #### <clear> Removes all the children from this node. ``` fun Node.clear() ``` **Platform and version requirements:** JS (1.4) #### [createElement](create-element) Creates a new element with the specified [name](create-element#kotlinx.dom%24createElement(org.w3c.dom.Document,%20kotlin.String,%20kotlin.Function1((org.w3c.dom.Element,%20kotlin.Unit)))/name). ``` fun Document.createElement(     name: String,     init: Element.() -> Unit ): Element ``` **Platform and version requirements:** JS (1.4) #### [hasClass](has-class) Returns true if the element has the given CSS class style in its 'class' attribute ``` fun Element.hasClass(cssClass: String): Boolean ``` **Platform and version requirements:** JS (1.4) #### [removeClass](remove-class) Removes all [cssClasses](remove-class#kotlinx.dom%24removeClass(org.w3c.dom.Element,%20kotlin.Array((kotlin.String)))/cssClasses) from element. Has no effect if all specified classes are missing in class attribute of the element ``` fun Element.removeClass(vararg cssClasses: String): Boolean ``` kotlin appendText appendText ========== [kotlin-stdlib](../../../../../index) / [kotlinx.dom](index) / [appendText](append-text) **Platform and version requirements:** JS (1.4) ``` fun Element.appendText(text: String): Element ``` Creates text node and append it to the element. **Return** this element kotlin removeClass removeClass =========== [kotlin-stdlib](../../../../../index) / [kotlinx.dom](index) / [removeClass](remove-class) **Platform and version requirements:** JS (1.4) ``` fun Element.removeClass(vararg cssClasses: String): Boolean ``` Removes all [cssClasses](remove-class#kotlinx.dom%24removeClass(org.w3c.dom.Element,%20kotlin.Array((kotlin.String)))/cssClasses) from element. Has no effect if all specified classes are missing in class attribute of the element **Return** true if at least one class has been removed kotlin hasClass hasClass ======== [kotlin-stdlib](../../../../../index) / [kotlinx.dom](index) / [hasClass](has-class) **Platform and version requirements:** JS (1.4) ``` fun Element.hasClass(cssClass: String): Boolean ``` Returns true if the element has the given CSS class style in its 'class' attribute kotlin clear clear ===== [kotlin-stdlib](../../../../../index) / [kotlinx.dom](index) / <clear> **Platform and version requirements:** JS (1.4) ``` fun Node.clear() ``` Removes all the children from this node. kotlin addClass addClass ======== [kotlin-stdlib](../../../../../index) / [kotlinx.dom](index) / [addClass](add-class) **Platform and version requirements:** JS (1.4) ``` fun Element.addClass(vararg cssClasses: String): Boolean ``` Adds CSS class to element. Has no effect if all specified classes are already in class attribute of the element **Return** true if at least one class has been added kotlin isElement isElement ========= [kotlin-stdlib](../../../../../index) / [kotlinx.dom](index) / [isElement](is-element) **Platform and version requirements:** JS (1.4) ``` val Node.isElement: Boolean ``` Gets a value indicating whether this node is an [Element](https://kotlinlang.org/api/latest/jvm/stdlib/org.w3c.dom/-element/index.html). kotlin createElement createElement ============= [kotlin-stdlib](../../../../../index) / [kotlinx.dom](index) / [createElement](create-element) **Platform and version requirements:** JS (1.4) ``` fun Document.createElement(     name: String,     init: Element.() -> Unit ): Element ``` Creates a new element with the specified [name](create-element#kotlinx.dom%24createElement(org.w3c.dom.Document,%20kotlin.String,%20kotlin.Function1((org.w3c.dom.Element,%20kotlin.Unit)))/name). The element is initialized with the specified [init](create-element#kotlinx.dom%24createElement(org.w3c.dom.Document,%20kotlin.String,%20kotlin.Function1((org.w3c.dom.Element,%20kotlin.Unit)))/init) function. kotlin appendElement appendElement ============= [kotlin-stdlib](../../../../../index) / [kotlinx.dom](index) / [appendElement](append-element) **Platform and version requirements:** JS (1.4) ``` fun Element.appendElement(     name: String,     init: Element.() -> Unit ): Element ``` Appends a newly created element with the specified [name](append-element#kotlinx.dom%24appendElement(org.w3c.dom.Element,%20kotlin.String,%20kotlin.Function1((org.w3c.dom.Element,%20kotlin.Unit)))/name) to this element. The element is initialized with the specified [init](append-element#kotlinx.dom%24appendElement(org.w3c.dom.Element,%20kotlin.String,%20kotlin.Function1((org.w3c.dom.Element,%20kotlin.Unit)))/init) function. kotlin Package kotlin.experimental Package kotlin.experimental =========================== [kotlin-stdlib](../../../../../index) / [kotlin.experimental](index) Experimental APIs, subject to change in future versions of Kotlin. Annotations ----------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [ExperimentalObjCName](-experimental-obj-c-name/index) This annotation marks the experimental [ObjCName](../kotlin.native/-obj-c-name/index#kotlin.native.ObjCName) annotation. ``` annotation class ExperimentalObjCName ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [ExperimentalObjCRefinement](-experimental-obj-c-refinement/index) This annotation marks the experimental Objective-C export refinement annotations. ``` annotation class ExperimentalObjCRefinement ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [ExperimentalTypeInference](-experimental-type-inference/index) The experimental marker for type inference augmenting annotations. ``` annotation class ExperimentalTypeInference ``` Functions --------- **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) #### <and> Performs a bitwise AND operation between the two values. ``` infix fun Byte.and(other: Byte): Byte ``` ``` infix fun Short.and(other: Short): Short ``` **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) #### <inv> Inverts the bits in this value. ``` fun Byte.inv(): Byte ``` ``` fun Short.inv(): Short ``` **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) #### <or> Performs a bitwise OR operation between the two values. ``` infix fun Byte.or(other: Byte): Byte ``` ``` infix fun Short.or(other: Short): Short ``` **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) #### <xor> Performs a bitwise XOR operation between the two values. ``` infix fun Byte.xor(other: Byte): Byte ``` ``` infix fun Short.xor(other: Short): Short ``` kotlin and and === [kotlin-stdlib](../../../../../index) / [kotlin.experimental](index) / <and> **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) ``` infix fun Byte.and(other: Byte): Byte ``` ``` infix fun Short.and(other: Short): Short ``` Performs a bitwise AND operation between the two values. kotlin inv inv === [kotlin-stdlib](../../../../../index) / [kotlin.experimental](index) / <inv> **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) ``` fun Byte.inv(): Byte ``` ``` fun Short.inv(): Short ``` Inverts the bits in this value. kotlin xor xor === [kotlin-stdlib](../../../../../index) / [kotlin.experimental](index) / <xor> **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) ``` infix fun Byte.xor(other: Byte): Byte ``` ``` infix fun Short.xor(other: Short): Short ``` Performs a bitwise XOR operation between the two values. kotlin or or == [kotlin-stdlib](../../../../../index) / [kotlin.experimental](index) / <or> **Platform and version requirements:** JVM (1.1), JS (1.1), Native (1.1) ``` infix fun Byte.or(other: Byte): Byte ``` ``` infix fun Short.or(other: Short): Short ``` Performs a bitwise OR operation between the two values. kotlin ExperimentalObjCRefinement ExperimentalObjCRefinement ========================== [kotlin-stdlib](../../../../../../index) / [kotlin.experimental](../index) / [ExperimentalObjCRefinement](index) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @Target([AnnotationTarget.ANNOTATION_CLASS]) annotation class ExperimentalObjCRefinement ``` This annotation marks the experimental Objective-C export refinement annotations. Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [<init>](-init-) This annotation marks the experimental Objective-C export refinement annotations. ``` ExperimentalObjCRefinement() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.experimental](../index) / [ExperimentalObjCRefinement](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` ExperimentalObjCRefinement() ``` This annotation marks the experimental Objective-C export refinement annotations. kotlin ExperimentalTypeInference ExperimentalTypeInference ========================= [kotlin-stdlib](../../../../../../index) / [kotlin.experimental](../index) / [ExperimentalTypeInference](index) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @Target([AnnotationTarget.ANNOTATION_CLASS]) annotation class ExperimentalTypeInference ``` The experimental marker for type inference augmenting annotations. Any usage of a declaration annotated with `@ExperimentalTypeInference` must be accepted either by annotating that usage with the [OptIn](../../kotlin/-opt-in/index) annotation, e.g. `@OptIn(ExperimentalTypeInference::class)`, or by using the compiler argument `-opt-in=kotlin.experimental.ExperimentalTypeInference`. Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [<init>](-init-) The experimental marker for type inference augmenting annotations. ``` ExperimentalTypeInference() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.experimental](../index) / [ExperimentalTypeInference](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` ExperimentalTypeInference() ``` The experimental marker for type inference augmenting annotations. Any usage of a declaration annotated with `@ExperimentalTypeInference` must be accepted either by annotating that usage with the [OptIn](../../kotlin/-opt-in/index) annotation, e.g. `@OptIn(ExperimentalTypeInference::class)`, or by using the compiler argument `-opt-in=kotlin.experimental.ExperimentalTypeInference`. kotlin ExperimentalObjCName ExperimentalObjCName ==================== [kotlin-stdlib](../../../../../../index) / [kotlin.experimental](../index) / [ExperimentalObjCName](index) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @Target([AnnotationTarget.ANNOTATION_CLASS]) annotation class ExperimentalObjCName ``` This annotation marks the experimental [ObjCName](../../kotlin.native/-obj-c-name/index#kotlin.native.ObjCName) annotation. Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [<init>](-init-) This annotation marks the experimental [ObjCName](../../kotlin.native/-obj-c-name/index#kotlin.native.ObjCName) annotation. ``` ExperimentalObjCName() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.experimental](../index) / [ExperimentalObjCName](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` ExperimentalObjCName() ``` This annotation marks the experimental [ObjCName](../../kotlin.native/-obj-c-name/index#kotlin.native.ObjCName) annotation. kotlin Package kotlin.random Package kotlin.random ===================== [kotlin-stdlib](../../../../../index) / [kotlin.random](index) Provides the default generator of pseudo-random values, the repeatable generator, and a base class for other RNG implementations. Types ----- **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [Random](-random/index) An abstract class that is implemented by random number generator algorithms. ``` abstract class Random ``` Extensions for External Classes ------------------------------- **Platform and version requirements:** JVM (1.3) #### [java.util.Random](java.util.-random/index) Functions --------- **Platform and version requirements:** JVM (1.3) #### [asJavaRandom](as-java-random) Creates a [java.util.Random](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html) instance that uses the specified Kotlin Random generator as a randomness source. ``` fun Random.asJavaRandom(): Random ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [nextInt](next-int) Gets the next random `Int` from the random number generator in the specified [range](next-int#kotlin.random%24nextInt(kotlin.random.Random,%20kotlin.ranges.IntRange)/range). ``` fun Random.nextInt(range: IntRange): Int ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [nextLong](next-long) Gets the next random `Long` from the random number generator in the specified [range](next-long#kotlin.random%24nextLong(kotlin.random.Random,%20kotlin.ranges.LongRange)/range). ``` fun Random.nextLong(range: LongRange): Long ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [nextUBytes](next-u-bytes) Fills the specified unsigned byte [array](next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray)/array) with random bytes and returns it. ``` fun Random.nextUBytes(array: UByteArray): UByteArray ``` Creates an unsigned byte array of the specified [size](next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.Int)/size), filled with random bytes. ``` fun Random.nextUBytes(size: Int): UByteArray ``` Fills a subrange of the specified `UByte` [array](next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray,%20kotlin.Int,%20kotlin.Int)/array) starting from [fromIndex](next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray,%20kotlin.Int,%20kotlin.Int)/fromIndex) inclusive and ending [toIndex](next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray,%20kotlin.Int,%20kotlin.Int)/toIndex) exclusive with random UBytes. ``` fun Random.nextUBytes(     array: UByteArray,     fromIndex: Int = 0,     toIndex: Int = array.size ): UByteArray ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### [nextUInt](next-u-int) Gets the next random [UInt](../kotlin/-u-int/index) from the random number generator. ``` fun Random.nextUInt(): UInt ``` Gets the next random [UInt](../kotlin/-u-int/index) from the random number generator less than the specified [until](next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.UInt)/until) bound. ``` fun Random.nextUInt(until: UInt): UInt ``` Gets the next random [UInt](../kotlin/-u-int/index) from the random number generator in the specified range. ``` fun Random.nextUInt(from: UInt, until: UInt): UInt ``` Gets the next random [UInt](../kotlin/-u-int/index) from the random number generator in the specified [range](next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.ranges.UIntRange)/range). ``` fun Random.nextUInt(range: UIntRange): UInt ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### [nextULong](next-u-long) Gets the next random [ULong](../kotlin/-u-long/index) from the random number generator. ``` fun Random.nextULong(): ULong ``` Gets the next random [ULong](../kotlin/-u-long/index) from the random number generator less than the specified [until](next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ULong)/until) bound. ``` fun Random.nextULong(until: ULong): ULong ``` Gets the next random [ULong](../kotlin/-u-long/index) from the random number generator in the specified range. ``` fun Random.nextULong(from: ULong, until: ULong): ULong ``` Gets the next random [ULong](../kotlin/-u-long/index) from the random number generator in the specified [range](next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ranges.ULongRange)/range). ``` fun Random.nextULong(range: ULongRange): ULong ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [Random](-random) Returns a repeatable random number generator seeded with the given [seed](-random#kotlin.random%24Random(kotlin.Int)/seed) `Int` value. ``` fun Random(seed: Int): Random ``` Returns a repeatable random number generator seeded with the given [seed](-random#kotlin.random%24Random(kotlin.Long)/seed) `Long` value. ``` fun Random(seed: Long): Random ```
programming_docs
kotlin nextULong nextULong ========= [kotlin-stdlib](../../../../../index) / [kotlin.random](index) / [nextULong](next-u-long) **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun Random.nextULong(): ULong ``` Gets the next random [ULong](../kotlin/-u-long/index) from the random number generator. Generates a [ULong](../kotlin/-u-long/index) random value uniformly distributed between [ULong.MIN\_VALUE](../kotlin/-u-long/-m-i-n_-v-a-l-u-e) and [ULong.MAX\_VALUE](../kotlin/-u-long/-m-a-x_-v-a-l-u-e) (inclusive). **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun Random.nextULong(until: ULong): ULong ``` Gets the next random [ULong](../kotlin/-u-long/index) from the random number generator less than the specified [until](next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ULong)/until) bound. Generates a [ULong](../kotlin/-u-long/index) random value uniformly distributed between `0` (inclusive) and the specified [until](next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ULong)/until) bound (exclusive). Exceptions ---------- `IllegalArgumentException` - if [until](next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ULong)/until) is zero. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun Random.nextULong(from: ULong, until: ULong): ULong ``` Gets the next random [ULong](../kotlin/-u-long/index) from the random number generator in the specified range. Generates a [ULong](../kotlin/-u-long/index) random value uniformly distributed between the specified [from](next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ULong,%20kotlin.ULong)/from) (inclusive) and [until](next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ULong,%20kotlin.ULong)/until) (exclusive) bounds. Exceptions ---------- `IllegalArgumentException` - if [from](next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ULong,%20kotlin.ULong)/from) is greater than or equal to [until](next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ULong,%20kotlin.ULong)/until). **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun Random.nextULong(range: ULongRange): ULong ``` Gets the next random [ULong](../kotlin/-u-long/index) from the random number generator in the specified [range](next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ranges.ULongRange)/range). Generates a [ULong](../kotlin/-u-long/index) random value uniformly distributed in the specified [range](next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ranges.ULongRange)/range): from `range.start` inclusive to `range.endInclusive` inclusive. Exceptions ---------- `IllegalArgumentException` - if [range](next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ranges.ULongRange)/range) is empty. kotlin asJavaRandom asJavaRandom ============ [kotlin-stdlib](../../../../../index) / [kotlin.random](index) / [asJavaRandom](as-java-random) **Platform and version requirements:** JVM (1.3) ``` fun Random.asJavaRandom(): Random ``` Creates a [java.util.Random](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html) instance that uses the specified Kotlin Random generator as a randomness source. kotlin nextInt nextInt ======= [kotlin-stdlib](../../../../../index) / [kotlin.random](index) / [nextInt](next-int) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` fun Random.nextInt(range: IntRange): Int ``` Gets the next random `Int` from the random number generator in the specified [range](next-int#kotlin.random%24nextInt(kotlin.random.Random,%20kotlin.ranges.IntRange)/range). Generates an `Int` random value uniformly distributed in the specified [range](next-int#kotlin.random%24nextInt(kotlin.random.Random,%20kotlin.ranges.IntRange)/range): from `range.start` inclusive to `range.endInclusive` inclusive. Exceptions ---------- `IllegalArgumentException` - if [range](next-int#kotlin.random%24nextInt(kotlin.random.Random,%20kotlin.ranges.IntRange)/range) is empty. kotlin Random Random ====== [kotlin-stdlib](../../../../../index) / [kotlin.random](index) / [Random](-random) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` fun Random(seed: Int): Random ``` Returns a repeatable random number generator seeded with the given [seed](-random#kotlin.random%24Random(kotlin.Int)/seed) `Int` value. Two generators with the same seed produce the same sequence of values within the same version of Kotlin runtime. *Note:* Future versions of Kotlin may change the algorithm of this seeded number generator so that it will return a sequence of values different from the current one for a given seed. On JVM the returned generator is NOT thread-safe. Do not invoke it from multiple threads without proper synchronization. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart fun getRandomList(random: Random): List<Int> = List(10) { random.nextInt(0, 100) } val randomValues1 = getRandomList(Random(42)) // prints the same sequence every time println(randomValues1) // [33, 40, 41, 2, 41, 32, 21, 40, 69, 87] val randomValues2 = getRandomList(Random(42)) // random with the same seed produce the same sequence println("randomValues1 == randomValues2 is ${randomValues1 == randomValues2}") // true val randomValues3 = getRandomList(Random(0)) // random with another seed produce another sequence println(randomValues3) // [14, 48, 57, 67, 82, 7, 61, 27, 14, 59] //sampleEnd } ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` fun Random(seed: Long): Random ``` Returns a repeatable random number generator seeded with the given [seed](-random#kotlin.random%24Random(kotlin.Long)/seed) `Long` value. Two generators with the same seed produce the same sequence of values within the same version of Kotlin runtime. *Note:* Future versions of Kotlin may change the algorithm of this seeded number generator so that it will return a sequence of values different from the current one for a given seed. On JVM the returned generator is NOT thread-safe. Do not invoke it from multiple threads without proper synchronization. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart fun getRandomList(random: Random): List<Int> = List(10) { random.nextInt(0, 100) } val randomValues1 = getRandomList(Random(42)) // prints the same sequence every time println(randomValues1) // [33, 40, 41, 2, 41, 32, 21, 40, 69, 87] val randomValues2 = getRandomList(Random(42)) // random with the same seed produce the same sequence println("randomValues1 == randomValues2 is ${randomValues1 == randomValues2}") // true val randomValues3 = getRandomList(Random(0)) // random with another seed produce another sequence println(randomValues3) // [14, 48, 57, 67, 82, 7, 61, 27, 14, 59] //sampleEnd } ``` kotlin nextUInt nextUInt ======== [kotlin-stdlib](../../../../../index) / [kotlin.random](index) / [nextUInt](next-u-int) **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun Random.nextUInt(): UInt ``` Gets the next random [UInt](../kotlin/-u-int/index) from the random number generator. Generates a [UInt](../kotlin/-u-int/index) random value uniformly distributed between [UInt.MIN\_VALUE](../kotlin/-u-int/-m-i-n_-v-a-l-u-e) and [UInt.MAX\_VALUE](../kotlin/-u-int/-m-a-x_-v-a-l-u-e) (inclusive). **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun Random.nextUInt(until: UInt): UInt ``` Gets the next random [UInt](../kotlin/-u-int/index) from the random number generator less than the specified [until](next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.UInt)/until) bound. Generates a [UInt](../kotlin/-u-int/index) random value uniformly distributed between `0` (inclusive) and the specified [until](next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.UInt)/until) bound (exclusive). Exceptions ---------- `IllegalArgumentException` - if [until](next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.UInt)/until) is zero. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun Random.nextUInt(from: UInt, until: UInt): UInt ``` Gets the next random [UInt](../kotlin/-u-int/index) from the random number generator in the specified range. Generates a [UInt](../kotlin/-u-int/index) random value uniformly distributed between the specified [from](next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.UInt,%20kotlin.UInt)/from) (inclusive) and [until](next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.UInt,%20kotlin.UInt)/until) (exclusive) bounds. Exceptions ---------- `IllegalArgumentException` - if [from](next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.UInt,%20kotlin.UInt)/from) is greater than or equal to [until](next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.UInt,%20kotlin.UInt)/until). **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` fun Random.nextUInt(range: UIntRange): UInt ``` Gets the next random [UInt](../kotlin/-u-int/index) from the random number generator in the specified [range](next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.ranges.UIntRange)/range). Generates a [UInt](../kotlin/-u-int/index) random value uniformly distributed in the specified [range](next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.ranges.UIntRange)/range): from `range.start` inclusive to `range.endInclusive` inclusive. Exceptions ---------- `IllegalArgumentException` - if [range](next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.ranges.UIntRange)/range) is empty. kotlin nextUBytes nextUBytes ========== [kotlin-stdlib](../../../../../index) / [kotlin.random](index) / [nextUBytes](next-u-bytes) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalUnsignedTypes fun Random.nextUBytes(     array: UByteArray ): UByteArray ``` Fills the specified unsigned byte [array](next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray)/array) with random bytes and returns it. **Return** [array](next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray)/array) filled with random bytes. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalUnsignedTypes fun Random.nextUBytes(     size: Int ): UByteArray ``` Creates an unsigned byte array of the specified [size](next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.Int)/size), filled with random bytes. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalUnsignedTypes fun Random.nextUBytes(     array: UByteArray,     fromIndex: Int = 0,     toIndex: Int = array.size ): UByteArray ``` Fills a subrange of the specified `UByte` [array](next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray,%20kotlin.Int,%20kotlin.Int)/array) starting from [fromIndex](next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray,%20kotlin.Int,%20kotlin.Int)/fromIndex) inclusive and ending [toIndex](next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray,%20kotlin.Int,%20kotlin.Int)/toIndex) exclusive with random UBytes. **Return** [array](next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray,%20kotlin.Int,%20kotlin.Int)/array) with the subrange filled with random bytes. kotlin nextLong nextLong ======== [kotlin-stdlib](../../../../../index) / [kotlin.random](index) / [nextLong](next-long) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` fun Random.nextLong(range: LongRange): Long ``` Gets the next random `Long` from the random number generator in the specified [range](next-long#kotlin.random%24nextLong(kotlin.random.Random,%20kotlin.ranges.LongRange)/range). Generates a `Long` random value uniformly distributed in the specified [range](next-long#kotlin.random%24nextLong(kotlin.random.Random,%20kotlin.ranges.LongRange)/range): from `range.start` inclusive to `range.endInclusive` inclusive. Exceptions ---------- `IllegalArgumentException` - if [range](next-long#kotlin.random%24nextLong(kotlin.random.Random,%20kotlin.ranges.LongRange)/range) is empty. kotlin Extensions for java.util.Random Extensions for java.util.Random =============================== [kotlin-stdlib](../../../../../../index) / [kotlin.random](../index) / [java.util.Random](index) **Platform and version requirements:** JVM (1.3) #### [asKotlinRandom](as-kotlin-random) Creates a Kotlin Random instance that uses the specified [java.util.Random](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html) generator as a randomness source. ``` fun Random.asKotlinRandom(): Random ``` kotlin asKotlinRandom asKotlinRandom ============== [kotlin-stdlib](../../../../../../index) / [kotlin.random](../index) / [java.util.Random](index) / [asKotlinRandom](as-kotlin-random) **Platform and version requirements:** JVM (1.3) ``` fun Random.asKotlinRandom(): Random ``` Creates a Kotlin Random instance that uses the specified [java.util.Random](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html) generator as a randomness source. kotlin nextFloat nextFloat ========= [kotlin-stdlib](../../../../../../index) / [kotlin.random](../index) / [Random](index) / [nextFloat](next-float) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextFloat(): Float ``` ``` fun nextFloat(): Float ``` Gets the next random [Float](../../kotlin/-float/index#kotlin.Float) value uniformly distributed between 0 (inclusive) and 1 (exclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart if (Random.nextFloat() <= 0.3) { println("There was 30% possibility of rainy weather today and it is raining.") } else { println("There was 70% possibility of sunny weather today and the sun is shining.") } //sampleEnd } ``` kotlin Random Random ====== [kotlin-stdlib](../../../../../../index) / [kotlin.random](../index) / [Random](index) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` abstract class Random ``` An abstract class that is implemented by random number generator algorithms. The companion object [Random.Default](-default/index) is the default instance of [Random](index). To get a seeded instance of random generator use [Random](index) function. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val randomValues = List(10) { Random.nextInt(0, 100) } // prints new sequence every time println(randomValues) val nextValues = List(10) { Random.nextInt(0, 100) } println(nextValues) println("randomValues != nextValues is ${randomValues != nextValues}") // true //sampleEnd } ``` Types ----- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [Default](-default/index) The default random number generator. ``` companion object Default : Random, Serializable ``` Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [<init>](-init-) An abstract class that is implemented by random number generator algorithms. ``` Random() ``` Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextBits](next-bits) Gets the next random [bitCount](next-bits#kotlin.random.Random%24nextBits(kotlin.Int)/bitCount) number of bits. ``` abstract fun nextBits(bitCount: Int): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextBoolean](next-boolean) Gets the next random [Boolean](../../kotlin/-boolean/index#kotlin.Boolean) value. ``` open fun nextBoolean(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextBytes](next-bytes) Fills a subrange of the specified byte [array](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/array) starting from [fromIndex](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/fromIndex) inclusive and ending [toIndex](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/toIndex) exclusive with random bytes. ``` open fun nextBytes(     array: ByteArray,     fromIndex: Int = 0,     toIndex: Int = array.size ): ByteArray ``` Fills the specified byte [array](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray)/array) with random bytes and returns it. ``` open fun nextBytes(array: ByteArray): ByteArray ``` Creates a byte array of the specified [size](next-bytes#kotlin.random.Random%24nextBytes(kotlin.Int)/size), filled with random bytes. ``` open fun nextBytes(size: Int): ByteArray ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextDouble](next-double) Gets the next random [Double](../../kotlin/-double/index#kotlin.Double) value uniformly distributed between 0 (inclusive) and 1 (exclusive). ``` open fun nextDouble(): Double ``` Gets the next random non-negative `Double` from the random number generator less than the specified [until](next-double#kotlin.random.Random%24nextDouble(kotlin.Double)/until) bound. ``` open fun nextDouble(until: Double): Double ``` Gets the next random `Double` from the random number generator in the specified range. ``` open fun nextDouble(from: Double, until: Double): Double ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextFloat](next-float) Gets the next random [Float](../../kotlin/-float/index#kotlin.Float) value uniformly distributed between 0 (inclusive) and 1 (exclusive). ``` open fun nextFloat(): Float ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextInt](next-int) Gets the next random `Int` from the random number generator. ``` open fun nextInt(): Int ``` Gets the next random non-negative `Int` from the random number generator less than the specified [until](next-int#kotlin.random.Random%24nextInt(kotlin.Int)/until) bound. ``` open fun nextInt(until: Int): Int ``` Gets the next random `Int` from the random number generator in the specified range. ``` open fun nextInt(from: Int, until: Int): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextLong](next-long) Gets the next random `Long` from the random number generator. ``` open fun nextLong(): Long ``` Gets the next random non-negative `Long` from the random number generator less than the specified [until](next-long#kotlin.random.Random%24nextLong(kotlin.Long)/until) bound. ``` open fun nextLong(until: Long): Long ``` Gets the next random `Long` from the random number generator in the specified range. ``` open fun nextLong(from: Long, until: Long): Long ``` Companion Object Functions -------------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextBits](next-bits) Gets the next random [bitCount](next-bits#kotlin.random.Random%24nextBits(kotlin.Int)/bitCount) number of bits. ``` fun nextBits(bitCount: Int): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextBoolean](next-boolean) Gets the next random [Boolean](../../kotlin/-boolean/index#kotlin.Boolean) value. ``` fun nextBoolean(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextBytes](next-bytes) Fills the specified byte [array](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray)/array) with random bytes and returns it. ``` fun nextBytes(array: ByteArray): ByteArray ``` Creates a byte array of the specified [size](next-bytes#kotlin.random.Random%24nextBytes(kotlin.Int)/size), filled with random bytes. ``` fun nextBytes(size: Int): ByteArray ``` Fills a subrange of the specified byte [array](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/array) starting from [fromIndex](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/fromIndex) inclusive and ending [toIndex](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/toIndex) exclusive with random bytes. ``` fun nextBytes(     array: ByteArray,     fromIndex: Int,     toIndex: Int ): ByteArray ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextDouble](next-double) Gets the next random [Double](../../kotlin/-double/index#kotlin.Double) value uniformly distributed between 0 (inclusive) and 1 (exclusive). ``` fun nextDouble(): Double ``` Gets the next random non-negative `Double` from the random number generator less than the specified [until](next-double#kotlin.random.Random%24nextDouble(kotlin.Double)/until) bound. ``` fun nextDouble(until: Double): Double ``` Gets the next random `Double` from the random number generator in the specified range. ``` fun nextDouble(from: Double, until: Double): Double ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextFloat](next-float) Gets the next random [Float](../../kotlin/-float/index#kotlin.Float) value uniformly distributed between 0 (inclusive) and 1 (exclusive). ``` fun nextFloat(): Float ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextInt](next-int) Gets the next random `Int` from the random number generator. ``` fun nextInt(): Int ``` Gets the next random non-negative `Int` from the random number generator less than the specified [until](next-int#kotlin.random.Random%24nextInt(kotlin.Int)/until) bound. ``` fun nextInt(until: Int): Int ``` Gets the next random `Int` from the random number generator in the specified range. ``` fun nextInt(from: Int, until: Int): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextLong](next-long) Gets the next random `Long` from the random number generator. ``` fun nextLong(): Long ``` Gets the next random non-negative `Long` from the random number generator less than the specified [until](next-long#kotlin.random.Random%24nextLong(kotlin.Long)/until) bound. ``` fun nextLong(until: Long): Long ``` Gets the next random `Long` from the random number generator in the specified range. ``` fun nextLong(from: Long, until: Long): Long ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.3) #### [asJavaRandom](../as-java-random) Creates a [java.util.Random](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html) instance that uses the specified Kotlin Random generator as a randomness source. ``` fun Random.asJavaRandom(): Random ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [nextInt](../next-int) Gets the next random `Int` from the random number generator in the specified [range](../next-int#kotlin.random%24nextInt(kotlin.random.Random,%20kotlin.ranges.IntRange)/range). ``` fun Random.nextInt(range: IntRange): Int ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [nextLong](../next-long) Gets the next random `Long` from the random number generator in the specified [range](../next-long#kotlin.random%24nextLong(kotlin.random.Random,%20kotlin.ranges.LongRange)/range). ``` fun Random.nextLong(range: LongRange): Long ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [nextUBytes](../next-u-bytes) Fills the specified unsigned byte [array](../next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray)/array) with random bytes and returns it. ``` fun Random.nextUBytes(array: UByteArray): UByteArray ``` Creates an unsigned byte array of the specified [size](../next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.Int)/size), filled with random bytes. ``` fun Random.nextUBytes(size: Int): UByteArray ``` Fills a subrange of the specified `UByte` [array](../next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray,%20kotlin.Int,%20kotlin.Int)/array) starting from [fromIndex](../next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray,%20kotlin.Int,%20kotlin.Int)/fromIndex) inclusive and ending [toIndex](../next-u-bytes#kotlin.random%24nextUBytes(kotlin.random.Random,%20kotlin.UByteArray,%20kotlin.Int,%20kotlin.Int)/toIndex) exclusive with random UBytes. ``` fun Random.nextUBytes(     array: UByteArray,     fromIndex: Int = 0,     toIndex: Int = array.size ): UByteArray ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### [nextUInt](../next-u-int) Gets the next random [UInt](../../kotlin/-u-int/index) from the random number generator. ``` fun Random.nextUInt(): UInt ``` Gets the next random [UInt](../../kotlin/-u-int/index) from the random number generator less than the specified [until](../next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.UInt)/until) bound. ``` fun Random.nextUInt(until: UInt): UInt ``` Gets the next random [UInt](../../kotlin/-u-int/index) from the random number generator in the specified range. ``` fun Random.nextUInt(from: UInt, until: UInt): UInt ``` Gets the next random [UInt](../../kotlin/-u-int/index) from the random number generator in the specified [range](../next-u-int#kotlin.random%24nextUInt(kotlin.random.Random,%20kotlin.ranges.UIntRange)/range). ``` fun Random.nextUInt(range: UIntRange): UInt ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### [nextULong](../next-u-long) Gets the next random [ULong](../../kotlin/-u-long/index) from the random number generator. ``` fun Random.nextULong(): ULong ``` Gets the next random [ULong](../../kotlin/-u-long/index) from the random number generator less than the specified [until](../next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ULong)/until) bound. ``` fun Random.nextULong(until: ULong): ULong ``` Gets the next random [ULong](../../kotlin/-u-long/index) from the random number generator in the specified range. ``` fun Random.nextULong(from: ULong, until: ULong): ULong ``` Gets the next random [ULong](../../kotlin/-u-long/index) from the random number generator in the specified [range](../next-u-long#kotlin.random%24nextULong(kotlin.random.Random,%20kotlin.ranges.ULongRange)/range). ``` fun Random.nextULong(range: ULongRange): ULong ```
programming_docs
kotlin nextBoolean nextBoolean =========== [kotlin-stdlib](../../../../../../index) / [kotlin.random](../index) / [Random](index) / [nextBoolean](next-boolean) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextBoolean(): Boolean ``` ``` fun nextBoolean(): Boolean ``` Gets the next random [Boolean](../../kotlin/-boolean/index#kotlin.Boolean) value. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val presents = listOf("Candy", "Balloon", "Ball") // a random partition, the result may be different every time val (alicePresents, bobPresents) = presents.partition { Random.nextBoolean() } println("Alice receives $alicePresents") println("Bob receives $bobPresents") //sampleEnd } ``` kotlin nextBytes nextBytes ========= [kotlin-stdlib](../../../../../../index) / [kotlin.random](../index) / [Random](index) / [nextBytes](next-bytes) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextBytes(     array: ByteArray,     fromIndex: Int = 0,     toIndex: Int = array.size ): ByteArray ``` ``` fun nextBytes(     array: ByteArray,     fromIndex: Int,     toIndex: Int ): ByteArray ``` Fills a subrange of the specified byte [array](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/array) starting from [fromIndex](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/fromIndex) inclusive and ending [toIndex](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/toIndex) exclusive with random bytes. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val bytes = ByteArray(4) println(bytes.contentToString()) // [0, 0, 0, 0] Random.nextBytes(bytes, 1, 3) // second and third bytes are generated, rest unchanged println(bytes.contentToString()) Random.nextBytes(bytes) // all bytes are newly generated println(bytes.contentToString()) val newBytes = Random.nextBytes(5) // a new byte array filled with random values println(newBytes.contentToString()) //sampleEnd } ``` **Return** [array](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/array) with the subrange filled with random bytes. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextBytes(array: ByteArray): ByteArray ``` ``` fun nextBytes(array: ByteArray): ByteArray ``` Fills the specified byte [array](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray)/array) with random bytes and returns it. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val bytes = ByteArray(4) println(bytes.contentToString()) // [0, 0, 0, 0] Random.nextBytes(bytes, 1, 3) // second and third bytes are generated, rest unchanged println(bytes.contentToString()) Random.nextBytes(bytes) // all bytes are newly generated println(bytes.contentToString()) val newBytes = Random.nextBytes(5) // a new byte array filled with random values println(newBytes.contentToString()) //sampleEnd } ``` **Return** [array](next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray)/array) filled with random bytes. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextBytes(size: Int): ByteArray ``` ``` fun nextBytes(size: Int): ByteArray ``` Creates a byte array of the specified [size](next-bytes#kotlin.random.Random%24nextBytes(kotlin.Int)/size), filled with random bytes. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val bytes = ByteArray(4) println(bytes.contentToString()) // [0, 0, 0, 0] Random.nextBytes(bytes, 1, 3) // second and third bytes are generated, rest unchanged println(bytes.contentToString()) Random.nextBytes(bytes) // all bytes are newly generated println(bytes.contentToString()) val newBytes = Random.nextBytes(5) // a new byte array filled with random values println(newBytes.contentToString()) //sampleEnd } ``` kotlin nextBits nextBits ======== [kotlin-stdlib](../../../../../../index) / [kotlin.random](../index) / [Random](index) / [nextBits](next-bits) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract fun nextBits(bitCount: Int): Int ``` ``` fun nextBits(bitCount: Int): Int ``` Gets the next random [bitCount](next-bits#kotlin.random.Random%24nextBits(kotlin.Int)/bitCount) number of bits. Generates an `Int` whose lower [bitCount](next-bits#kotlin.random.Random%24nextBits(kotlin.Int)/bitCount) bits are filled with random values and the remaining upper bits are zero. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart // always generates a 0 println(Random.nextBits(0)) // randomly generates a 0 or 1 println(Random.nextBits(1)) // generates a random non-negative Int value less than 256 println(Random.nextBits(8)) // generates a random Int value, may generate a negative value as well println(Random.nextBits(32)) //sampleEnd } ``` Parameters ---------- `bitCount` - number of bits to generate, must be in range 0..32, otherwise the behavior is unspecified. kotlin nextInt nextInt ======= [kotlin-stdlib](../../../../../../index) / [kotlin.random](../index) / [Random](index) / [nextInt](next-int) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextInt(): Int ``` ``` fun nextInt(): Int ``` Gets the next random `Int` from the random number generator. Generates an `Int` random value uniformly distributed between `Int.MIN_VALUE` and `Int.MAX_VALUE` (inclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val randomInts = List(5) { Random.nextInt() } println(randomInts) val sortedRandomInts = randomInts.sorted() println(sortedRandomInts) //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextInt(until: Int): Int ``` ``` fun nextInt(until: Int): Int ``` Gets the next random non-negative `Int` from the random number generator less than the specified [until](next-int#kotlin.random.Random%24nextInt(kotlin.Int)/until) bound. Generates an `Int` random value uniformly distributed between `0` (inclusive) and the specified [until](next-int#kotlin.random.Random%24nextInt(kotlin.Int)/until) bound (exclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val menu = listOf("Omelette", "Porridge", "Cereal", "Chicken", "Pizza", "Pasta") val forBreakfast = Random.nextInt(until = 3).let { menu[it] } val forLunch = Random.nextInt(from = 3, until = 6).let { menu[it] } // new meals every time println("Today I want $forBreakfast for breakfast, and $forLunch for lunch.") //sampleEnd } ``` Parameters ---------- `until` - must be positive. Exceptions ---------- `IllegalArgumentException` - if [until](next-int#kotlin.random.Random%24nextInt(kotlin.Int)/until) is negative or zero. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextInt(from: Int, until: Int): Int ``` ``` fun nextInt(from: Int, until: Int): Int ``` Gets the next random `Int` from the random number generator in the specified range. Generates an `Int` random value uniformly distributed between the specified [from](next-int#kotlin.random.Random%24nextInt(kotlin.Int,%20kotlin.Int)/from) (inclusive) and [until](next-int#kotlin.random.Random%24nextInt(kotlin.Int,%20kotlin.Int)/until) (exclusive) bounds. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val menu = listOf("Omelette", "Porridge", "Cereal", "Chicken", "Pizza", "Pasta") val forBreakfast = Random.nextInt(until = 3).let { menu[it] } val forLunch = Random.nextInt(from = 3, until = 6).let { menu[it] } // new meals every time println("Today I want $forBreakfast for breakfast, and $forLunch for lunch.") //sampleEnd } ``` Exceptions ---------- `IllegalArgumentException` - if [from](next-int#kotlin.random.Random%24nextInt(kotlin.Int,%20kotlin.Int)/from) is greater than or equal to [until](next-int#kotlin.random.Random%24nextInt(kotlin.Int,%20kotlin.Int)/until). kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.random](../index) / [Random](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` Random() ``` An abstract class that is implemented by random number generator algorithms. The companion object [Random.Default](-default/index) is the default instance of [Random](index). To get a seeded instance of random generator use [Random](index) function. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val randomValues = List(10) { Random.nextInt(0, 100) } // prints new sequence every time println(randomValues) val nextValues = List(10) { Random.nextInt(0, 100) } println(nextValues) println("randomValues != nextValues is ${randomValues != nextValues}") // true //sampleEnd } ``` kotlin nextDouble nextDouble ========== [kotlin-stdlib](../../../../../../index) / [kotlin.random](../index) / [Random](index) / [nextDouble](next-double) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextDouble(): Double ``` ``` fun nextDouble(): Double ``` Gets the next random [Double](../../kotlin/-double/index#kotlin.Double) value uniformly distributed between 0 (inclusive) and 1 (exclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart if (Random.nextDouble() <= 0.3) { println("There was 30% possibility of rainy weather today and it is raining.") } else { println("There was 70% possibility of sunny weather today and the sun is shining.") } //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextDouble(until: Double): Double ``` ``` fun nextDouble(until: Double): Double ``` Gets the next random non-negative `Double` from the random number generator less than the specified [until](next-double#kotlin.random.Random%24nextDouble(kotlin.Double)/until) bound. Generates a `Double` random value uniformly distributed between 0 (inclusive) and [until](next-double#kotlin.random.Random%24nextDouble(kotlin.Double)/until) (exclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val firstAngle = Random.nextDouble(until = Math.PI / 6); println("sin(firstAngle) < 0.5 is ${sin(firstAngle) < 0.5}") // true val secondAngle = Random.nextDouble(from = Math.PI / 6, until = Math.PI / 2) val sinValue = sin(secondAngle) println("sinValue >= 0.5 && sinValue < 1.0 is ${sinValue >= 0.5 && sinValue < 1.0}") // true //sampleEnd } ``` Exceptions ---------- `IllegalArgumentException` - if [until](next-double#kotlin.random.Random%24nextDouble(kotlin.Double)/until) is negative or zero. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextDouble(from: Double, until: Double): Double ``` ``` fun nextDouble(from: Double, until: Double): Double ``` Gets the next random `Double` from the random number generator in the specified range. Generates a `Double` random value uniformly distributed between the specified [from](next-double#kotlin.random.Random%24nextDouble(kotlin.Double,%20kotlin.Double)/from) (inclusive) and [until](next-double#kotlin.random.Random%24nextDouble(kotlin.Double,%20kotlin.Double)/until) (exclusive) bounds. [from](next-double#kotlin.random.Random%24nextDouble(kotlin.Double,%20kotlin.Double)/from) and [until](next-double#kotlin.random.Random%24nextDouble(kotlin.Double,%20kotlin.Double)/until) must be finite otherwise the behavior is unspecified. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val firstAngle = Random.nextDouble(until = Math.PI / 6); println("sin(firstAngle) < 0.5 is ${sin(firstAngle) < 0.5}") // true val secondAngle = Random.nextDouble(from = Math.PI / 6, until = Math.PI / 2) val sinValue = sin(secondAngle) println("sinValue >= 0.5 && sinValue < 1.0 is ${sinValue >= 0.5 && sinValue < 1.0}") // true //sampleEnd } ``` Exceptions ---------- `IllegalArgumentException` - if [from](next-double#kotlin.random.Random%24nextDouble(kotlin.Double,%20kotlin.Double)/from) is greater than or equal to [until](next-double#kotlin.random.Random%24nextDouble(kotlin.Double,%20kotlin.Double)/until). kotlin nextLong nextLong ======== [kotlin-stdlib](../../../../../../index) / [kotlin.random](../index) / [Random](index) / [nextLong](next-long) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextLong(): Long ``` ``` fun nextLong(): Long ``` Gets the next random `Long` from the random number generator. Generates a `Long` random value uniformly distributed between `Long.MIN_VALUE` and `Long.MAX_VALUE` (inclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val randomLongs = List(5) { Random.nextLong() } println(randomLongs) val sortedRandomLongs = randomLongs.sorted() println(sortedRandomLongs) //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextLong(until: Long): Long ``` ``` fun nextLong(until: Long): Long ``` Gets the next random non-negative `Long` from the random number generator less than the specified [until](next-long#kotlin.random.Random%24nextLong(kotlin.Long)/until) bound. Generates a `Long` random value uniformly distributed between `0` (inclusive) and the specified [until](next-long#kotlin.random.Random%24nextLong(kotlin.Long)/until) bound (exclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val fileSize = Random.nextLong(until = 1_099_511_627_776) println("A file of $fileSize bytes fits on a 1TB storage.") val long = Random.nextLong(Int.MAX_VALUE + 1L, Long.MAX_VALUE) println("Number $long doesn't fit in an Int.") //sampleEnd } ``` Parameters ---------- `until` - must be positive. Exceptions ---------- `IllegalArgumentException` - if [until](next-long#kotlin.random.Random%24nextLong(kotlin.Long)/until) is negative or zero. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun nextLong(from: Long, until: Long): Long ``` ``` fun nextLong(from: Long, until: Long): Long ``` Gets the next random `Long` from the random number generator in the specified range. Generates a `Long` random value uniformly distributed between the specified [from](next-long#kotlin.random.Random%24nextLong(kotlin.Long,%20kotlin.Long)/from) (inclusive) and [until](next-long#kotlin.random.Random%24nextLong(kotlin.Long,%20kotlin.Long)/until) (exclusive) bounds. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val fileSize = Random.nextLong(until = 1_099_511_627_776) println("A file of $fileSize bytes fits on a 1TB storage.") val long = Random.nextLong(Int.MAX_VALUE + 1L, Long.MAX_VALUE) println("Number $long doesn't fit in an Int.") //sampleEnd } ``` Exceptions ---------- `IllegalArgumentException` - if [from](next-long#kotlin.random.Random%24nextLong(kotlin.Long,%20kotlin.Long)/from) is greater than or equal to [until](next-long#kotlin.random.Random%24nextLong(kotlin.Long,%20kotlin.Long)/until). kotlin nextFloat nextFloat ========= [kotlin-stdlib](../../../../../../../index) / [kotlin.random](../../index) / [Random](../index) / [Default](index) / [nextFloat](next-float) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextFloat(): Float ``` Gets the next random [Float](../../../kotlin/-float/index#kotlin.Float) value uniformly distributed between 0 (inclusive) and 1 (exclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart if (Random.nextFloat() <= 0.3) { println("There was 30% possibility of rainy weather today and it is raining.") } else { println("There was 70% possibility of sunny weather today and the sun is shining.") } //sampleEnd } ``` kotlin Default Default ======= [kotlin-stdlib](../../../../../../../index) / [kotlin.random](../../index) / [Random](../index) / [Default](index) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` companion object Default : Random, Serializable ``` The default random number generator. On JVM this generator is thread-safe, its methods can be invoked from multiple threads. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val randomValues = List(10) { Random.nextInt(0, 100) } // prints new sequence every time println(randomValues) val nextValues = List(10) { Random.nextInt(0, 100) } println(nextValues) println("randomValues != nextValues is ${randomValues != nextValues}") // true //sampleEnd } ``` Companion Object Functions -------------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextBits](next-bits) Gets the next random [bitCount](../next-bits#kotlin.random.Random%24nextBits(kotlin.Int)/bitCount) number of bits. ``` fun nextBits(bitCount: Int): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextBoolean](next-boolean) Gets the next random [Boolean](../../../kotlin/-boolean/index#kotlin.Boolean) value. ``` fun nextBoolean(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextBytes](next-bytes) Fills the specified byte [array](../next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray)/array) with random bytes and returns it. ``` fun nextBytes(array: ByteArray): ByteArray ``` Creates a byte array of the specified [size](../next-bytes#kotlin.random.Random%24nextBytes(kotlin.Int)/size), filled with random bytes. ``` fun nextBytes(size: Int): ByteArray ``` Fills a subrange of the specified byte [array](../next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/array) starting from [fromIndex](../next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/fromIndex) inclusive and ending [toIndex](../next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/toIndex) exclusive with random bytes. ``` fun nextBytes(     array: ByteArray,     fromIndex: Int,     toIndex: Int ): ByteArray ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextDouble](next-double) Gets the next random [Double](../../../kotlin/-double/index#kotlin.Double) value uniformly distributed between 0 (inclusive) and 1 (exclusive). ``` fun nextDouble(): Double ``` Gets the next random non-negative `Double` from the random number generator less than the specified [until](../next-double#kotlin.random.Random%24nextDouble(kotlin.Double)/until) bound. ``` fun nextDouble(until: Double): Double ``` Gets the next random `Double` from the random number generator in the specified range. ``` fun nextDouble(from: Double, until: Double): Double ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextFloat](next-float) Gets the next random [Float](../../../kotlin/-float/index#kotlin.Float) value uniformly distributed between 0 (inclusive) and 1 (exclusive). ``` fun nextFloat(): Float ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextInt](next-int) Gets the next random `Int` from the random number generator. ``` fun nextInt(): Int ``` Gets the next random non-negative `Int` from the random number generator less than the specified [until](../next-int#kotlin.random.Random%24nextInt(kotlin.Int)/until) bound. ``` fun nextInt(until: Int): Int ``` Gets the next random `Int` from the random number generator in the specified range. ``` fun nextInt(from: Int, until: Int): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [nextLong](next-long) Gets the next random `Long` from the random number generator. ``` fun nextLong(): Long ``` Gets the next random non-negative `Long` from the random number generator less than the specified [until](../next-long#kotlin.random.Random%24nextLong(kotlin.Long)/until) bound. ``` fun nextLong(until: Long): Long ``` Gets the next random `Long` from the random number generator in the specified range. ``` fun nextLong(from: Long, until: Long): Long ```
programming_docs
kotlin nextBoolean nextBoolean =========== [kotlin-stdlib](../../../../../../../index) / [kotlin.random](../../index) / [Random](../index) / [Default](index) / [nextBoolean](next-boolean) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextBoolean(): Boolean ``` Gets the next random [Boolean](../../../kotlin/-boolean/index#kotlin.Boolean) value. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val presents = listOf("Candy", "Balloon", "Ball") // a random partition, the result may be different every time val (alicePresents, bobPresents) = presents.partition { Random.nextBoolean() } println("Alice receives $alicePresents") println("Bob receives $bobPresents") //sampleEnd } ``` kotlin nextBytes nextBytes ========= [kotlin-stdlib](../../../../../../../index) / [kotlin.random](../../index) / [Random](../index) / [Default](index) / [nextBytes](next-bytes) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextBytes(array: ByteArray): ByteArray ``` Fills the specified byte [array](../next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray)/array) with random bytes and returns it. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val bytes = ByteArray(4) println(bytes.contentToString()) // [0, 0, 0, 0] Random.nextBytes(bytes, 1, 3) // second and third bytes are generated, rest unchanged println(bytes.contentToString()) Random.nextBytes(bytes) // all bytes are newly generated println(bytes.contentToString()) val newBytes = Random.nextBytes(5) // a new byte array filled with random values println(newBytes.contentToString()) //sampleEnd } ``` **Return** [array](../next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray)/array) filled with random bytes. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextBytes(size: Int): ByteArray ``` Creates a byte array of the specified [size](../next-bytes#kotlin.random.Random%24nextBytes(kotlin.Int)/size), filled with random bytes. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val bytes = ByteArray(4) println(bytes.contentToString()) // [0, 0, 0, 0] Random.nextBytes(bytes, 1, 3) // second and third bytes are generated, rest unchanged println(bytes.contentToString()) Random.nextBytes(bytes) // all bytes are newly generated println(bytes.contentToString()) val newBytes = Random.nextBytes(5) // a new byte array filled with random values println(newBytes.contentToString()) //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextBytes(     array: ByteArray,     fromIndex: Int,     toIndex: Int ): ByteArray ``` Fills a subrange of the specified byte [array](../next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/array) starting from [fromIndex](../next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/fromIndex) inclusive and ending [toIndex](../next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/toIndex) exclusive with random bytes. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val bytes = ByteArray(4) println(bytes.contentToString()) // [0, 0, 0, 0] Random.nextBytes(bytes, 1, 3) // second and third bytes are generated, rest unchanged println(bytes.contentToString()) Random.nextBytes(bytes) // all bytes are newly generated println(bytes.contentToString()) val newBytes = Random.nextBytes(5) // a new byte array filled with random values println(newBytes.contentToString()) //sampleEnd } ``` **Return** [array](../next-bytes#kotlin.random.Random%24nextBytes(kotlin.ByteArray,%20kotlin.Int,%20kotlin.Int)/array) with the subrange filled with random bytes. kotlin nextBits nextBits ======== [kotlin-stdlib](../../../../../../../index) / [kotlin.random](../../index) / [Random](../index) / [Default](index) / [nextBits](next-bits) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextBits(bitCount: Int): Int ``` Gets the next random [bitCount](../next-bits#kotlin.random.Random%24nextBits(kotlin.Int)/bitCount) number of bits. Generates an `Int` whose lower [bitCount](../next-bits#kotlin.random.Random%24nextBits(kotlin.Int)/bitCount) bits are filled with random values and the remaining upper bits are zero. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart // always generates a 0 println(Random.nextBits(0)) // randomly generates a 0 or 1 println(Random.nextBits(1)) // generates a random non-negative Int value less than 256 println(Random.nextBits(8)) // generates a random Int value, may generate a negative value as well println(Random.nextBits(32)) //sampleEnd } ``` Parameters ---------- `bitCount` - number of bits to generate, must be in range 0..32, otherwise the behavior is unspecified. kotlin nextInt nextInt ======= [kotlin-stdlib](../../../../../../../index) / [kotlin.random](../../index) / [Random](../index) / [Default](index) / [nextInt](next-int) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextInt(): Int ``` Gets the next random `Int` from the random number generator. Generates an `Int` random value uniformly distributed between `Int.MIN_VALUE` and `Int.MAX_VALUE` (inclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val randomInts = List(5) { Random.nextInt() } println(randomInts) val sortedRandomInts = randomInts.sorted() println(sortedRandomInts) //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextInt(until: Int): Int ``` Gets the next random non-negative `Int` from the random number generator less than the specified [until](../next-int#kotlin.random.Random%24nextInt(kotlin.Int)/until) bound. Generates an `Int` random value uniformly distributed between `0` (inclusive) and the specified [until](../next-int#kotlin.random.Random%24nextInt(kotlin.Int)/until) bound (exclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val menu = listOf("Omelette", "Porridge", "Cereal", "Chicken", "Pizza", "Pasta") val forBreakfast = Random.nextInt(until = 3).let { menu[it] } val forLunch = Random.nextInt(from = 3, until = 6).let { menu[it] } // new meals every time println("Today I want $forBreakfast for breakfast, and $forLunch for lunch.") //sampleEnd } ``` Parameters ---------- `until` - must be positive. Exceptions ---------- `IllegalArgumentException` - if [until](../next-int#kotlin.random.Random%24nextInt(kotlin.Int)/until) is negative or zero. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextInt(from: Int, until: Int): Int ``` Gets the next random `Int` from the random number generator in the specified range. Generates an `Int` random value uniformly distributed between the specified [from](../next-int#kotlin.random.Random%24nextInt(kotlin.Int,%20kotlin.Int)/from) (inclusive) and [until](../next-int#kotlin.random.Random%24nextInt(kotlin.Int,%20kotlin.Int)/until) (exclusive) bounds. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val menu = listOf("Omelette", "Porridge", "Cereal", "Chicken", "Pizza", "Pasta") val forBreakfast = Random.nextInt(until = 3).let { menu[it] } val forLunch = Random.nextInt(from = 3, until = 6).let { menu[it] } // new meals every time println("Today I want $forBreakfast for breakfast, and $forLunch for lunch.") //sampleEnd } ``` Exceptions ---------- `IllegalArgumentException` - if [from](../next-int#kotlin.random.Random%24nextInt(kotlin.Int,%20kotlin.Int)/from) is greater than or equal to [until](../next-int#kotlin.random.Random%24nextInt(kotlin.Int,%20kotlin.Int)/until). kotlin nextDouble nextDouble ========== [kotlin-stdlib](../../../../../../../index) / [kotlin.random](../../index) / [Random](../index) / [Default](index) / [nextDouble](next-double) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextDouble(): Double ``` Gets the next random [Double](../../../kotlin/-double/index#kotlin.Double) value uniformly distributed between 0 (inclusive) and 1 (exclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart if (Random.nextDouble() <= 0.3) { println("There was 30% possibility of rainy weather today and it is raining.") } else { println("There was 70% possibility of sunny weather today and the sun is shining.") } //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextDouble(until: Double): Double ``` Gets the next random non-negative `Double` from the random number generator less than the specified [until](../next-double#kotlin.random.Random%24nextDouble(kotlin.Double)/until) bound. Generates a `Double` random value uniformly distributed between 0 (inclusive) and [until](../next-double#kotlin.random.Random%24nextDouble(kotlin.Double)/until) (exclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val firstAngle = Random.nextDouble(until = Math.PI / 6); println("sin(firstAngle) < 0.5 is ${sin(firstAngle) < 0.5}") // true val secondAngle = Random.nextDouble(from = Math.PI / 6, until = Math.PI / 2) val sinValue = sin(secondAngle) println("sinValue >= 0.5 && sinValue < 1.0 is ${sinValue >= 0.5 && sinValue < 1.0}") // true //sampleEnd } ``` Exceptions ---------- `IllegalArgumentException` - if [until](../next-double#kotlin.random.Random%24nextDouble(kotlin.Double)/until) is negative or zero. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextDouble(from: Double, until: Double): Double ``` Gets the next random `Double` from the random number generator in the specified range. Generates a `Double` random value uniformly distributed between the specified [from](../next-double#kotlin.random.Random%24nextDouble(kotlin.Double,%20kotlin.Double)/from) (inclusive) and [until](../next-double#kotlin.random.Random%24nextDouble(kotlin.Double,%20kotlin.Double)/until) (exclusive) bounds. [from](../next-double#kotlin.random.Random%24nextDouble(kotlin.Double,%20kotlin.Double)/from) and [until](../next-double#kotlin.random.Random%24nextDouble(kotlin.Double,%20kotlin.Double)/until) must be finite otherwise the behavior is unspecified. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val firstAngle = Random.nextDouble(until = Math.PI / 6); println("sin(firstAngle) < 0.5 is ${sin(firstAngle) < 0.5}") // true val secondAngle = Random.nextDouble(from = Math.PI / 6, until = Math.PI / 2) val sinValue = sin(secondAngle) println("sinValue >= 0.5 && sinValue < 1.0 is ${sinValue >= 0.5 && sinValue < 1.0}") // true //sampleEnd } ``` Exceptions ---------- `IllegalArgumentException` - if [from](../next-double#kotlin.random.Random%24nextDouble(kotlin.Double,%20kotlin.Double)/from) is greater than or equal to [until](../next-double#kotlin.random.Random%24nextDouble(kotlin.Double,%20kotlin.Double)/until). kotlin nextLong nextLong ======== [kotlin-stdlib](../../../../../../../index) / [kotlin.random](../../index) / [Random](../index) / [Default](index) / [nextLong](next-long) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextLong(): Long ``` Gets the next random `Long` from the random number generator. Generates a `Long` random value uniformly distributed between `Long.MIN_VALUE` and `Long.MAX_VALUE` (inclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val randomLongs = List(5) { Random.nextLong() } println(randomLongs) val sortedRandomLongs = randomLongs.sorted() println(sortedRandomLongs) //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextLong(until: Long): Long ``` Gets the next random non-negative `Long` from the random number generator less than the specified [until](../next-long#kotlin.random.Random%24nextLong(kotlin.Long)/until) bound. Generates a `Long` random value uniformly distributed between `0` (inclusive) and the specified [until](../next-long#kotlin.random.Random%24nextLong(kotlin.Long)/until) bound (exclusive). ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val fileSize = Random.nextLong(until = 1_099_511_627_776) println("A file of $fileSize bytes fits on a 1TB storage.") val long = Random.nextLong(Int.MAX_VALUE + 1L, Long.MAX_VALUE) println("Number $long doesn't fit in an Int.") //sampleEnd } ``` Parameters ---------- `until` - must be positive. Exceptions ---------- `IllegalArgumentException` - if [until](../next-long#kotlin.random.Random%24nextLong(kotlin.Long)/until) is negative or zero. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun nextLong(from: Long, until: Long): Long ``` Gets the next random `Long` from the random number generator in the specified range. Generates a `Long` random value uniformly distributed between the specified [from](../next-long#kotlin.random.Random%24nextLong(kotlin.Long,%20kotlin.Long)/from) (inclusive) and [until](../next-long#kotlin.random.Random%24nextLong(kotlin.Long,%20kotlin.Long)/until) (exclusive) bounds. ``` import kotlin.math.sin import kotlin.random.Random import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val fileSize = Random.nextLong(until = 1_099_511_627_776) println("A file of $fileSize bytes fits on a 1TB storage.") val long = Random.nextLong(Int.MAX_VALUE + 1L, Long.MAX_VALUE) println("Number $long doesn't fit in an Int.") //sampleEnd } ``` Exceptions ---------- `IllegalArgumentException` - if [from](../next-long#kotlin.random.Random%24nextLong(kotlin.Long,%20kotlin.Long)/from) is greater than or equal to [until](../next-long#kotlin.random.Random%24nextLong(kotlin.Long,%20kotlin.Long)/until). kotlin fixedRateTimer fixedRateTimer ============== [kotlin-stdlib](../../../../../index) / [kotlin.concurrent](index) / [fixedRateTimer](fixed-rate-timer) **Platform and version requirements:** JVM (1.0) ``` inline fun fixedRateTimer(     name: String? = null,     daemon: Boolean = false,     initialDelay: Long = 0.toLong(),     period: Long,     crossinline action: TimerTask.() -> Unit ): Timer ``` Creates a timer that executes the specified [action](fixed-rate-timer#kotlin.concurrent%24fixedRateTimer(kotlin.String?,%20kotlin.Boolean,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) periodically, starting after the specified [initialDelay](fixed-rate-timer#kotlin.concurrent%24fixedRateTimer(kotlin.String?,%20kotlin.Boolean,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/initialDelay) (expressed in milliseconds) and with the interval of [period](fixed-rate-timer#kotlin.concurrent%24fixedRateTimer(kotlin.String?,%20kotlin.Boolean,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the start of the previous task and the start of the next one. Parameters ---------- `name` - the name to use for the thread which is running the timer. `daemon` - if `true`, the thread is started as a daemon thread (the VM will exit when only daemon threads are running). **Platform and version requirements:** JVM (1.0) ``` inline fun fixedRateTimer(     name: String? = null,     daemon: Boolean = false,     startAt: Date,     period: Long,     crossinline action: TimerTask.() -> Unit ): Timer ``` Creates a timer that executes the specified [action](fixed-rate-timer#kotlin.concurrent%24fixedRateTimer(kotlin.String?,%20kotlin.Boolean,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) periodically, starting at the specified [startAt](fixed-rate-timer#kotlin.concurrent%24fixedRateTimer(kotlin.String?,%20kotlin.Boolean,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/startAt) date and with the interval of [period](fixed-rate-timer#kotlin.concurrent%24fixedRateTimer(kotlin.String?,%20kotlin.Boolean,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the start of the previous task and the start of the next one. Parameters ---------- `name` - the name to use for the thread which is running the timer. `daemon` - if `true`, the thread is started as a daemon thread (the VM will exit when only daemon threads are running). kotlin Package kotlin.concurrent Package kotlin.concurrent ========================= [kotlin-stdlib](../../../../../index) / [kotlin.concurrent](index) Utility functions for concurrent programming. Extensions for External Classes ------------------------------- **Platform and version requirements:** JVM (1.0) #### [java.lang.ThreadLocal](java.lang.-thread-local/index) **Platform and version requirements:** JVM (1.0) #### [java.util.concurrent.locks.Lock](java.util.concurrent.locks.-lock/index) **Platform and version requirements:** JVM (1.0) #### [java.util.concurrent.locks.ReentrantReadWriteLock](java.util.concurrent.locks.-reentrant-read-write-lock/index) **Platform and version requirements:** JVM (1.0) #### [java.util.Timer](java.util.-timer/index) Functions --------- **Platform and version requirements:** JVM (1.0) #### [fixedRateTimer](fixed-rate-timer) Creates a timer that executes the specified [action](fixed-rate-timer#kotlin.concurrent%24fixedRateTimer(kotlin.String?,%20kotlin.Boolean,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) periodically, starting after the specified [initialDelay](fixed-rate-timer#kotlin.concurrent%24fixedRateTimer(kotlin.String?,%20kotlin.Boolean,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/initialDelay) (expressed in milliseconds) and with the interval of [period](fixed-rate-timer#kotlin.concurrent%24fixedRateTimer(kotlin.String?,%20kotlin.Boolean,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the start of the previous task and the start of the next one. ``` fun fixedRateTimer(     name: String? = null,     daemon: Boolean = false,     initialDelay: Long = 0.toLong(),     period: Long,     action: TimerTask.() -> Unit ): Timer ``` Creates a timer that executes the specified [action](fixed-rate-timer#kotlin.concurrent%24fixedRateTimer(kotlin.String?,%20kotlin.Boolean,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) periodically, starting at the specified [startAt](fixed-rate-timer#kotlin.concurrent%24fixedRateTimer(kotlin.String?,%20kotlin.Boolean,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/startAt) date and with the interval of [period](fixed-rate-timer#kotlin.concurrent%24fixedRateTimer(kotlin.String?,%20kotlin.Boolean,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the start of the previous task and the start of the next one. ``` fun fixedRateTimer(     name: String? = null,     daemon: Boolean = false,     startAt: Date,     period: Long,     action: TimerTask.() -> Unit ): Timer ``` **Platform and version requirements:** JVM (1.0) #### <thread> Creates a thread that runs the specified [block](thread#kotlin.concurrent%24thread(kotlin.Boolean,%20kotlin.Boolean,%20java.lang.ClassLoader?,%20kotlin.String?,%20kotlin.Int,%20kotlin.Function0((kotlin.Unit)))/block) of code. ``` fun thread(     start: Boolean = true,     isDaemon: Boolean = false,     contextClassLoader: ClassLoader? = null,     name: String? = null,     priority: Int = -1,     block: () -> Unit ): Thread ``` **Platform and version requirements:** JVM (1.0) #### <timer> Creates a timer that executes the specified [action](timer#kotlin.concurrent%24timer(kotlin.String?,%20kotlin.Boolean,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) periodically, starting after the specified [initialDelay](timer#kotlin.concurrent%24timer(kotlin.String?,%20kotlin.Boolean,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/initialDelay) (expressed in milliseconds) and with the interval of [period](timer#kotlin.concurrent%24timer(kotlin.String?,%20kotlin.Boolean,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the end of the previous task and the start of the next one. ``` fun timer(     name: String? = null,     daemon: Boolean = false,     initialDelay: Long = 0.toLong(),     period: Long,     action: TimerTask.() -> Unit ): Timer ``` Creates a timer that executes the specified [action](timer#kotlin.concurrent%24timer(kotlin.String?,%20kotlin.Boolean,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) periodically, starting at the specified [startAt](timer#kotlin.concurrent%24timer(kotlin.String?,%20kotlin.Boolean,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/startAt) date and with the interval of [period](timer#kotlin.concurrent%24timer(kotlin.String?,%20kotlin.Boolean,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the end of the previous task and the start of the next one. ``` fun timer(     name: String? = null,     daemon: Boolean = false,     startAt: Date,     period: Long,     action: TimerTask.() -> Unit ): Timer ``` **Platform and version requirements:** JVM (1.0) #### [timerTask](timer-task) Wraps the specified [action](timer-task#kotlin.concurrent%24timerTask(kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) in a [TimerTask](https://docs.oracle.com/javase/8/docs/api/java/util/TimerTask.html). ``` fun timerTask(action: TimerTask.() -> Unit): TimerTask ```
programming_docs
kotlin timerTask timerTask ========= [kotlin-stdlib](../../../../../index) / [kotlin.concurrent](index) / [timerTask](timer-task) **Platform and version requirements:** JVM (1.0) ``` inline fun timerTask(     crossinline action: TimerTask.() -> Unit ): TimerTask ``` Wraps the specified [action](timer-task#kotlin.concurrent%24timerTask(kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) in a [TimerTask](https://docs.oracle.com/javase/8/docs/api/java/util/TimerTask.html). kotlin timer timer ===== [kotlin-stdlib](../../../../../index) / [kotlin.concurrent](index) / <timer> **Platform and version requirements:** JVM (1.0) ``` inline fun timer(     name: String? = null,     daemon: Boolean = false,     initialDelay: Long = 0.toLong(),     period: Long,     crossinline action: TimerTask.() -> Unit ): Timer ``` Creates a timer that executes the specified [action](timer#kotlin.concurrent%24timer(kotlin.String?,%20kotlin.Boolean,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) periodically, starting after the specified [initialDelay](timer#kotlin.concurrent%24timer(kotlin.String?,%20kotlin.Boolean,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/initialDelay) (expressed in milliseconds) and with the interval of [period](timer#kotlin.concurrent%24timer(kotlin.String?,%20kotlin.Boolean,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the end of the previous task and the start of the next one. Parameters ---------- `name` - the name to use for the thread which is running the timer. `daemon` - if `true`, the thread is started as a daemon thread (the VM will exit when only daemon threads are running). **Platform and version requirements:** JVM (1.0) ``` inline fun timer(     name: String? = null,     daemon: Boolean = false,     startAt: Date,     period: Long,     crossinline action: TimerTask.() -> Unit ): Timer ``` Creates a timer that executes the specified [action](timer#kotlin.concurrent%24timer(kotlin.String?,%20kotlin.Boolean,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) periodically, starting at the specified [startAt](timer#kotlin.concurrent%24timer(kotlin.String?,%20kotlin.Boolean,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/startAt) date and with the interval of [period](timer#kotlin.concurrent%24timer(kotlin.String?,%20kotlin.Boolean,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the end of the previous task and the start of the next one. Parameters ---------- `name` - the name to use for the thread which is running the timer. `daemon` - if `true`, the thread is started as a daemon thread (the VM will exit when only daemon threads are running). kotlin thread thread ====== [kotlin-stdlib](../../../../../index) / [kotlin.concurrent](index) / <thread> **Platform and version requirements:** JVM (1.0) ``` fun thread(     start: Boolean = true,     isDaemon: Boolean = false,     contextClassLoader: ClassLoader? = null,     name: String? = null,     priority: Int = -1,     block: () -> Unit ): Thread ``` Creates a thread that runs the specified [block](thread#kotlin.concurrent%24thread(kotlin.Boolean,%20kotlin.Boolean,%20java.lang.ClassLoader?,%20kotlin.String?,%20kotlin.Int,%20kotlin.Function0((kotlin.Unit)))/block) of code. Parameters ---------- `start` - if `true`, the thread is immediately started. `isDaemon` - if `true`, the thread is created as a daemon thread. The Java Virtual Machine exits when the only threads running are all daemon threads. `contextClassLoader` - the class loader to use for loading classes and resources in this thread. `name` - the name of the thread. `priority` - the priority of the thread. kotlin Extensions for java.util.concurrent.locks.Lock Extensions for java.util.concurrent.locks.Lock ============================================== [kotlin-stdlib](../../../../../../index) / [kotlin.concurrent](../index) / [java.util.concurrent.locks.Lock](index) **Platform and version requirements:** JVM (1.0) #### [withLock](with-lock) Executes the given [action](with-lock#kotlin.concurrent%24withLock(java.util.concurrent.locks.Lock,%20kotlin.Function0((kotlin.concurrent.withLock.T)))/action) under this lock. ``` fun <T> Lock.withLock(action: () -> T): T ``` kotlin withLock withLock ======== [kotlin-stdlib](../../../../../../index) / [kotlin.concurrent](../index) / [java.util.concurrent.locks.Lock](index) / [withLock](with-lock) **Platform and version requirements:** JVM (1.0) ``` inline fun <T> Lock.withLock(action: () -> T): T ``` Executes the given [action](with-lock#kotlin.concurrent%24withLock(java.util.concurrent.locks.Lock,%20kotlin.Function0((kotlin.concurrent.withLock.T)))/action) under this lock. **Return** the return value of the action. kotlin Extensions for java.lang.ThreadLocal Extensions for java.lang.ThreadLocal ==================================== [kotlin-stdlib](../../../../../../index) / [kotlin.concurrent](../index) / [java.lang.ThreadLocal](index) **Platform and version requirements:** JVM (1.0) #### [getOrSet](get-or-set) Gets the value in the current thread's copy of this thread-local variable or replaces the value with the result of calling [default](get-or-set#kotlin.concurrent%24getOrSet(java.lang.ThreadLocal((kotlin.concurrent.getOrSet.T)),%20kotlin.Function0((kotlin.concurrent.getOrSet.T)))/default) function in case if that value was `null`. ``` fun <T : Any> ThreadLocal<T>.getOrSet(default: () -> T): T ``` kotlin getOrSet getOrSet ======== [kotlin-stdlib](../../../../../../index) / [kotlin.concurrent](../index) / [java.lang.ThreadLocal](index) / [getOrSet](get-or-set) **Platform and version requirements:** JVM (1.0) ``` inline fun <T : Any> ThreadLocal<T>.getOrSet(     default: () -> T ): T ``` Gets the value in the current thread's copy of this thread-local variable or replaces the value with the result of calling [default](get-or-set#kotlin.concurrent%24getOrSet(java.lang.ThreadLocal((kotlin.concurrent.getOrSet.T)),%20kotlin.Function0((kotlin.concurrent.getOrSet.T)))/default) function in case if that value was `null`. If the variable has no value for the current thread, it is first initialized to the value returned by an invocation of the [ThreadLocal.initialValue](https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html#initialValue--) method. Then if it is still `null`, the provided [default](get-or-set#kotlin.concurrent%24getOrSet(java.lang.ThreadLocal((kotlin.concurrent.getOrSet.T)),%20kotlin.Function0((kotlin.concurrent.getOrSet.T)))/default) function is called and its result is stored for the current thread and then returned. kotlin Extensions for java.util.Timer Extensions for java.util.Timer ============================== [kotlin-stdlib](../../../../../../index) / [kotlin.concurrent](../index) / [java.util.Timer](index) **Platform and version requirements:** JVM (1.0) #### <schedule> Schedules an [action](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) to be executed after the specified [delay](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/delay) (expressed in milliseconds). ``` fun Timer.schedule(     delay: Long,     action: TimerTask.() -> Unit ): TimerTask ``` Schedules an [action](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20java.util.Date,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) to be executed at the specified [time](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20java.util.Date,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/time). ``` fun Timer.schedule(     time: Date,     action: TimerTask.() -> Unit ): TimerTask ``` Schedules an [action](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) to be executed periodically, starting after the specified [delay](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/delay) (expressed in milliseconds) and with the interval of [period](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the end of the previous task and the start of the next one. ``` fun Timer.schedule(     delay: Long,     period: Long,     action: TimerTask.() -> Unit ): TimerTask ``` Schedules an [action](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) to be executed periodically, starting at the specified [time](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/time) and with the interval of [period](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the end of the previous task and the start of the next one. ``` fun Timer.schedule(     time: Date,     period: Long,     action: TimerTask.() -> Unit ): TimerTask ``` **Platform and version requirements:** JVM (1.0) #### [scheduleAtFixedRate](schedule-at-fixed-rate) Schedules an [action](schedule-at-fixed-rate#kotlin.concurrent%24scheduleAtFixedRate(java.util.Timer,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) to be executed periodically, starting after the specified [delay](schedule-at-fixed-rate#kotlin.concurrent%24scheduleAtFixedRate(java.util.Timer,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/delay) (expressed in milliseconds) and with the interval of [period](schedule-at-fixed-rate#kotlin.concurrent%24scheduleAtFixedRate(java.util.Timer,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the start of the previous task and the start of the next one. ``` fun Timer.scheduleAtFixedRate(     delay: Long,     period: Long,     action: TimerTask.() -> Unit ): TimerTask ``` Schedules an [action](schedule-at-fixed-rate#kotlin.concurrent%24scheduleAtFixedRate(java.util.Timer,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) to be executed periodically, starting at the specified [time](schedule-at-fixed-rate#kotlin.concurrent%24scheduleAtFixedRate(java.util.Timer,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/time) and with the interval of [period](schedule-at-fixed-rate#kotlin.concurrent%24scheduleAtFixedRate(java.util.Timer,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the start of the previous task and the start of the next one. ``` fun Timer.scheduleAtFixedRate(     time: Date,     period: Long,     action: TimerTask.() -> Unit ): TimerTask ``` kotlin schedule schedule ======== [kotlin-stdlib](../../../../../../index) / [kotlin.concurrent](../index) / [java.util.Timer](index) / <schedule> **Platform and version requirements:** JVM (1.0) ``` inline fun Timer.schedule(     delay: Long,     crossinline action: TimerTask.() -> Unit ): TimerTask ``` Schedules an [action](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) to be executed after the specified [delay](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/delay) (expressed in milliseconds). **Platform and version requirements:** JVM (1.0) ``` inline fun Timer.schedule(     time: Date,     crossinline action: TimerTask.() -> Unit ): TimerTask ``` Schedules an [action](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20java.util.Date,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) to be executed at the specified [time](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20java.util.Date,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/time). **Platform and version requirements:** JVM (1.0) ``` inline fun Timer.schedule(     delay: Long,     period: Long,     crossinline action: TimerTask.() -> Unit ): TimerTask ``` Schedules an [action](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) to be executed periodically, starting after the specified [delay](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/delay) (expressed in milliseconds) and with the interval of [period](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the end of the previous task and the start of the next one. **Platform and version requirements:** JVM (1.0) ``` inline fun Timer.schedule(     time: Date,     period: Long,     crossinline action: TimerTask.() -> Unit ): TimerTask ``` Schedules an [action](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) to be executed periodically, starting at the specified [time](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/time) and with the interval of [period](schedule#kotlin.concurrent%24schedule(java.util.Timer,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the end of the previous task and the start of the next one. kotlin scheduleAtFixedRate scheduleAtFixedRate =================== [kotlin-stdlib](../../../../../../index) / [kotlin.concurrent](../index) / [java.util.Timer](index) / [scheduleAtFixedRate](schedule-at-fixed-rate) **Platform and version requirements:** JVM (1.0) ``` inline fun Timer.scheduleAtFixedRate(     delay: Long,     period: Long,     crossinline action: TimerTask.() -> Unit ): TimerTask ``` Schedules an [action](schedule-at-fixed-rate#kotlin.concurrent%24scheduleAtFixedRate(java.util.Timer,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) to be executed periodically, starting after the specified [delay](schedule-at-fixed-rate#kotlin.concurrent%24scheduleAtFixedRate(java.util.Timer,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/delay) (expressed in milliseconds) and with the interval of [period](schedule-at-fixed-rate#kotlin.concurrent%24scheduleAtFixedRate(java.util.Timer,%20kotlin.Long,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the start of the previous task and the start of the next one. **Platform and version requirements:** JVM (1.0) ``` inline fun Timer.scheduleAtFixedRate(     time: Date,     period: Long,     crossinline action: TimerTask.() -> Unit ): TimerTask ``` Schedules an [action](schedule-at-fixed-rate#kotlin.concurrent%24scheduleAtFixedRate(java.util.Timer,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/action) to be executed periodically, starting at the specified [time](schedule-at-fixed-rate#kotlin.concurrent%24scheduleAtFixedRate(java.util.Timer,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/time) and with the interval of [period](schedule-at-fixed-rate#kotlin.concurrent%24scheduleAtFixedRate(java.util.Timer,%20java.util.Date,%20kotlin.Long,%20kotlin.Function1((java.util.TimerTask,%20kotlin.Unit)))/period) milliseconds between the start of the previous task and the start of the next one. kotlin read read ==== [kotlin-stdlib](../../../../../../index) / [kotlin.concurrent](../index) / [java.util.concurrent.locks.ReentrantReadWriteLock](index) / <read> **Platform and version requirements:** JVM (1.0) ``` inline fun <T> ReentrantReadWriteLock.read(     action: () -> T ): T ``` Executes the given [action](read#kotlin.concurrent%24read(java.util.concurrent.locks.ReentrantReadWriteLock,%20kotlin.Function0((kotlin.concurrent.read.T)))/action) under the read lock of this lock. **Return** the return value of the action. kotlin Extensions for java.util.concurrent.locks.ReentrantReadWriteLock Extensions for java.util.concurrent.locks.ReentrantReadWriteLock ================================================================ [kotlin-stdlib](../../../../../../index) / [kotlin.concurrent](../index) / [java.util.concurrent.locks.ReentrantReadWriteLock](index) **Platform and version requirements:** JVM (1.0) #### <read> Executes the given [action](read#kotlin.concurrent%24read(java.util.concurrent.locks.ReentrantReadWriteLock,%20kotlin.Function0((kotlin.concurrent.read.T)))/action) under the read lock of this lock. ``` fun <T> ReentrantReadWriteLock.read(action: () -> T): T ``` **Platform and version requirements:** JVM (1.0) #### <write> Executes the given [action](write#kotlin.concurrent%24write(java.util.concurrent.locks.ReentrantReadWriteLock,%20kotlin.Function0((kotlin.concurrent.write.T)))/action) under the write lock of this lock. ``` fun <T> ReentrantReadWriteLock.write(action: () -> T): T ``` kotlin write write ===== [kotlin-stdlib](../../../../../../index) / [kotlin.concurrent](../index) / [java.util.concurrent.locks.ReentrantReadWriteLock](index) / <write> **Platform and version requirements:** JVM (1.0) ``` inline fun <T> ReentrantReadWriteLock.write(     action: () -> T ): T ``` Executes the given [action](write#kotlin.concurrent%24write(java.util.concurrent.locks.ReentrantReadWriteLock,%20kotlin.Function0((kotlin.concurrent.write.T)))/action) under the write lock of this lock. The function does upgrade from read to write lock if needed, but this upgrade is not atomic as such upgrade is not supported by [ReentrantReadWriteLock](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html). In order to do such upgrade this function first releases all read locks held by this thread, then acquires write lock, and after releasing it acquires read locks back again. Therefore if the [action](write#kotlin.concurrent%24write(java.util.concurrent.locks.ReentrantReadWriteLock,%20kotlin.Function0((kotlin.concurrent.write.T)))/action) inside write lock has been initiated by checking some condition, the condition must be rechecked inside the [action](write#kotlin.concurrent%24write(java.util.concurrent.locks.ReentrantReadWriteLock,%20kotlin.Function0((kotlin.concurrent.write.T)))/action) to avoid possible races. **Return** the return value of the action. kotlin minutes minutes ======= [kotlin-stdlib](../../../../../index) / [kotlin.time](index) / <minutes> **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Int.minutes: Duration ``` **Deprecated:** Use 'Int.minutes' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of minutes. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Long.minutes: Duration ``` **Deprecated:** Use 'Long.minutes' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of minutes. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Double.minutes: Duration ``` **Deprecated:** Use 'Double.minutes' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of minutes. Exceptions ---------- `IllegalArgumentException` - if this [Double](../kotlin/-double/index#kotlin.Double) value is `NaN`.
programming_docs
kotlin nanoseconds nanoseconds =========== [kotlin-stdlib](../../../../../index) / [kotlin.time](index) / <nanoseconds> **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Int.nanoseconds: Duration ``` **Deprecated:** Use 'Int.nanoseconds' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of nanoseconds. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Long.nanoseconds: Duration ``` **Deprecated:** Use 'Long.nanoseconds' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of nanoseconds. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Double.nanoseconds: Duration ``` **Deprecated:** Use 'Double.nanoseconds' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of nanoseconds. Exceptions ---------- `IllegalArgumentException` - if this [Double](../kotlin/-double/index#kotlin.Double) value is `NaN`. kotlin Package kotlin.time Package kotlin.time =================== [kotlin-stdlib](../../../../../index) / [kotlin.time](index) API for representing [Duration](-duration/index) values and experimental API for measuring time intervals. Types ----- **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [AbstractDoubleTimeSource](-abstract-double-time-source/index) An abstract class used to implement time sources that return their readings as [Double](../kotlin/-double/index#kotlin.Double) values in the specified [unit](-abstract-double-time-source/unit). ``` abstract class AbstractDoubleTimeSource : WithComparableMarks ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [AbstractLongTimeSource](-abstract-long-time-source/index) An abstract class used to implement time sources that return their readings as [Long](../kotlin/-long/index#kotlin.Long) values in the specified [unit](-abstract-long-time-source/unit). ``` abstract class AbstractLongTimeSource : WithComparableMarks ``` **Platform and version requirements:** JVM (1.8), JS (1.8), Native (1.8) #### [ComparableTimeMark](-comparable-time-mark/index) A [TimeMark](-time-mark/index) that can be compared for difference with other time marks obtained from the same [TimeSource.WithComparableMarks](-time-source/-with-comparable-marks/index) time source. ``` interface ComparableTimeMark :      TimeMark,     Comparable<ComparableTimeMark> ``` **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) #### [Duration](-duration/index) Represents the amount of time one instant of time is away from another instant. ``` class Duration : Comparable<Duration> ``` **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) #### [DurationUnit](-duration-unit/index) The list of possible time measurement units, in which a duration can be expressed. ``` enum class DurationUnit ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [TestTimeSource](-test-time-source/index) A time source that has programmatically updatable readings. It is useful as a predictable source of time in tests. ``` class TestTimeSource : AbstractLongTimeSource ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [TimedValue](-timed-value/index) Data class representing a result of executing an action, along with the duration of elapsed time interval. ``` data class TimedValue<T> ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [TimeMark](-time-mark/index) Represents a time point notched on a particular [TimeSource](-time-source/index). Remains bound to the time source it was taken from and allows querying for the duration of time elapsed from that point (see the function [elapsedNow](-time-mark/elapsed-now)). ``` interface TimeMark ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [TimeSource](-time-source/index) A source of time for measuring time intervals. ``` interface TimeSource ``` Annotations ----------- **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [ExperimentalTime](-experimental-time/index) This annotation marks the experimental preview of the standard library API for measuring time and working with durations. ``` annotation class ExperimentalTime ``` Extensions for External Classes ------------------------------- **Platform and version requirements:** JVM (1.6), JRE8 (1.6) #### [java.time.Duration](java.time.-duration/index) **Platform and version requirements:** JVM (1.8) #### [java.util.concurrent.TimeUnit](java.util.concurrent.-time-unit/index) Properties ---------- **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### <days> Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of days. ``` val Int.days: Duration ``` Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of days. ``` val Long.days: Duration ``` Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of days. ``` val Double.days: Duration ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### <hours> Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of hours. ``` val Int.hours: Duration ``` Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of hours. ``` val Long.hours: Duration ``` Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of hours. ``` val Double.hours: Duration ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### <microseconds> Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of microseconds. ``` val Int.microseconds: Duration ``` Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of microseconds. ``` val Long.microseconds: Duration ``` Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of microseconds. ``` val Double.microseconds: Duration ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### <milliseconds> Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of milliseconds. ``` val Int.milliseconds: Duration ``` Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of milliseconds. ``` val Long.milliseconds: Duration ``` Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of milliseconds. ``` val Double.milliseconds: Duration ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### <minutes> Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of minutes. ``` val Int.minutes: Duration ``` Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of minutes. ``` val Long.minutes: Duration ``` Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of minutes. ``` val Double.minutes: Duration ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### <nanoseconds> Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of nanoseconds. ``` val Int.nanoseconds: Duration ``` Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of nanoseconds. ``` val Long.nanoseconds: Duration ``` Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of nanoseconds. ``` val Double.nanoseconds: Duration ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### <seconds> Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of seconds. ``` val Int.seconds: Duration ``` Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of seconds. ``` val Long.seconds: Duration ``` Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of seconds. ``` val Double.seconds: Duration ``` Functions --------- **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [measureTime](measure-time) Executes the given function [block](measure-time#kotlin.time%24measureTime(kotlin.Function0((kotlin.Unit)))/block) and returns the duration of elapsed time interval. ``` fun measureTime(block: () -> Unit): Duration ``` ``` fun TimeSource.measureTime(block: () -> Unit): Duration ``` ``` fun Monotonic.measureTime(block: () -> Unit): Duration ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [measureTimedValue](measure-timed-value) Executes the given function [block](measure-timed-value#kotlin.time%24measureTimedValue(kotlin.Function0((kotlin.time.measureTimedValue.T)))/block) and returns an instance of [TimedValue](-timed-value/index) class, containing both the result of the function execution and the duration of elapsed time interval. ``` fun <T> measureTimedValue(block: () -> T): TimedValue<T> ``` Executes the given [block](measure-timed-value#kotlin.time%24measureTimedValue(kotlin.time.TimeSource,%20kotlin.Function0((kotlin.time.measureTimedValue.T)))/block) and returns an instance of [TimedValue](-timed-value/index) class, containing both the result of function execution and the duration of elapsed time interval. ``` fun <T> TimeSource.measureTimedValue(     block: () -> T ): TimedValue<T> ``` ``` fun <T> Monotonic.measureTimedValue(     block: () -> T ): TimedValue<T> ``` **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) #### <times> Returns a duration whose value is the specified [duration](times#kotlin.time%24times(kotlin.Int,%20kotlin.time.Duration)/duration) value multiplied by this number. ``` operator fun Int.times(duration: Duration): Duration ``` ``` operator fun Double.times(duration: Duration): Duration ``` **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) #### [toDuration](to-duration) Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of the specified [unit](to-duration#kotlin.time%24toDuration(kotlin.Int,%20kotlin.time.DurationUnit)/unit). ``` fun Int.toDuration(unit: DurationUnit): Duration ``` Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of the specified [unit](to-duration#kotlin.time%24toDuration(kotlin.Long,%20kotlin.time.DurationUnit)/unit). ``` fun Long.toDuration(unit: DurationUnit): Duration ``` Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of the specified [unit](to-duration#kotlin.time%24toDuration(kotlin.Double,%20kotlin.time.DurationUnit)/unit). ``` fun Double.toDuration(unit: DurationUnit): Duration ``` **Platform and version requirements:** JVM (1.6), JRE8 (1.6) #### [toJavaDuration](to-java-duration) Converts kotlin.time.Duration value to [java.time.Duration](https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html) value. ``` fun Duration.toJavaDuration(): Duration ``` **Platform and version requirements:** JVM (1.8) #### [toTimeUnit](to-time-unit) Converts this [kotlin.time.DurationUnit](-duration-unit/index#kotlin.time.DurationUnit) enum value to the corresponding [java.util.concurrent.TimeUnit](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html) value. ``` fun DurationUnit.toTimeUnit(): TimeUnit ``` kotlin measureTimedValue measureTimedValue ================= [kotlin-stdlib](../../../../../index) / [kotlin.time](index) / [measureTimedValue](measure-timed-value) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime inline fun <T> measureTimedValue(     block: () -> T ): TimedValue<T> ``` Executes the given function [block](measure-timed-value#kotlin.time%24measureTimedValue(kotlin.Function0((kotlin.time.measureTimedValue.T)))/block) and returns an instance of [TimedValue](-timed-value/index) class, containing both the result of the function execution and the duration of elapsed time interval. The elapsed time is measured with [TimeSource.Monotonic](-time-source/-monotonic/index). **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime inline fun <T> TimeSource.measureTimedValue(     block: () -> T ): TimedValue<T> ``` Executes the given [block](measure-timed-value#kotlin.time%24measureTimedValue(kotlin.time.TimeSource,%20kotlin.Function0((kotlin.time.measureTimedValue.T)))/block) and returns an instance of [TimedValue](-timed-value/index) class, containing both the result of function execution and the duration of elapsed time interval. The elapsed time is measured with the specified `this` [TimeSource](-time-source/index) instance. **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) ``` @ExperimentalTime inline fun <T> Monotonic.measureTimedValue(     block: () -> T ): TimedValue<T> ``` Executes the given [block](measure-timed-value#kotlin.time%24measureTimedValue(kotlin.time.TimeSource.Monotonic,%20kotlin.Function0((kotlin.time.measureTimedValue.T)))/block) and returns an instance of [TimedValue](-timed-value/index) class, containing both the result of function execution and the duration of elapsed time interval. The elapsed time is measured with the specified `this` [TimeSource.Monotonic](-time-source/-monotonic/index) instance. kotlin hours hours ===== [kotlin-stdlib](../../../../../index) / [kotlin.time](index) / <hours> **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Int.hours: Duration ``` **Deprecated:** Use 'Int.hours' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of hours. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Long.hours: Duration ``` **Deprecated:** Use 'Long.hours' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of hours. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Double.hours: Duration ``` **Deprecated:** Use 'Double.hours' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of hours. Exceptions ---------- `IllegalArgumentException` - if this [Double](../kotlin/-double/index#kotlin.Double) value is `NaN`. kotlin milliseconds milliseconds ============ [kotlin-stdlib](../../../../../index) / [kotlin.time](index) / <milliseconds> **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Int.milliseconds: Duration ``` **Deprecated:** Use 'Int.milliseconds' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of milliseconds. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Long.milliseconds: Duration ``` **Deprecated:** Use 'Long.milliseconds' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of milliseconds. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Double.milliseconds: Duration ``` **Deprecated:** Use 'Double.milliseconds' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of milliseconds. Exceptions ---------- `IllegalArgumentException` - if this [Double](../kotlin/-double/index#kotlin.Double) value is `NaN`. kotlin measureTime measureTime =========== [kotlin-stdlib](../../../../../index) / [kotlin.time](index) / [measureTime](measure-time) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime inline fun measureTime(     block: () -> Unit ): Duration ``` Executes the given function [block](measure-time#kotlin.time%24measureTime(kotlin.Function0((kotlin.Unit)))/block) and returns the duration of elapsed time interval. The elapsed time is measured with [TimeSource.Monotonic](-time-source/-monotonic/index). **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime inline fun TimeSource.measureTime(     block: () -> Unit ): Duration ``` Executes the given function [block](measure-time#kotlin.time%24measureTime(kotlin.time.TimeSource,%20kotlin.Function0((kotlin.Unit)))/block) and returns the duration of elapsed time interval. The elapsed time is measured with the specified `this` [TimeSource](-time-source/index) instance. **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) ``` @ExperimentalTime inline fun Monotonic.measureTime(     block: () -> Unit ): Duration ``` Executes the given function [block](measure-time#kotlin.time%24measureTime(kotlin.time.TimeSource.Monotonic,%20kotlin.Function0((kotlin.Unit)))/block) and returns the duration of elapsed time interval. The elapsed time is measured with the specified `this` [TimeSource.Monotonic](-time-source/-monotonic/index) instance. kotlin toJavaDuration toJavaDuration ============== [kotlin-stdlib](../../../../../index) / [kotlin.time](index) / [toJavaDuration](to-java-duration) **Platform and version requirements:** JVM (1.6), JRE8 (1.6) ``` fun Duration.toJavaDuration(): Duration ``` Converts kotlin.time.Duration value to [java.time.Duration](https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html) value. Durations greater than Long.MAX\_VALUE seconds are cut to that value. kotlin microseconds microseconds ============ [kotlin-stdlib](../../../../../index) / [kotlin.time](index) / <microseconds> **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Int.microseconds: Duration ``` **Deprecated:** Use 'Int.microseconds' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of microseconds. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Long.microseconds: Duration ``` **Deprecated:** Use 'Long.microseconds' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of microseconds. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Double.microseconds: Duration ``` **Deprecated:** Use 'Double.microseconds' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of microseconds. Exceptions ---------- `IllegalArgumentException` - if this [Double](../kotlin/-double/index#kotlin.Double) value is `NaN`.
programming_docs
kotlin days days ==== [kotlin-stdlib](../../../../../index) / [kotlin.time](index) / <days> **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Int.days: Duration ``` **Deprecated:** Use 'Int.days' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of days. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Long.days: Duration ``` **Deprecated:** Use 'Long.days' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of days. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Double.days: Duration ``` **Deprecated:** Use 'Double.days' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of days. Exceptions ---------- `IllegalArgumentException` - if this [Double](../kotlin/-double/index#kotlin.Double) value is `NaN`. kotlin times times ===== [kotlin-stdlib](../../../../../index) / [kotlin.time](index) / <times> **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) ``` operator fun Int.times(duration: Duration): Duration ``` Returns a duration whose value is the specified [duration](times#kotlin.time%24times(kotlin.Int,%20kotlin.time.Duration)/duration) value multiplied by this number. **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) ``` operator fun Double.times(duration: Duration): Duration ``` Returns a duration whose value is the specified [duration](times#kotlin.time%24times(kotlin.Double,%20kotlin.time.Duration)/duration) value multiplied by this number. The operation may involve rounding when the result cannot be represented exactly with a [Double](../kotlin/-double/index#kotlin.Double) number. Exceptions ---------- `IllegalArgumentException` - if the operation results in a `NaN` value. kotlin toDuration toDuration ========== [kotlin-stdlib](../../../../../index) / [kotlin.time](index) / [toDuration](to-duration) **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) ``` fun Int.toDuration(unit: DurationUnit): Duration ``` Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of the specified [unit](to-duration#kotlin.time%24toDuration(kotlin.Int,%20kotlin.time.DurationUnit)/unit). **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) ``` fun Long.toDuration(unit: DurationUnit): Duration ``` Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of the specified [unit](to-duration#kotlin.time%24toDuration(kotlin.Long,%20kotlin.time.DurationUnit)/unit). **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) ``` fun Double.toDuration(unit: DurationUnit): Duration ``` Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of the specified [unit](to-duration#kotlin.time%24toDuration(kotlin.Double,%20kotlin.time.DurationUnit)/unit). Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds. Exceptions ---------- `IllegalArgumentException` - if this `Double` value is `NaN`. kotlin toTimeUnit toTimeUnit ========== [kotlin-stdlib](../../../../../index) / [kotlin.time](index) / [toTimeUnit](to-time-unit) **Platform and version requirements:** JVM (1.8) ``` fun DurationUnit.toTimeUnit(): TimeUnit ``` Converts this [kotlin.time.DurationUnit](-duration-unit/index#kotlin.time.DurationUnit) enum value to the corresponding [java.util.concurrent.TimeUnit](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html) value. kotlin seconds seconds ======= [kotlin-stdlib](../../../../../index) / [kotlin.time](index) / <seconds> **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Int.seconds: Duration ``` **Deprecated:** Use 'Int.seconds' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Int](../kotlin/-int/index#kotlin.Int) number of seconds. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Long.seconds: Duration ``` **Deprecated:** Use 'Long.seconds' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Long](../kotlin/-long/index#kotlin.Long) number of seconds. **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val Double.seconds: Duration ``` **Deprecated:** Use 'Double.seconds' extension property from Duration.Companion instead. Returns a [Duration](-duration/index) equal to this [Double](../kotlin/-double/index#kotlin.Double) number of seconds. Exceptions ---------- `IllegalArgumentException` - if this [Double](../kotlin/-double/index#kotlin.Double) value is `NaN`. kotlin read read ==== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [AbstractDoubleTimeSource](index) / <read> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` protected abstract fun read(): Double ``` This protected method should be overridden to return the current reading of the time source expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number in the unit specified by the <unit> property. kotlin AbstractDoubleTimeSource AbstractDoubleTimeSource ======================== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [AbstractDoubleTimeSource](index) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime abstract class AbstractDoubleTimeSource :      WithComparableMarks ``` **Deprecated:** Using AbstractDoubleTimeSource is no longer recommended, use AbstractLongTimeSource instead. An abstract class used to implement time sources that return their readings as [Double](../../kotlin/-double/index#kotlin.Double) values in the specified <unit>. Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [<init>](-init-) An abstract class used to implement time sources that return their readings as [Double](../../kotlin/-double/index#kotlin.Double) values in the specified <unit>. ``` AbstractDoubleTimeSource(unit: DurationUnit) ``` Properties ---------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <unit> The unit in which this time source's readings are expressed. ``` val unit: DurationUnit ``` Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [markNow](mark-now) Marks a point in time on this time source. ``` open fun markNow(): ComparableTimeMark ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <read> This protected method should be overridden to return the current reading of the time source expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number in the unit specified by the <unit> property. ``` abstract fun read(): Double ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [measureTime](../measure-time) Executes the given function [block](../measure-time#kotlin.time%24measureTime(kotlin.time.TimeSource,%20kotlin.Function0((kotlin.Unit)))/block) and returns the duration of elapsed time interval. ``` fun TimeSource.measureTime(block: () -> Unit): Duration ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [measureTimedValue](../measure-timed-value) Executes the given [block](../measure-timed-value#kotlin.time%24measureTimedValue(kotlin.time.TimeSource,%20kotlin.Function0((kotlin.time.measureTimedValue.T)))/block) and returns an instance of [TimedValue](../-timed-value/index) class, containing both the result of function execution and the duration of elapsed time interval. ``` fun <T> TimeSource.measureTimedValue(     block: () -> T ): TimedValue<T> ``` kotlin unit unit ==== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [AbstractDoubleTimeSource](index) / <unit> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` protected val unit: DurationUnit ``` The unit in which this time source's readings are expressed. Property -------- `unit` - The unit in which this time source's readings are expressed. kotlin markNow markNow ======= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [AbstractDoubleTimeSource](index) / [markNow](mark-now) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun markNow(): ComparableTimeMark ``` Marks a point in time on this time source. The returned [TimeMark](../-time-mark/index) instance encapsulates the captured time point and allows querying the duration of time interval [elapsed](../-time-mark/elapsed-now) from that point. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [AbstractDoubleTimeSource](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` AbstractDoubleTimeSource(unit: DurationUnit) ``` An abstract class used to implement time sources that return their readings as [Double](../../kotlin/-double/index#kotlin.Double) values in the specified <unit>. kotlin duration duration ======== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TimedValue](index) / <duration> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` val duration: Duration ``` the time elapsed to execute the action. Property -------- `duration` - the time elapsed to execute the action. kotlin TimedValue TimedValue ========== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TimedValue](index) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime data class TimedValue<T> ``` Data class representing a result of executing an action, along with the duration of elapsed time interval. Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [<init>](-init-) Data class representing a result of executing an action, along with the duration of elapsed time interval. ``` TimedValue(value: T, duration: Duration) ``` Properties ---------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <duration> the time elapsed to execute the action. ``` val duration: Duration ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <value> the result of the action. ``` val value: T ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TimedValue](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` TimedValue(value: T, duration: Duration) ``` Data class representing a result of executing an action, along with the duration of elapsed time interval. kotlin value value ===== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TimedValue](index) / <value> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` val value: T ``` the result of the action. Property -------- `value` - the result of the action. kotlin SECONDS SECONDS ======= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [DurationUnit](index) / [SECONDS](-s-e-c-o-n-d-s) **Platform and version requirements:** JVM (1.0), JS (1.1), Native (1.3) ``` SECONDS ``` Time unit representing one second. kotlin DurationUnit DurationUnit ============ [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [DurationUnit](index) **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) ``` enum class DurationUnit ``` The list of possible time measurement units, in which a duration can be expressed. The smallest time unit is [NANOSECONDS](-n-a-n-o-s-e-c-o-n-d-s#kotlin.time.DurationUnit.NANOSECONDS) and the largest is [DAYS](-d-a-y-s#kotlin.time.DurationUnit.DAYS), which corresponds to exactly 24 [HOURS](-h-o-u-r-s#kotlin.time.DurationUnit.HOURS). Enum Values ----------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [NANOSECONDS](-n-a-n-o-s-e-c-o-n-d-s) Time unit representing one nanosecond, which is 1/1000 of a microsecond. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [MICROSECONDS](-m-i-c-r-o-s-e-c-o-n-d-s) Time unit representing one microsecond, which is 1/1000 of a millisecond. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [MILLISECONDS](-m-i-l-l-i-s-e-c-o-n-d-s) Time unit representing one millisecond, which is 1/1000 of a second. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [SECONDS](-s-e-c-o-n-d-s) Time unit representing one second. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [MINUTES](-m-i-n-u-t-e-s) Time unit representing one minute. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [HOURS](-h-o-u-r-s) Time unit representing one hour. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [DAYS](-d-a-y-s) Time unit representing one day, which is always equal to 24 hours. Extension Properties -------------------- **Platform and version requirements:** JVM (1.7) #### [declaringJavaClass](../../kotlin.jvm/declaring-java-class) Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance of the enum the given constant belongs to. ``` val <E : Enum<E>> Enum<E>.declaringJavaClass: Class<E> ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceAtLeast](../../kotlin.ranges/coerce-at-least) Ensures that this value is not less than the specified [minimumValue](../../kotlin.ranges/coerce-at-least#kotlin.ranges%24coerceAtLeast(kotlin.ranges.coerceAtLeast.T,%20kotlin.ranges.coerceAtLeast.T)/minimumValue). ``` fun <T : Comparable<T>> T.coerceAtLeast(minimumValue: T): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceAtMost](../../kotlin.ranges/coerce-at-most) Ensures that this value is not greater than the specified [maximumValue](../../kotlin.ranges/coerce-at-most#kotlin.ranges%24coerceAtMost(kotlin.ranges.coerceAtMost.T,%20kotlin.ranges.coerceAtMost.T)/maximumValue). ``` fun <T : Comparable<T>> T.coerceAtMost(maximumValue: T): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceIn](../../kotlin.ranges/coerce-in) Ensures that this value lies in the specified range [minimumValue](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.coerceIn.T?,%20kotlin.ranges.coerceIn.T?)/minimumValue)..[maximumValue](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.coerceIn.T?,%20kotlin.ranges.coerceIn.T?)/maximumValue). ``` fun <T : Comparable<T>> T.coerceIn(     minimumValue: T?,     maximumValue: T? ): T ``` Ensures that this value lies in the specified [range](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.ClosedFloatingPointRange((kotlin.ranges.coerceIn.T)))/range). ``` fun <T : Comparable<T>> T.coerceIn(     range: ClosedFloatingPointRange<T> ): T ``` ``` fun <T : Comparable<T>> T.coerceIn(range: ClosedRange<T>): T ``` **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) #### [compareTo](../../kotlin/compare-to) Compares this object with the specified object for order. Returns zero if this object is equal to the specified [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other) object, a negative number if it's less than [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other), or a positive number if it's greater than [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other). ``` infix fun <T> Comparable<T>.compareTo(other: T): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [rangeTo](../../kotlin.ranges/range-to) Creates a range from this [Comparable](../../kotlin/-comparable/index#kotlin.Comparable) value to the specified [that](../../kotlin.ranges/range-to#kotlin.ranges%24rangeTo(kotlin.ranges.rangeTo.T,%20kotlin.ranges.rangeTo.T)/that) value. ``` operator fun <T : Comparable<T>> T.rangeTo(     that: T ): ClosedRange<T> ``` **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) #### [rangeUntil](../../kotlin.ranges/range-until) Creates an open-ended range from this [Comparable](../../kotlin/-comparable/index#kotlin.Comparable) value to the specified [that](../../kotlin.ranges/range-until#kotlin.ranges%24rangeUntil(kotlin.ranges.rangeUntil.T,%20kotlin.ranges.rangeUntil.T)/that) value. ``` operator fun <T : Comparable<T>> T.rangeUntil(     that: T ): OpenEndRange<T> ``` **Platform and version requirements:** JVM (1.8) #### [toTimeUnit](../to-time-unit) Converts this [kotlin.time.DurationUnit](index#kotlin.time.DurationUnit) enum value to the corresponding [java.util.concurrent.TimeUnit](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html) value. ``` fun DurationUnit.toTimeUnit(): TimeUnit ``` Inheritors ---------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [DAYS](-d-a-y-s) Time unit representing one day, which is always equal to 24 hours. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [HOURS](-h-o-u-r-s) Time unit representing one hour. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [MICROSECONDS](-m-i-c-r-o-s-e-c-o-n-d-s) Time unit representing one microsecond, which is 1/1000 of a millisecond. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [MILLISECONDS](-m-i-l-l-i-s-e-c-o-n-d-s) Time unit representing one millisecond, which is 1/1000 of a second. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [MINUTES](-m-i-n-u-t-e-s) Time unit representing one minute. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [NANOSECONDS](-n-a-n-o-s-e-c-o-n-d-s) Time unit representing one nanosecond, which is 1/1000 of a microsecond. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [SECONDS](-s-e-c-o-n-d-s) Time unit representing one second. kotlin NANOSECONDS NANOSECONDS =========== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [DurationUnit](index) / [NANOSECONDS](-n-a-n-o-s-e-c-o-n-d-s) **Platform and version requirements:** JVM (1.0), JS (1.1), Native (1.3) ``` NANOSECONDS ``` Time unit representing one nanosecond, which is 1/1000 of a microsecond.
programming_docs
kotlin HOURS HOURS ===== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [DurationUnit](index) / [HOURS](-h-o-u-r-s) **Platform and version requirements:** JVM (1.0), JS (1.1), Native (1.3) ``` HOURS ``` Time unit representing one hour. kotlin DAYS DAYS ==== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [DurationUnit](index) / [DAYS](-d-a-y-s) **Platform and version requirements:** JVM (1.0), JS (1.1), Native (1.3) ``` DAYS ``` Time unit representing one day, which is always equal to 24 hours. kotlin MICROSECONDS MICROSECONDS ============ [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [DurationUnit](index) / [MICROSECONDS](-m-i-c-r-o-s-e-c-o-n-d-s) **Platform and version requirements:** JVM (1.0), JS (1.1), Native (1.3) ``` MICROSECONDS ``` Time unit representing one microsecond, which is 1/1000 of a millisecond. kotlin MILLISECONDS MILLISECONDS ============ [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [DurationUnit](index) / [MILLISECONDS](-m-i-l-l-i-s-e-c-o-n-d-s) **Platform and version requirements:** JVM (1.0), JS (1.1), Native (1.3) ``` MILLISECONDS ``` Time unit representing one millisecond, which is 1/1000 of a second. kotlin MINUTES MINUTES ======= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [DurationUnit](index) / [MINUTES](-m-i-n-u-t-e-s) **Platform and version requirements:** JVM (1.0), JS (1.1), Native (1.3) ``` MINUTES ``` Time unit representing one minute. kotlin minutes minutes ======= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / <minutes> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Int.minutes: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of minutes. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Long.minutes: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of minutes. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Double.minutes: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of minutes. Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds. Exceptions ---------- `IllegalArgumentException` - if this [Double](../../kotlin/-double/index#kotlin.Double) value is `NaN`. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun minutes(     value: Int ): Duration ``` **Deprecated:** Use 'Int.minutes' extension property from Duration.Companion instead. ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun minutes(     value: Long ): Duration ``` **Deprecated:** Use 'Long.minutes' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](minutes#kotlin.time.Duration.Companion%24minutes(kotlin.Int)/value) number of minutes. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun minutes(     value: Double ): Duration ``` **Deprecated:** Use 'Double.minutes' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](minutes#kotlin.time.Duration.Companion%24minutes(kotlin.Double)/value) number of minutes. Exceptions ---------- `IllegalArgumentException` - if the provided `Double` [value](minutes#kotlin.time.Duration.Companion%24minutes(kotlin.Double)/value) is `NaN`. kotlin inMicroseconds inMicroseconds ============== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inMicroseconds](in-microseconds) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val inMicroseconds: Double ``` **Deprecated:** Use inWholeMicroseconds property instead or convert toDouble(MICROSECONDS) if a double value is required. The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of microseconds. kotlin toInt toInt ===== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [toInt](to-int) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun toInt(unit: DurationUnit): Int ``` Returns the value of this duration expressed as an [Int](../../kotlin/-int/index#kotlin.Int) number of the specified [unit](to-int#kotlin.time.Duration%24toInt(kotlin.time.DurationUnit)/unit). If the result doesn't fit in the range of [Int](../../kotlin/-int/index#kotlin.Int) type, it is coerced into that range: * [Int.MIN\_VALUE](../../kotlin/-int/-m-i-n_-v-a-l-u-e#kotlin.Int.Companion%24MIN_VALUE) is returned if it's less than `Int.MIN_VALUE`, * [Int.MAX\_VALUE](../../kotlin/-int/-m-a-x_-v-a-l-u-e#kotlin.Int.Companion%24MAX_VALUE) is returned if it's greater than `Int.MAX_VALUE`. An infinite duration value is converted either to [Int.MAX\_VALUE](../../kotlin/-int/-m-a-x_-v-a-l-u-e#kotlin.Int.Companion%24MAX_VALUE) or [Int.MIN\_VALUE](../../kotlin/-int/-m-i-n_-v-a-l-u-e#kotlin.Int.Companion%24MIN_VALUE) depending on its sign. kotlin isFinite isFinite ======== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [isFinite](is-finite) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun isFinite(): Boolean ``` Returns true, if the duration value is finite. kotlin inNanoseconds inNanoseconds ============= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inNanoseconds](in-nanoseconds) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val inNanoseconds: Double ``` **Deprecated:** Use inWholeNanoseconds property instead or convert toDouble(NANOSECONDS) if a double value is required. The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of nanoseconds. kotlin inWholeMicroseconds inWholeMicroseconds =================== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inWholeMicroseconds](in-whole-microseconds) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` val inWholeMicroseconds: Long ``` The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of microseconds. If the result doesn't fit in the range of [Long](../../kotlin/-long/index#kotlin.Long) type, it is coerced into that range: * [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) is returned if it's less than `Long.MIN_VALUE`, * [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) is returned if it's greater than `Long.MAX_VALUE`. An infinite duration value is converted either to [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) or [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) depending on its sign. kotlin inWholeNanoseconds inWholeNanoseconds ================== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inWholeNanoseconds](in-whole-nanoseconds) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` val inWholeNanoseconds: Long ``` The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of nanoseconds. If the result doesn't fit in the range of [Long](../../kotlin/-long/index#kotlin.Long) type, it is coerced into that range: * [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) is returned if it's less than `Long.MIN_VALUE`, * [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) is returned if it's greater than `Long.MAX_VALUE`. An infinite duration value is converted either to [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) or [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) depending on its sign. kotlin inWholeSeconds inWholeSeconds ============== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inWholeSeconds](in-whole-seconds) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` val inWholeSeconds: Long ``` The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of seconds. An infinite duration value is converted either to [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) or [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) depending on its sign. kotlin nanoseconds nanoseconds =========== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / <nanoseconds> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Int.nanoseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of nanoseconds. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Long.nanoseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of nanoseconds. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Double.nanoseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of nanoseconds. Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds. Exceptions ---------- `IllegalArgumentException` - if this [Double](../../kotlin/-double/index#kotlin.Double) value is `NaN`. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun nanoseconds(     value: Int ): Duration ``` **Deprecated:** Use 'Int.nanoseconds' extension property from Duration.Companion instead. ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun nanoseconds(     value: Long ): Duration ``` **Deprecated:** Use 'Long.nanoseconds' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](nanoseconds#kotlin.time.Duration.Companion%24nanoseconds(kotlin.Int)/value) number of nanoseconds. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun nanoseconds(     value: Double ): Duration ``` **Deprecated:** Use 'Double.nanoseconds' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](nanoseconds#kotlin.time.Duration.Companion%24nanoseconds(kotlin.Double)/value) number of nanoseconds. Exceptions ---------- `IllegalArgumentException` - if the provided `Double` [value](nanoseconds#kotlin.time.Duration.Companion%24nanoseconds(kotlin.Double)/value) is `NaN`. kotlin Duration Duration ======== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) ``` inline class Duration : Comparable<Duration> ``` Represents the amount of time one instant of time is away from another instant. A negative duration is possible in a situation when the second instant is earlier than the first one. The type can store duration values up to ±146 years with nanosecond precision, and up to ±146 million years with millisecond precision. If a duration-returning operation provided in `kotlin.time` produces a duration value that doesn't fit into the above range, the returned `Duration` is infinite. An infinite duration value [Duration.INFINITE](-i-n-f-i-n-i-t-e) can be used to represent infinite timeouts. To construct a duration use either the extension function [toDuration](../to-duration), or the extension properties <hours>, <minutes>, <seconds>, and so on, available on [Int](../../kotlin/-int/index#kotlin.Int), [Long](../../kotlin/-long/index#kotlin.Long), and [Double](../../kotlin/-double/index#kotlin.Double) numeric types. To get the value of this duration expressed in a particular [duration units](../-duration-unit/index#kotlin.time.DurationUnit) use the functions [toInt](to-int), [toLong](to-long), and [toDouble](to-double) or the properties [inWholeHours](in-whole-hours), [inWholeMinutes](in-whole-minutes), [inWholeSeconds](in-whole-seconds), [inWholeNanoseconds](in-whole-nanoseconds), and so on. Properties ---------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [absoluteValue](absolute-value) Returns the absolute value of this value. The returned value is always non-negative. ``` val absoluteValue: Duration ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inDays](in-days) The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of days. ``` val inDays: Double ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inHours](in-hours) The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of hours. ``` val inHours: Double ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inMicroseconds](in-microseconds) The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of microseconds. ``` val inMicroseconds: Double ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inMilliseconds](in-milliseconds) The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of milliseconds. ``` val inMilliseconds: Double ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inMinutes](in-minutes) The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of minutes. ``` val inMinutes: Double ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inNanoseconds](in-nanoseconds) The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of nanoseconds. ``` val inNanoseconds: Double ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inSeconds](in-seconds) The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of seconds. ``` val inSeconds: Double ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inWholeDays](in-whole-days) The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of days. ``` val inWholeDays: Long ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inWholeHours](in-whole-hours) The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of hours. ``` val inWholeHours: Long ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inWholeMicroseconds](in-whole-microseconds) The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of microseconds. ``` val inWholeMicroseconds: Long ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inWholeMilliseconds](in-whole-milliseconds) The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of milliseconds. ``` val inWholeMilliseconds: Long ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inWholeMinutes](in-whole-minutes) The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of minutes. ``` val inWholeMinutes: Long ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inWholeNanoseconds](in-whole-nanoseconds) The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of nanoseconds. ``` val inWholeNanoseconds: Long ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [inWholeSeconds](in-whole-seconds) The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of seconds. ``` val inWholeSeconds: Long ``` Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [compareTo](compare-to) ``` fun compareTo(other: Duration): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <div> Returns a duration whose value is this duration value divided by the given [scale](div#kotlin.time.Duration%24div(kotlin.Int)/scale) number. ``` operator fun div(scale: Int): Duration ``` ``` operator fun div(scale: Double): Duration ``` Returns a number that is the ratio of this and [other](div#kotlin.time.Duration%24div(kotlin.time.Duration)/other) duration values. ``` operator fun div(other: Duration): Double ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [isFinite](is-finite) Returns true, if the duration value is finite. ``` fun isFinite(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [isInfinite](is-infinite) Returns true, if the duration value is infinite. ``` fun isInfinite(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [isNegative](is-negative) Returns true, if the duration value is less than zero. ``` fun isNegative(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [isPositive](is-positive) Returns true, if the duration value is greater than zero. ``` fun isPositive(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <minus> Returns a duration whose value is the difference between this and [other](minus#kotlin.time.Duration%24minus(kotlin.time.Duration)/other) duration values. ``` operator fun minus(other: Duration): Duration ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <plus> Returns a duration whose value is the sum of this and [other](plus#kotlin.time.Duration%24plus(kotlin.time.Duration)/other) duration values. ``` operator fun plus(other: Duration): Duration ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <times> Returns a duration whose value is this duration value multiplied by the given [scale](times#kotlin.time.Duration%24times(kotlin.Int)/scale) number. ``` operator fun times(scale: Int): Duration ``` ``` operator fun times(scale: Double): Duration ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toComponents](to-components) Splits this duration into days, hours, minutes, seconds, and nanoseconds and executes the given [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function5((kotlin.Long,%20kotlin.Int,%20,%20,%20,%20kotlin.time.Duration.toComponents.T)))/action) with these components. The result of [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function5((kotlin.Long,%20kotlin.Int,%20,%20,%20,%20kotlin.time.Duration.toComponents.T)))/action) is returned as the result of this function. ``` fun <T> toComponents(     action: (days: Long, hours: Int, minutes: Int, seconds: Int, nanoseconds: Int) -> T ): T ``` Splits this duration into hours, minutes, seconds, and nanoseconds and executes the given [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function4((kotlin.Long,%20kotlin.Int,%20,%20,%20kotlin.time.Duration.toComponents.T)))/action) with these components. The result of [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function4((kotlin.Long,%20kotlin.Int,%20,%20,%20kotlin.time.Duration.toComponents.T)))/action) is returned as the result of this function. ``` fun <T> toComponents(     action: (hours: Long, minutes: Int, seconds: Int, nanoseconds: Int) -> T ): T ``` Splits this duration into minutes, seconds, and nanoseconds and executes the given [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function3((kotlin.Long,%20kotlin.Int,%20,%20kotlin.time.Duration.toComponents.T)))/action) with these components. The result of [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function3((kotlin.Long,%20kotlin.Int,%20,%20kotlin.time.Duration.toComponents.T)))/action) is returned as the result of this function. ``` fun <T> toComponents(     action: (minutes: Long, seconds: Int, nanoseconds: Int) -> T ): T ``` Splits this duration into seconds, and nanoseconds and executes the given [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function2((kotlin.Long,%20kotlin.Int,%20kotlin.time.Duration.toComponents.T)))/action) with these components. The result of [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function2((kotlin.Long,%20kotlin.Int,%20kotlin.time.Duration.toComponents.T)))/action) is returned as the result of this function. ``` fun <T> toComponents(     action: (seconds: Long, nanoseconds: Int) -> T ): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toDouble](to-double) Returns the value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of the specified [unit](to-double#kotlin.time.Duration%24toDouble(kotlin.time.DurationUnit)/unit). ``` fun toDouble(unit: DurationUnit): Double ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toInt](to-int) Returns the value of this duration expressed as an [Int](../../kotlin/-int/index#kotlin.Int) number of the specified [unit](to-int#kotlin.time.Duration%24toInt(kotlin.time.DurationUnit)/unit). ``` fun toInt(unit: DurationUnit): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toIsoString](to-iso-string) Returns an ISO-8601 based string representation of this duration. ``` fun toIsoString(): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toLong](to-long) Returns the value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of the specified [unit](to-long#kotlin.time.Duration%24toLong(kotlin.time.DurationUnit)/unit). ``` fun toLong(unit: DurationUnit): Long ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toLongMilliseconds](to-long-milliseconds) Returns the value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of milliseconds. ``` fun toLongMilliseconds(): Long ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toLongNanoseconds](to-long-nanoseconds) Returns the value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of nanoseconds. ``` fun toLongNanoseconds(): Long ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toString](to-string) Returns a string representation of this duration value expressed as a combination of numeric components, each in its own unit. ``` fun toString(): String ``` Returns a string representation of this duration value expressed in the given [unit](to-string#kotlin.time.Duration%24toString(kotlin.time.DurationUnit,%20kotlin.Int)/unit) and formatted with the specified [decimals](to-string#kotlin.time.Duration%24toString(kotlin.time.DurationUnit,%20kotlin.Int)/decimals) number of digits after decimal point. ``` fun toString(unit: DurationUnit, decimals: Int = 0): String ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [unaryMinus](unary-minus) Returns the negative of this value. ``` operator fun unaryMinus(): Duration ``` Companion Object Properties --------------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <days> Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of days. ``` val Int.days: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of days. ``` val Long.days: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of days. ``` val Double.days: <ERROR CLASS> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <hours> Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of hours. ``` val Int.hours: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of hours. ``` val Long.hours: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of hours. ``` val Double.hours: <ERROR CLASS> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [INFINITE](-i-n-f-i-n-i-t-e) The duration whose value is positive infinity. It is useful for representing timeouts that should never expire. ``` val INFINITE: Duration ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <microseconds> Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of microseconds. ``` val Int.microseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of microseconds. ``` val Long.microseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of microseconds. ``` val Double.microseconds: <ERROR CLASS> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <milliseconds> Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of milliseconds. ``` val Int.milliseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of milliseconds. ``` val Long.milliseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of milliseconds. ``` val Double.milliseconds: <ERROR CLASS> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <minutes> Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of minutes. ``` val Int.minutes: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of minutes. ``` val Long.minutes: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of minutes. ``` val Double.minutes: <ERROR CLASS> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <nanoseconds> Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of nanoseconds. ``` val Int.nanoseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of nanoseconds. ``` val Long.nanoseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of nanoseconds. ``` val Double.nanoseconds: <ERROR CLASS> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <seconds> Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of seconds. ``` val Int.seconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of seconds. ``` val Long.seconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of seconds. ``` val Double.seconds: <ERROR CLASS> ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [ZERO](-z-e-r-o) The duration equal to exactly 0 seconds. ``` val ZERO: Duration ``` Companion Object Functions -------------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <convert> Converts the given time duration [value](convert#kotlin.time.Duration.Companion%24convert(kotlin.Double,%20kotlin.time.DurationUnit,%20kotlin.time.DurationUnit)/value) expressed in the specified [sourceUnit](convert#kotlin.time.Duration.Companion%24convert(kotlin.Double,%20kotlin.time.DurationUnit,%20kotlin.time.DurationUnit)/sourceUnit) into the specified [targetUnit](convert#kotlin.time.Duration.Companion%24convert(kotlin.Double,%20kotlin.time.DurationUnit,%20kotlin.time.DurationUnit)/targetUnit). ``` fun convert(     value: Double,     sourceUnit: DurationUnit,     targetUnit: DurationUnit ): Double ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### <days> Returns a [Duration](index) representing the specified [value](days#kotlin.time.Duration.Companion%24days(kotlin.Int)/value) number of days. ``` fun days(value: Int): Duration ``` ``` fun days(value: Long): Duration ``` ``` fun days(value: Double): Duration ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### <hours> Returns a [Duration](index) representing the specified [value](hours#kotlin.time.Duration.Companion%24hours(kotlin.Int)/value) number of hours. ``` fun hours(value: Int): Duration ``` ``` fun hours(value: Long): Duration ``` ``` fun hours(value: Double): Duration ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### <microseconds> Returns a [Duration](index) representing the specified [value](microseconds#kotlin.time.Duration.Companion%24microseconds(kotlin.Int)/value) number of microseconds. ``` fun microseconds(value: Int): Duration ``` ``` fun microseconds(value: Long): Duration ``` ``` fun microseconds(value: Double): Duration ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### <milliseconds> Returns a [Duration](index) representing the specified [value](milliseconds#kotlin.time.Duration.Companion%24milliseconds(kotlin.Int)/value) number of milliseconds. ``` fun milliseconds(value: Int): Duration ``` ``` fun milliseconds(value: Long): Duration ``` ``` fun milliseconds(value: Double): Duration ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### <minutes> Returns a [Duration](index) representing the specified [value](minutes#kotlin.time.Duration.Companion%24minutes(kotlin.Int)/value) number of minutes. ``` fun minutes(value: Int): Duration ``` ``` fun minutes(value: Long): Duration ``` ``` fun minutes(value: Double): Duration ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### <nanoseconds> Returns a [Duration](index) representing the specified [value](nanoseconds#kotlin.time.Duration.Companion%24nanoseconds(kotlin.Int)/value) number of nanoseconds. ``` fun nanoseconds(value: Int): Duration ``` ``` fun nanoseconds(value: Long): Duration ``` ``` fun nanoseconds(value: Double): Duration ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <parse> Parses a string that represents a duration and returns the parsed [Duration](index) value. ``` fun parse(value: String): Duration ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [parseIsoString](parse-iso-string) Parses a string that represents a duration in a restricted ISO-8601 composite representation and returns the parsed [Duration](index) value. Composite representation is a relaxed version of ISO-8601 duration format that supports negative durations and negative values of individual components. ``` fun parseIsoString(value: String): Duration ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [parseIsoStringOrNull](parse-iso-string-or-null) Parses a string that represents a duration in restricted ISO-8601 composite representation and returns the parsed [Duration](index) value or `null` if the string doesn't represent a duration in the format acceptable by [parseIsoString](parse-iso-string). ``` fun parseIsoStringOrNull(value: String): Duration? ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [parseOrNull](parse-or-null) Parses a string that represents a duration and returns the parsed [Duration](index) value, or `null` if the string doesn't represent a duration in any of the supported formats. ``` fun parseOrNull(value: String): Duration? ``` **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) #### <seconds> Returns a [Duration](index) representing the specified [value](seconds#kotlin.time.Duration.Companion%24seconds(kotlin.Int)/value) number of seconds. ``` fun seconds(value: Int): Duration ``` ``` fun seconds(value: Long): Duration ``` ``` fun seconds(value: Double): Duration ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceAtLeast](../../kotlin.ranges/coerce-at-least) Ensures that this value is not less than the specified [minimumValue](../../kotlin.ranges/coerce-at-least#kotlin.ranges%24coerceAtLeast(kotlin.ranges.coerceAtLeast.T,%20kotlin.ranges.coerceAtLeast.T)/minimumValue). ``` fun <T : Comparable<T>> T.coerceAtLeast(minimumValue: T): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceAtMost](../../kotlin.ranges/coerce-at-most) Ensures that this value is not greater than the specified [maximumValue](../../kotlin.ranges/coerce-at-most#kotlin.ranges%24coerceAtMost(kotlin.ranges.coerceAtMost.T,%20kotlin.ranges.coerceAtMost.T)/maximumValue). ``` fun <T : Comparable<T>> T.coerceAtMost(maximumValue: T): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceIn](../../kotlin.ranges/coerce-in) Ensures that this value lies in the specified range [minimumValue](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.coerceIn.T?,%20kotlin.ranges.coerceIn.T?)/minimumValue)..[maximumValue](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.coerceIn.T?,%20kotlin.ranges.coerceIn.T?)/maximumValue). ``` fun <T : Comparable<T>> T.coerceIn(     minimumValue: T?,     maximumValue: T? ): T ``` Ensures that this value lies in the specified [range](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.ClosedFloatingPointRange((kotlin.ranges.coerceIn.T)))/range). ``` fun <T : Comparable<T>> T.coerceIn(     range: ClosedFloatingPointRange<T> ): T ``` ``` fun <T : Comparable<T>> T.coerceIn(range: ClosedRange<T>): T ``` **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) #### [compareTo](../../kotlin/compare-to) Compares this object with the specified object for order. Returns zero if this object is equal to the specified [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other) object, a negative number if it's less than [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other), or a positive number if it's greater than [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other). ``` infix fun <T> Comparable<T>.compareTo(other: T): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [rangeTo](../../kotlin.ranges/range-to) Creates a range from this [Comparable](../../kotlin/-comparable/index#kotlin.Comparable) value to the specified [that](../../kotlin.ranges/range-to#kotlin.ranges%24rangeTo(kotlin.ranges.rangeTo.T,%20kotlin.ranges.rangeTo.T)/that) value. ``` operator fun <T : Comparable<T>> T.rangeTo(     that: T ): ClosedRange<T> ``` **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) #### [rangeUntil](../../kotlin.ranges/range-until) Creates an open-ended range from this [Comparable](../../kotlin/-comparable/index#kotlin.Comparable) value to the specified [that](../../kotlin.ranges/range-until#kotlin.ranges%24rangeUntil(kotlin.ranges.rangeUntil.T,%20kotlin.ranges.rangeUntil.T)/that) value. ``` operator fun <T : Comparable<T>> T.rangeUntil(     that: T ): OpenEndRange<T> ``` **Platform and version requirements:** JVM (1.6), JRE8 (1.6) #### [toJavaDuration](../to-java-duration) Converts kotlin.time.Duration value to [java.time.Duration](https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html) value. ``` fun Duration.toJavaDuration(): Duration ```
programming_docs
kotlin ZERO ZERO ==== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [ZERO](-z-e-r-o) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` val ZERO: Duration ``` The duration equal to exactly 0 seconds. kotlin inMinutes inMinutes ========= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inMinutes](in-minutes) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val inMinutes: Double ``` **Deprecated:** Use inWholeMinutes property instead or convert toDouble(MINUTES) if a double value is required. The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of minutes. kotlin toLong toLong ====== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [toLong](to-long) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun toLong(unit: DurationUnit): Long ``` Returns the value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of the specified [unit](to-long#kotlin.time.Duration%24toLong(kotlin.time.DurationUnit)/unit). If the result doesn't fit in the range of [Long](../../kotlin/-long/index#kotlin.Long) type, it is coerced into that range: * [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) is returned if it's less than `Long.MIN_VALUE`, * [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) is returned if it's greater than `Long.MAX_VALUE`. An infinite duration value is converted either to [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) or [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) depending on its sign. kotlin toLongNanoseconds toLongNanoseconds ================= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [toLongNanoseconds](to-long-nanoseconds) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") fun toLongNanoseconds(): Long ``` **Deprecated:** Use inWholeNanoseconds property instead. Returns the value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of nanoseconds. If the value doesn't fit in the range of [Long](../../kotlin/-long/index#kotlin.Long) type, it is coerced into that range, see the conversion [Double.toLong](../../kotlin/-double/to-long#kotlin.Double%24toLong()) for details. The range of durations that can be expressed as a `Long` number of nanoseconds is approximately ±292 years. kotlin parseIsoStringOrNull parseIsoStringOrNull ==================== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [parseIsoStringOrNull](parse-iso-string-or-null) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun parseIsoStringOrNull(value: String): Duration? ``` Parses a string that represents a duration in restricted ISO-8601 composite representation and returns the parsed [Duration](index) value or `null` if the string doesn't represent a duration in the format acceptable by [parseIsoString](parse-iso-string). ``` import kotlin.test.* import kotlin.time.* import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.Duration.Companion.seconds fun main(args: Array<String>) { //sampleStart val isoFormatString = "PT1H30M" val defaultFormatString = "1h 30m" println(Duration.parseIsoString(isoFormatString)) // 1h 30m // Duration.parseIsoString(defaultFormatString) // will fail println(Duration.parseIsoStringOrNull(defaultFormatString)) // null //sampleEnd } ``` kotlin inDays inDays ====== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inDays](in-days) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val inDays: Double ``` **Deprecated:** Use inWholeDays property instead or convert toDouble(DAYS) if a double value is required. The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of days. kotlin parseIsoString parseIsoString ============== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [parseIsoString](parse-iso-string) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun parseIsoString(value: String): Duration ``` Parses a string that represents a duration in a restricted ISO-8601 composite representation and returns the parsed [Duration](index) value. Composite representation is a relaxed version of ISO-8601 duration format that supports negative durations and negative values of individual components. The following restrictions are imposed: * The only allowed non-time designator is days (`D`). `Y` (years), `W` (weeks), and `M` (months) are not supported. * Day is considered to be exactly 24 hours (24-hour clock time scale). * Alternative week-based representation `["P"][number]["W"]` is not supported. ``` import kotlin.test.* import kotlin.time.* import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.Duration.Companion.seconds fun main(args: Array<String>) { //sampleStart val isoFormatString = "PT1H30M" val defaultFormatString = "1h 30m" println(Duration.parseIsoString(isoFormatString)) // 1h 30m // Duration.parseIsoString(defaultFormatString) // will fail println(Duration.parseIsoStringOrNull(defaultFormatString)) // null //sampleEnd } ``` Exceptions ---------- `IllegalArgumentException` - if the string doesn't represent a duration in ISO-8601 format. kotlin compareTo compareTo ========= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [compareTo](compare-to) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun compareTo(other: Duration): Int ``` kotlin hours hours ===== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / <hours> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Int.hours: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of hours. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Long.hours: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of hours. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Double.hours: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of hours. Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds. Exceptions ---------- `IllegalArgumentException` - if this [Double](../../kotlin/-double/index#kotlin.Double) value is `NaN`. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun hours(     value: Int ): Duration ``` **Deprecated:** Use 'Int.hours' extension property from Duration.Companion instead. ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun hours(     value: Long ): Duration ``` **Deprecated:** Use 'Long.hours' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](hours#kotlin.time.Duration.Companion%24hours(kotlin.Int)/value) number of hours. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun hours(     value: Double ): Duration ``` **Deprecated:** Use 'Double.hours' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](hours#kotlin.time.Duration.Companion%24hours(kotlin.Double)/value) number of hours. Exceptions ---------- `IllegalArgumentException` - if the provided `Double` [value](hours#kotlin.time.Duration.Companion%24hours(kotlin.Double)/value) is `NaN`. kotlin milliseconds milliseconds ============ [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / <milliseconds> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Int.milliseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of milliseconds. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Long.milliseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of milliseconds. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Double.milliseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of milliseconds. Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds. Exceptions ---------- `IllegalArgumentException` - if this [Double](../../kotlin/-double/index#kotlin.Double) value is `NaN`. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun milliseconds(     value: Int ): Duration ``` **Deprecated:** Use 'Int.milliseconds' extension property from Duration.Companion instead. ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun milliseconds(     value: Long ): Duration ``` **Deprecated:** Use 'Long.milliseconds' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](milliseconds#kotlin.time.Duration.Companion%24milliseconds(kotlin.Int)/value) number of milliseconds. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun milliseconds(     value: Double ): Duration ``` **Deprecated:** Use 'Double.milliseconds' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](milliseconds#kotlin.time.Duration.Companion%24milliseconds(kotlin.Double)/value) number of milliseconds. Exceptions ---------- `IllegalArgumentException` - if the provided `Double` [value](milliseconds#kotlin.time.Duration.Companion%24milliseconds(kotlin.Double)/value) is `NaN`. kotlin parseOrNull parseOrNull =========== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [parseOrNull](parse-or-null) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun parseOrNull(value: String): Duration? ``` Parses a string that represents a duration and returns the parsed [Duration](index) value, or `null` if the string doesn't represent a duration in any of the supported formats. The following formats are accepted: * Restricted ISO-8601 duration composite representation, e.g. `P1DT2H3M4.058S`, see [toIsoString](to-iso-string) and [parseIsoString](parse-iso-string). * The format of string returned by the default [Duration.toString](to-string) and `toString` in a specific unit, e.g. `10s`, `1h 30m` or `-(1h 30m)`. ``` import kotlin.test.* import kotlin.time.* import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.Duration.Companion.seconds fun main(args: Array<String>) { //sampleStart val isoFormatString = "PT1H30M" val defaultFormatString = "1h 30m" val singleUnitFormatString = "1.5h" val invalidFormatString = "1 hour 30 minutes" println(Duration.parse(isoFormatString)) // 1h 30m println(Duration.parse(defaultFormatString)) // 1h 30m println(Duration.parse(singleUnitFormatString)) // 1h 30m // Duration.parse(invalidFormatString) // will fail println(Duration.parseOrNull(invalidFormatString)) // null //sampleEnd } ``` kotlin div div === [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / <div> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun div(scale: Int): Duration ``` Returns a duration whose value is this duration value divided by the given [scale](div#kotlin.time.Duration%24div(kotlin.Int)/scale) number. Exceptions ---------- `IllegalArgumentException` - if the operation results in an undefined value for the given arguments, e.g. when dividing zero duration by zero. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun div(scale: Double): Duration ``` Returns a duration whose value is this duration value divided by the given [scale](div#kotlin.time.Duration%24div(kotlin.Double)/scale) number. Exceptions ---------- `IllegalArgumentException` - if the operation results in an undefined value for the given arguments, e.g. when dividing an infinite duration by infinity or zero duration by zero. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun div(other: Duration): Double ``` Returns a number that is the ratio of this and [other](div#kotlin.time.Duration%24div(kotlin.time.Duration)/other) duration values. kotlin absoluteValue absoluteValue ============= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [absoluteValue](absolute-value) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` val absoluteValue: Duration ``` Returns the absolute value of this value. The returned value is always non-negative. kotlin toDouble toDouble ======== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [toDouble](to-double) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun toDouble(unit: DurationUnit): Double ``` Returns the value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of the specified [unit](to-double#kotlin.time.Duration%24toDouble(kotlin.time.DurationUnit)/unit). The operation may involve rounding when the result cannot be represented exactly with a [Double](../../kotlin/-double/index#kotlin.Double) number. An infinite duration value is converted either to [Double.POSITIVE\_INFINITY](../../kotlin/-double/-p-o-s-i-t-i-v-e_-i-n-f-i-n-i-t-y#kotlin.Double.Companion%24POSITIVE_INFINITY) or [Double.NEGATIVE\_INFINITY](../../kotlin/-double/-n-e-g-a-t-i-v-e_-i-n-f-i-n-i-t-y#kotlin.Double.Companion%24NEGATIVE_INFINITY) depending on its sign. kotlin microseconds microseconds ============ [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / <microseconds> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Int.microseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of microseconds. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Long.microseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of microseconds. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Double.microseconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of microseconds. Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds. Exceptions ---------- `IllegalArgumentException` - if this [Double](../../kotlin/-double/index#kotlin.Double) value is `NaN`. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun microseconds(     value: Int ): Duration ``` **Deprecated:** Use 'Int.microseconds' extension property from Duration.Companion instead. ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun microseconds(     value: Long ): Duration ``` **Deprecated:** Use 'Long.microseconds' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](microseconds#kotlin.time.Duration.Companion%24microseconds(kotlin.Int)/value) number of microseconds. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun microseconds(     value: Double ): Duration ``` **Deprecated:** Use 'Double.microseconds' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](microseconds#kotlin.time.Duration.Companion%24microseconds(kotlin.Double)/value) number of microseconds. Exceptions ---------- `IllegalArgumentException` - if the provided `Double` [value](microseconds#kotlin.time.Duration.Companion%24microseconds(kotlin.Double)/value) is `NaN`. kotlin isPositive isPositive ========== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [isPositive](is-positive) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun isPositive(): Boolean ``` Returns true, if the duration value is greater than zero. kotlin toString toString ======== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [toString](to-string) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun toString(): String ``` Returns a string representation of this duration value expressed as a combination of numeric components, each in its own unit. Each component is a number followed by the unit abbreviated name: `d`, `h`, `m`, `s`: `5h`, `1d 12h`, `1h 0m 30.340s`. The last component, usually seconds, can be a number with a fractional part. If the duration is less than a second, it is represented as a single number with one of sub-second units: `ms` (milliseconds), `us` (microseconds), or `ns` (nanoseconds): `140.884ms`, `500us`, `24ns`. A negative duration is prefixed with `-` sign and, if it consists of multiple components, surrounded with parentheses: `-12m` and `-(1h 30m)`. Special cases: * an infinite duration is formatted as `"Infinity"` or `"-Infinity"` without a unit. It's recommended to use [toIsoString](to-iso-string) that uses more strict ISO-8601 format instead of this `toString` when you want to convert a duration to a string in cases of serialization, interchange, etc. ``` import kotlin.test.* import kotlin.time.* import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.Duration.Companion.seconds fun main(args: Array<String>) { //sampleStart println(45.days) // 45d println(1.5.days) // 1d 12h println(1230.minutes) // 20h 30m println(920.minutes) // 15h 20m println(1.546.seconds) // 1.546s println(25.12.milliseconds) // 25.12ms //sampleEnd } ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun toString(unit: DurationUnit, decimals: Int = 0): String ``` Returns a string representation of this duration value expressed in the given [unit](to-string#kotlin.time.Duration%24toString(kotlin.time.DurationUnit,%20kotlin.Int)/unit) and formatted with the specified [decimals](to-string#kotlin.time.Duration%24toString(kotlin.time.DurationUnit,%20kotlin.Int)/decimals) number of digits after decimal point. Special cases: * an infinite duration is formatted as `"Infinity"` or `"-Infinity"` without a unit. ``` import kotlin.test.* import kotlin.time.* import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.Duration.Companion.seconds fun main(args: Array<String>) { //sampleStart println(1230.minutes.toString(DurationUnit.DAYS, 2)) // 0.85d println(1230.minutes.toString(DurationUnit.HOURS, 2)) // 20.50h println(1230.minutes.toString(DurationUnit.MINUTES)) // 1230m println(1230.minutes.toString(DurationUnit.SECONDS)) // 73800s //sampleEnd } ``` Parameters ---------- `decimals` - the number of digits after decimal point to show. The value must be non-negative. No more than 12 decimals will be shown, even if a larger number is requested. Exceptions ---------- `IllegalArgumentException` - if [decimals](to-string#kotlin.time.Duration%24toString(kotlin.time.DurationUnit,%20kotlin.Int)/decimals) is less than zero. **Return** the value of duration in the specified [unit](to-string#kotlin.time.Duration%24toString(kotlin.time.DurationUnit,%20kotlin.Int)/unit) followed by that unit abbreviated name: `d`, `h`, `m`, `s`, `ms`, `us`, or `ns`.
programming_docs
kotlin unaryMinus unaryMinus ========== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [unaryMinus](unary-minus) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun unaryMinus(): Duration ``` Returns the negative of this value. kotlin isNegative isNegative ========== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [isNegative](is-negative) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun isNegative(): Boolean ``` Returns true, if the duration value is less than zero. kotlin inHours inHours ======= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inHours](in-hours) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val inHours: Double ``` **Deprecated:** Use inWholeHours property instead or convert toDouble(HOURS) if a double value is required. The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of hours. kotlin inWholeDays inWholeDays =========== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inWholeDays](in-whole-days) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` val inWholeDays: Long ``` The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of days. An infinite duration value is converted either to [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) or [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) depending on its sign. kotlin INFINITE INFINITE ======== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [INFINITE](-i-n-f-i-n-i-t-e) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` val INFINITE: Duration ``` The duration whose value is positive infinity. It is useful for representing timeouts that should never expire. kotlin days days ==== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / <days> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Int.days: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of days. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Long.days: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of days. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Double.days: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of days. Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds. Exceptions ---------- `IllegalArgumentException` - if this [Double](../../kotlin/-double/index#kotlin.Double) value is `NaN`. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun days(     value: Int ): Duration ``` **Deprecated:** Use 'Int.days' extension property from Duration.Companion instead. ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun days(     value: Long ): Duration ``` **Deprecated:** Use 'Long.days' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](days#kotlin.time.Duration.Companion%24days(kotlin.Int)/value) number of days. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun days(     value: Double ): Duration ``` **Deprecated:** Use 'Double.days' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](days#kotlin.time.Duration.Companion%24days(kotlin.Double)/value) number of days. Exceptions ---------- `IllegalArgumentException` - if the provided `Double` [value](days#kotlin.time.Duration.Companion%24days(kotlin.Double)/value) is `NaN`. kotlin times times ===== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / <times> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun times(scale: Int): Duration ``` Returns a duration whose value is this duration value multiplied by the given [scale](times#kotlin.time.Duration%24times(kotlin.Int)/scale) number. Exceptions ---------- `IllegalArgumentException` - if the operation results in an undefined value for the given arguments, e.g. when multiplying an infinite duration by zero. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun times(scale: Double): Duration ``` Returns a duration whose value is this duration value multiplied by the given [scale](times#kotlin.time.Duration%24times(kotlin.Double)/scale) number. The operation may involve rounding when the result cannot be represented exactly with a [Double](../../kotlin/-double/index#kotlin.Double) number. Exceptions ---------- `IllegalArgumentException` - if the operation results in an undefined value for the given arguments, e.g. when multiplying an infinite duration by zero. kotlin minus minus ===== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / <minus> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun minus(other: Duration): Duration ``` Returns a duration whose value is the difference between this and [other](minus#kotlin.time.Duration%24minus(kotlin.time.Duration)/other) duration values. Exceptions ---------- `IllegalArgumentException` - if the operation results in an undefined value for the given arguments, e.g. when subtracting infinite durations of the same sign. kotlin inWholeMilliseconds inWholeMilliseconds =================== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inWholeMilliseconds](in-whole-milliseconds) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` val inWholeMilliseconds: Long ``` The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of milliseconds. An infinite duration value is converted either to [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) or [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) depending on its sign. kotlin inSeconds inSeconds ========= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inSeconds](in-seconds) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val inSeconds: Double ``` **Deprecated:** Use inWholeSeconds property instead or convert toDouble(SECONDS) if a double value is required. The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of seconds. kotlin parse parse ===== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / <parse> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun parse(value: String): Duration ``` Parses a string that represents a duration and returns the parsed [Duration](index) value. The following formats are accepted: * ISO-8601 Duration format, e.g. `P1DT2H3M4.058S`, see [toIsoString](to-iso-string) and [parseIsoString](parse-iso-string). * The format of string returned by the default [Duration.toString](to-string) and `toString` in a specific unit, e.g. `10s`, `1h 30m` or `-(1h 30m)`. ``` import kotlin.test.* import kotlin.time.* import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.Duration.Companion.seconds fun main(args: Array<String>) { //sampleStart val isoFormatString = "PT1H30M" val defaultFormatString = "1h 30m" val singleUnitFormatString = "1.5h" val invalidFormatString = "1 hour 30 minutes" println(Duration.parse(isoFormatString)) // 1h 30m println(Duration.parse(defaultFormatString)) // 1h 30m println(Duration.parse(singleUnitFormatString)) // 1h 30m // Duration.parse(invalidFormatString) // will fail println(Duration.parseOrNull(invalidFormatString)) // null //sampleEnd } ``` Exceptions ---------- `IllegalArgumentException` - if the string doesn't represent a duration in any of the supported formats. kotlin isInfinite isInfinite ========== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [isInfinite](is-infinite) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun isInfinite(): Boolean ``` Returns true, if the duration value is infinite. kotlin inWholeMinutes inWholeMinutes ============== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inWholeMinutes](in-whole-minutes) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` val inWholeMinutes: Long ``` The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of minutes. An infinite duration value is converted either to [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) or [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) depending on its sign. kotlin inMilliseconds inMilliseconds ============== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inMilliseconds](in-milliseconds) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") val inMilliseconds: Double ``` **Deprecated:** Use inWholeMilliseconds property instead or convert toDouble(MILLISECONDS) if a double value is required. The value of this duration expressed as a [Double](../../kotlin/-double/index#kotlin.Double) number of milliseconds. kotlin inWholeHours inWholeHours ============ [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [inWholeHours](in-whole-hours) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` val inWholeHours: Long ``` The value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of hours. An infinite duration value is converted either to [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) or [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) depending on its sign. kotlin plus plus ==== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / <plus> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun plus(other: Duration): Duration ``` Returns a duration whose value is the sum of this and [other](plus#kotlin.time.Duration%24plus(kotlin.time.Duration)/other) duration values. Exceptions ---------- `IllegalArgumentException` - if the operation results in an undefined value for the given arguments, e.g. when adding infinite durations of different sign. kotlin toComponents toComponents ============ [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [toComponents](to-components) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <T> toComponents(     action: (days: Long, hours: Int, minutes: Int, seconds: Int, nanoseconds: Int) -> T ): T ``` Splits this duration into days, hours, minutes, seconds, and nanoseconds and executes the given [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function5((kotlin.Long,%20kotlin.Int,%20,%20,%20,%20kotlin.time.Duration.toComponents.T)))/action) with these components. The result of [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function5((kotlin.Long,%20kotlin.Int,%20,%20,%20,%20kotlin.time.Duration.toComponents.T)))/action) is returned as the result of this function. * `nanoseconds` represents the whole number of nanoseconds in this duration, and its absolute value is less than 1\_000\_000\_000; * `seconds` represents the whole number of seconds in this duration, and its absolute value is less than 60; * `minutes` represents the whole number of minutes in this duration, and its absolute value is less than 60; * `hours` represents the whole number of hours in this duration, and its absolute value is less than 24; * `days` represents the whole number of days in this duration. Infinite durations are represented as either [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) days, or [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) days (depending on the sign of infinity), and zeroes in the lower components. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <T> toComponents(     action: (hours: Long, minutes: Int, seconds: Int, nanoseconds: Int) -> T ): T ``` Splits this duration into hours, minutes, seconds, and nanoseconds and executes the given [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function4((kotlin.Long,%20kotlin.Int,%20,%20,%20kotlin.time.Duration.toComponents.T)))/action) with these components. The result of [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function4((kotlin.Long,%20kotlin.Int,%20,%20,%20kotlin.time.Duration.toComponents.T)))/action) is returned as the result of this function. * `nanoseconds` represents the whole number of nanoseconds in this duration, and its absolute value is less than 1\_000\_000\_000; * `seconds` represents the whole number of seconds in this duration, and its absolute value is less than 60; * `minutes` represents the whole number of minutes in this duration, and its absolute value is less than 60; * `hours` represents the whole number of hours in this duration. Infinite durations are represented as either [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) hours, or [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) hours (depending on the sign of infinity), and zeroes in the lower components. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <T> toComponents(     action: (minutes: Long, seconds: Int, nanoseconds: Int) -> T ): T ``` Splits this duration into minutes, seconds, and nanoseconds and executes the given [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function3((kotlin.Long,%20kotlin.Int,%20,%20kotlin.time.Duration.toComponents.T)))/action) with these components. The result of [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function3((kotlin.Long,%20kotlin.Int,%20,%20kotlin.time.Duration.toComponents.T)))/action) is returned as the result of this function. * `nanoseconds` represents the whole number of nanoseconds in this duration, and its absolute value is less than 1\_000\_000\_000; * `seconds` represents the whole number of seconds in this duration, and its absolute value is less than 60; * `minutes` represents the whole number of minutes in this duration. Infinite durations are represented as either [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) minutes, or [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) minutes (depending on the sign of infinity), and zeroes in the lower components. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline fun <T> toComponents(     action: (seconds: Long, nanoseconds: Int) -> T ): T ``` Splits this duration into seconds, and nanoseconds and executes the given [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function2((kotlin.Long,%20kotlin.Int,%20kotlin.time.Duration.toComponents.T)))/action) with these components. The result of [action](to-components#kotlin.time.Duration%24toComponents(kotlin.Function2((kotlin.Long,%20kotlin.Int,%20kotlin.time.Duration.toComponents.T)))/action) is returned as the result of this function. * `nanoseconds` represents the whole number of nanoseconds in this duration, and its absolute value is less than 1\_000\_000\_000; * `seconds` represents the whole number of seconds in this duration. Infinite durations are represented as either [Long.MAX\_VALUE](../../kotlin/-long/-m-a-x_-v-a-l-u-e#kotlin.Long.Companion%24MAX_VALUE) seconds, or [Long.MIN\_VALUE](../../kotlin/-long/-m-i-n_-v-a-l-u-e#kotlin.Long.Companion%24MIN_VALUE) seconds (depending on the sign of infinity), and zero nanoseconds. kotlin convert convert ======= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / <convert> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @ExperimentalTime fun convert(     value: Double,     sourceUnit: DurationUnit,     targetUnit: DurationUnit ): Double ``` Converts the given time duration [value](convert#kotlin.time.Duration.Companion%24convert(kotlin.Double,%20kotlin.time.DurationUnit,%20kotlin.time.DurationUnit)/value) expressed in the specified [sourceUnit](convert#kotlin.time.Duration.Companion%24convert(kotlin.Double,%20kotlin.time.DurationUnit,%20kotlin.time.DurationUnit)/sourceUnit) into the specified [targetUnit](convert#kotlin.time.Duration.Companion%24convert(kotlin.Double,%20kotlin.time.DurationUnit,%20kotlin.time.DurationUnit)/targetUnit). kotlin toIsoString toIsoString =========== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [toIsoString](to-iso-string) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun toIsoString(): String ``` Returns an ISO-8601 based string representation of this duration. The returned value is presented in the format `PThHmMs.fS`, where `h`, `m`, `s` are the integer components of this duration (see [toComponents](to-components)) and `f` is a fractional part of second. Depending on the roundness of the value the fractional part can be formatted with either 0, 3, 6, or 9 decimal digits. The infinite duration is represented as `"PT9999999999999H"` which is larger than any possible finite duration in Kotlin. Negative durations are indicated with the sign `-` in the beginning of the returned string, for example, `"-PT5M30S"`. ``` import kotlin.test.* import kotlin.time.* import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.Duration.Companion.seconds fun main(args: Array<String>) { //sampleStart println(25.nanoseconds.toIsoString()) // PT0.000000025S println(120.3.milliseconds.toIsoString()) // PT0.120300S println(30.5.seconds.toIsoString()) // PT30.500S println(30.5.minutes.toIsoString()) // PT30M30S println(86420.seconds.toIsoString()) // PT24H0M20S println(2.days.toIsoString()) // PT48H println(Duration.ZERO.toIsoString()) // PT0S println(Duration.INFINITE.toIsoString()) // PT9999999999999H //sampleEnd } ```
programming_docs
kotlin toLongMilliseconds toLongMilliseconds ================== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / [toLongMilliseconds](to-long-milliseconds) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.5", "1.8") fun toLongMilliseconds(): Long ``` **Deprecated:** Use inWholeMilliseconds property instead. Returns the value of this duration expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number of milliseconds. The value is coerced to the range of [Long](../../kotlin/-long/index#kotlin.Long) type, if it doesn't fit in that range, see the conversion [Double.toLong](../../kotlin/-double/to-long#kotlin.Double%24toLong()) for details. The range of durations that can be expressed as a `Long` number of milliseconds is approximately ±292 million years. kotlin seconds seconds ======= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [Duration](index) / <seconds> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Int.seconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Int](../../kotlin/-int/index#kotlin.Int) number of seconds. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Long.seconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Long](../../kotlin/-long/index#kotlin.Long) number of seconds. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` inline val Double.seconds: <ERROR CLASS> ``` Returns a [Duration](index) equal to this [Double](../../kotlin/-double/index#kotlin.Double) number of seconds. Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds. Exceptions ---------- `IllegalArgumentException` - if this [Double](../../kotlin/-double/index#kotlin.Double) value is `NaN`. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun seconds(     value: Int ): Duration ``` **Deprecated:** Use 'Int.seconds' extension property from Duration.Companion instead. ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun seconds(     value: Long ): Duration ``` **Deprecated:** Use 'Long.seconds' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](seconds#kotlin.time.Duration.Companion%24seconds(kotlin.Int)/value) number of seconds. **Platform and version requirements:** JVM (1.5), JS (1.5), Native (1.5) ``` @ExperimentalTime @DeprecatedSinceKotlin("1.6", "1.8") fun seconds(     value: Double ): Duration ``` **Deprecated:** Use 'Double.seconds' extension property from Duration.Companion instead. Returns a [Duration](index) representing the specified [value](seconds#kotlin.time.Duration.Companion%24seconds(kotlin.Double)/value) number of seconds. Exceptions ---------- `IllegalArgumentException` - if the provided `Double` [value](seconds#kotlin.time.Duration.Companion%24seconds(kotlin.Double)/value) is `NaN`. kotlin Extensions for java.time.Duration Extensions for java.time.Duration ================================= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [java.time.Duration](index) **Platform and version requirements:** JVM (1.6), JRE8 (1.6) #### [toKotlinDuration](to-kotlin-duration) Converts [java.time.Duration](https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html) value to kotlin.time.Duration value. ``` fun Duration.toKotlinDuration(): Duration ``` kotlin toKotlinDuration toKotlinDuration ================ [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [java.time.Duration](index) / [toKotlinDuration](to-kotlin-duration) **Platform and version requirements:** JVM (1.6), JRE8 (1.6) ``` fun Duration.toKotlinDuration(): Duration ``` Converts [java.time.Duration](https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html) value to kotlin.time.Duration value. Durations less than 104 days are converted exactly, and durations greater than that can lose some precision due to rounding. kotlin plusAssign plusAssign ========== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TestTimeSource](index) / [plusAssign](plus-assign) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun plusAssign(duration: Duration) ``` Advances the current reading value of this time source by the specified [duration](plus-assign#kotlin.time.TestTimeSource%24plusAssign(kotlin.time.Duration)/duration). [duration](plus-assign#kotlin.time.TestTimeSource%24plusAssign(kotlin.time.Duration)/duration) value is rounded down towards zero when converting it to a [Long](../../kotlin/-long/index#kotlin.Long) number of nanoseconds. For example, if the duration being added is `0.6.nanoseconds`, the reading doesn't advance because the duration value is rounded to zero nanoseconds. Exceptions ---------- `IllegalStateException` - when the reading value overflows as the result of this operation. kotlin read read ==== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TestTimeSource](index) / <read> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` protected fun read(): Long ``` This protected method should be overridden to return the current reading of the time source expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number in the unit specified by the [unit](../-abstract-long-time-source/unit) property. kotlin TestTimeSource TestTimeSource ============== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TestTimeSource](index) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime class TestTimeSource :      AbstractLongTimeSource ``` A time source that has programmatically updatable readings. It is useful as a predictable source of time in tests. The current reading value can be advanced by the specified duration amount with the operator [plusAssign](plus-assign): ``` val timeSource = TestTimeSource() timeSource += 10.seconds ``` Implementation note: the current reading value is stored as a [Long](../../kotlin/-long/index#kotlin.Long) number of nanoseconds, thus it's capable to represent a time range of approximately ±292 years. Should the reading value overflow as the result of [plusAssign](plus-assign) operation, an [IllegalStateException](../../kotlin/-illegal-state-exception/index#kotlin.IllegalStateException) is thrown. Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [<init>](-init-) A time source that has programmatically updatable readings. It is useful as a predictable source of time in tests. ``` TestTimeSource() ``` Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [plusAssign](plus-assign) Advances the current reading value of this time source by the specified [duration](plus-assign#kotlin.time.TestTimeSource%24plusAssign(kotlin.time.Duration)/duration). ``` operator fun plusAssign(duration: Duration) ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <read> This protected method should be overridden to return the current reading of the time source expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number in the unit specified by the [unit](../-abstract-long-time-source/unit) property. ``` fun read(): Long ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [measureTime](../measure-time) Executes the given function [block](../measure-time#kotlin.time%24measureTime(kotlin.time.TimeSource,%20kotlin.Function0((kotlin.Unit)))/block) and returns the duration of elapsed time interval. ``` fun TimeSource.measureTime(block: () -> Unit): Duration ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [measureTimedValue](../measure-timed-value) Executes the given [block](../measure-timed-value#kotlin.time%24measureTimedValue(kotlin.time.TimeSource,%20kotlin.Function0((kotlin.time.measureTimedValue.T)))/block) and returns an instance of [TimedValue](../-timed-value/index) class, containing both the result of function execution and the duration of elapsed time interval. ``` fun <T> TimeSource.measureTimedValue(     block: () -> T ): TimedValue<T> ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TestTimeSource](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` TestTimeSource() ``` A time source that has programmatically updatable readings. It is useful as a predictable source of time in tests. The current reading value can be advanced by the specified duration amount with the operator [plusAssign](plus-assign): ``` val timeSource = TestTimeSource() timeSource += 10.seconds ``` Implementation note: the current reading value is stored as a [Long](../../kotlin/-long/index#kotlin.Long) number of nanoseconds, thus it's capable to represent a time range of approximately ±292 years. Should the reading value overflow as the result of [plusAssign](plus-assign) operation, an [IllegalStateException](../../kotlin/-illegal-state-exception/index#kotlin.IllegalStateException) is thrown. kotlin Extensions for java.util.concurrent.TimeUnit Extensions for java.util.concurrent.TimeUnit ============================================ [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [java.util.concurrent.TimeUnit](index) **Platform and version requirements:** JVM (1.8) #### [toDurationUnit](to-duration-unit) Converts this [java.util.concurrent.TimeUnit](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html) enum value to the corresponding [kotlin.time.DurationUnit](../-duration-unit/index#kotlin.time.DurationUnit) value. ``` fun TimeUnit.toDurationUnit(): DurationUnit ``` kotlin toDurationUnit toDurationUnit ============== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [java.util.concurrent.TimeUnit](index) / [toDurationUnit](to-duration-unit) **Platform and version requirements:** JVM (1.8) ``` fun TimeUnit.toDurationUnit(): DurationUnit ``` Converts this [java.util.concurrent.TimeUnit](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html) enum value to the corresponding [kotlin.time.DurationUnit](../-duration-unit/index#kotlin.time.DurationUnit) value. kotlin TimeSource TimeSource ========== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TimeSource](index) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime interface TimeSource ``` A source of time for measuring time intervals. The only operation provided by the time source is [markNow](mark-now). It returns a [TimeMark](../-time-mark/index), which can be used to query the elapsed time later. **See Also** [measureTime](../measure-time) [measureTimedValue](../measure-timed-value) Types ----- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [Monotonic](-monotonic/index) The most precise time source available in the platform. ``` object Monotonic : WithComparableMarks ``` **Platform and version requirements:** JVM (1.8), JS (1.8), Native (1.8) #### [WithComparableMarks](-with-comparable-marks/index) A [TimeSource](index) that returns [time marks](../-comparable-time-mark/index) that can be compared for difference with each other. ``` interface WithComparableMarks : TimeSource ``` Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [markNow](mark-now) Marks a point in time on this time source. ``` abstract fun markNow(): TimeMark ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [measureTime](../measure-time) Executes the given function [block](../measure-time#kotlin.time%24measureTime(kotlin.time.TimeSource,%20kotlin.Function0((kotlin.Unit)))/block) and returns the duration of elapsed time interval. ``` fun TimeSource.measureTime(block: () -> Unit): Duration ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [measureTimedValue](../measure-timed-value) Executes the given [block](../measure-timed-value#kotlin.time%24measureTimedValue(kotlin.time.TimeSource,%20kotlin.Function0((kotlin.time.measureTimedValue.T)))/block) and returns an instance of [TimedValue](../-timed-value/index) class, containing both the result of function execution and the duration of elapsed time interval. ``` fun <T> TimeSource.measureTimedValue(     block: () -> T ): TimedValue<T> ``` kotlin markNow markNow ======= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TimeSource](index) / [markNow](mark-now) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract fun markNow(): TimeMark ``` Marks a point in time on this time source. The returned [TimeMark](../-time-mark/index) instance encapsulates the captured time point and allows querying the duration of time interval [elapsed](../-time-mark/elapsed-now) from that point. kotlin Monotonic Monotonic ========= [kotlin-stdlib](../../../../../../../index) / [kotlin.time](../../index) / [TimeSource](../index) / [Monotonic](index) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` object Monotonic : WithComparableMarks ``` The most precise time source available in the platform. This time source returns its readings from a source of monotonic time when it is available in a target platform, and resorts to a non-monotonic time source otherwise. The function [markNow](mark-now) of this time source returns the specialized [ValueTimeMark](-value-time-mark/index) that is an inline value class wrapping a platform-dependent time reading value. Types ----- **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) #### [ValueTimeMark](-value-time-mark/index) A specialized [kotlin.time.TimeMark](../../-time-mark/index) returned by [TimeSource.Monotonic](index) time source. ``` class ValueTimeMark : ComparableTimeMark ``` Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [markNow](mark-now) Marks a point in time on this time source. ``` fun markNow(): ValueTimeMark ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [toString](to-string) Returns a string representation of the object. ``` fun toString(): String ``` kotlin markNow markNow ======= [kotlin-stdlib](../../../../../../../index) / [kotlin.time](../../index) / [TimeSource](../index) / [Monotonic](index) / [markNow](mark-now) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun markNow(): ValueTimeMark ``` Marks a point in time on this time source. The returned [TimeMark](../../-time-mark/index) instance encapsulates the captured time point and allows querying the duration of time interval [elapsed](../../-time-mark/elapsed-now) from that point. kotlin toString toString ======== [kotlin-stdlib](../../../../../../../index) / [kotlin.time](../../index) / [TimeSource](../index) / [Monotonic](index) / [toString](to-string) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun toString(): String ``` Returns a string representation of the object. kotlin ValueTimeMark ValueTimeMark ============= [kotlin-stdlib](../../../../../../../../index) / [kotlin.time](../../../index) / [TimeSource](../../index) / [Monotonic](../index) / [ValueTimeMark](index) **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) ``` @ExperimentalTime inline class ValueTimeMark :      ComparableTimeMark ``` A specialized [kotlin.time.TimeMark](../../../-time-mark/index) returned by [TimeSource.Monotonic](../index) time source. This time mark is implemented as an inline value class wrapping a platform-dependent time reading value of the default monotonic time source, thus allowing to avoid additional boxing of that value. The operations <plus> and <minus> are also specialized to return [ValueTimeMark](index) type. This time mark implements [ComparableTimeMark](../../../-comparable-time-mark/index) and therefore is comparable with other time marks obtained from the same [TimeSource.Monotonic](../index) time source. Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [compareTo](compare-to) Compares this time mark with the [other](compare-to#kotlin.time.TimeSource.Monotonic.ValueTimeMark%24compareTo(kotlin.time.TimeSource.Monotonic.ValueTimeMark)/other) time mark for order. ``` operator fun compareTo(other: ValueTimeMark): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [elapsedNow](elapsed-now) Returns the amount of time passed from this mark measured with the time source from which this mark was taken. ``` fun elapsedNow(): Duration ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [hasNotPassedNow](has-not-passed-now) Returns false if this time mark has not passed according to the time source from which this mark was taken. ``` fun hasNotPassedNow(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [hasPassedNow](has-passed-now) Returns true if this time mark has passed according to the time source from which this mark was taken. ``` fun hasPassedNow(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <minus> Returns a time mark on the same time source that is behind this time mark by the specified [duration](../../../-time-mark/minus#kotlin.time.TimeMark%24minus(kotlin.time.Duration)/duration). ``` fun minus(duration: Duration): ValueTimeMark ``` Returns the duration elapsed between the [other](../../../-comparable-time-mark/minus#kotlin.time.ComparableTimeMark%24minus(kotlin.time.ComparableTimeMark)/other) time mark and `this` time mark. ``` fun minus(other: ComparableTimeMark): Duration ``` Returns the duration elapsed between the [other](minus#kotlin.time.TimeSource.Monotonic.ValueTimeMark%24minus(kotlin.time.TimeSource.Monotonic.ValueTimeMark)/other) time mark obtained from the same [TimeSource.Monotonic](../index) time source and `this` time mark. ``` operator fun minus(other: ValueTimeMark): Duration ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <plus> Returns a time mark on the same time source that is ahead of this time mark by the specified [duration](../../../-time-mark/plus#kotlin.time.TimeMark%24plus(kotlin.time.Duration)/duration). ``` fun plus(duration: Duration): ValueTimeMark ``` kotlin compareTo compareTo ========= [kotlin-stdlib](../../../../../../../../index) / [kotlin.time](../../../index) / [TimeSource](../../index) / [Monotonic](../index) / [ValueTimeMark](index) / [compareTo](compare-to) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun compareTo(other: ValueTimeMark): Int ``` Compares this time mark with the [other](compare-to#kotlin.time.TimeSource.Monotonic.ValueTimeMark%24compareTo(kotlin.time.TimeSource.Monotonic.ValueTimeMark)/other) time mark for order. * Returns zero if this time mark represents *the same moment* of time as the [other](compare-to#kotlin.time.TimeSource.Monotonic.ValueTimeMark%24compareTo(kotlin.time.TimeSource.Monotonic.ValueTimeMark)/other) time mark. * Returns a negative number if this time mark is *earlier* than the [other](compare-to#kotlin.time.TimeSource.Monotonic.ValueTimeMark%24compareTo(kotlin.time.TimeSource.Monotonic.ValueTimeMark)/other) time mark. * Returns a positive number if this time mark is *later* than the [other](compare-to#kotlin.time.TimeSource.Monotonic.ValueTimeMark%24compareTo(kotlin.time.TimeSource.Monotonic.ValueTimeMark)/other) time mark.
programming_docs
kotlin elapsedNow elapsedNow ========== [kotlin-stdlib](../../../../../../../../index) / [kotlin.time](../../../index) / [TimeSource](../../index) / [Monotonic](../index) / [ValueTimeMark](index) / [elapsedNow](elapsed-now) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun elapsedNow(): Duration ``` Returns the amount of time passed from this mark measured with the time source from which this mark was taken. Note that the value returned by this function can change on subsequent invocations. Exceptions ---------- `IllegalArgumentException` - an implementation may throw if calculating the elapsed time involves adding a positive infinite duration to an infinitely distant past time mark or a negative infinite duration to an infinitely distant future time mark. kotlin minus minus ===== [kotlin-stdlib](../../../../../../../../index) / [kotlin.time](../../../index) / [TimeSource](../../index) / [Monotonic](../index) / [ValueTimeMark](index) / <minus> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun minus(duration: Duration): ValueTimeMark ``` Returns a time mark on the same time source that is behind this time mark by the specified [duration](../../../-time-mark/minus#kotlin.time.TimeMark%24minus(kotlin.time.Duration)/duration). The returned time mark is more *early* when the [duration](../../../-time-mark/minus#kotlin.time.TimeMark%24minus(kotlin.time.Duration)/duration) is positive, and more *late* when the [duration](../../../-time-mark/minus#kotlin.time.TimeMark%24minus(kotlin.time.Duration)/duration) is negative. If the time mark is adjusted too far in the past or in the future, it may saturate to an infinitely distant time mark. In that case, [elapsedNow](../../../-time-mark/elapsed-now) will return an infinite duration elapsed from such infinitely distant mark. Exceptions ---------- `IllegalArgumentException` - an implementation may throw if a positive infinite duration is subtracted from an infinitely distant future time mark or a negative infinite duration is subtracted from an infinitely distant past time mark. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun minus(other: ComparableTimeMark): Duration ``` Returns the duration elapsed between the [other](../../../-comparable-time-mark/minus#kotlin.time.ComparableTimeMark%24minus(kotlin.time.ComparableTimeMark)/other) time mark and `this` time mark. The returned duration can be infinite if the time marks are far away from each other and the result doesn't fit into [Duration](../../../-duration/index) type, or if one time mark is infinitely distant, or if both `this` and [other](../../../-comparable-time-mark/minus#kotlin.time.ComparableTimeMark%24minus(kotlin.time.ComparableTimeMark)/other) time marks lie infinitely distant on the opposite sides of the time scale. Two infinitely distant time marks on the same side of the time scale are considered equal and the duration between them is [Duration.ZERO](../../../-duration/-z-e-r-o). Note that the other time mark must be obtained from the same time source as this one. Exceptions ---------- `IllegalArgumentException` - if time marks were obtained from different time sources. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` operator fun minus(other: ValueTimeMark): Duration ``` Returns the duration elapsed between the [other](minus#kotlin.time.TimeSource.Monotonic.ValueTimeMark%24minus(kotlin.time.TimeSource.Monotonic.ValueTimeMark)/other) time mark obtained from the same [TimeSource.Monotonic](../index) time source and `this` time mark. The returned duration can be infinite if the time marks are far away from each other and the result doesn't fit into [Duration](../../../-duration/index) type, or if one time mark is infinitely distant, or if both `this` and [other](minus#kotlin.time.TimeSource.Monotonic.ValueTimeMark%24minus(kotlin.time.TimeSource.Monotonic.ValueTimeMark)/other) time marks lie infinitely distant on the opposite sides of the time scale. Two infinitely distant time marks on the same side of the time scale are considered equal and the duration between them is [Duration.ZERO](../../../-duration/-z-e-r-o). kotlin hasNotPassedNow hasNotPassedNow =============== [kotlin-stdlib](../../../../../../../../index) / [kotlin.time](../../../index) / [TimeSource](../../index) / [Monotonic](../index) / [ValueTimeMark](index) / [hasNotPassedNow](has-not-passed-now) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun hasNotPassedNow(): Boolean ``` Returns false if this time mark has not passed according to the time source from which this mark was taken. Note that the value returned by this function can change on subsequent invocations. If the time source is monotonic, it can change only from `true` to `false`, namely, when the time mark becomes behind the current point of the time source. kotlin plus plus ==== [kotlin-stdlib](../../../../../../../../index) / [kotlin.time](../../../index) / [TimeSource](../../index) / [Monotonic](../index) / [ValueTimeMark](index) / <plus> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun plus(duration: Duration): ValueTimeMark ``` Returns a time mark on the same time source that is ahead of this time mark by the specified [duration](../../../-time-mark/plus#kotlin.time.TimeMark%24plus(kotlin.time.Duration)/duration). The returned time mark is more *late* when the [duration](../../../-time-mark/plus#kotlin.time.TimeMark%24plus(kotlin.time.Duration)/duration) is positive, and more *early* when the [duration](../../../-time-mark/plus#kotlin.time.TimeMark%24plus(kotlin.time.Duration)/duration) is negative. If the time mark is adjusted too far in the past or in the future, it may saturate to an infinitely distant time mark. In that case, [elapsedNow](../../../-time-mark/elapsed-now) will return an infinite duration elapsed from such infinitely distant mark. Exceptions ---------- `IllegalArgumentException` - an implementation may throw if a positive infinite duration is added to an infinitely distant past time mark or a negative infinite duration is added to an infinitely distant future time mark. kotlin hasPassedNow hasPassedNow ============ [kotlin-stdlib](../../../../../../../../index) / [kotlin.time](../../../index) / [TimeSource](../../index) / [Monotonic](../index) / [ValueTimeMark](index) / [hasPassedNow](has-passed-now) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun hasPassedNow(): Boolean ``` Returns true if this time mark has passed according to the time source from which this mark was taken. Note that the value returned by this function can change on subsequent invocations. If the time source is monotonic, it can change only from `false` to `true`, namely, when the time mark becomes behind the current point of the time source. kotlin WithComparableMarks WithComparableMarks =================== [kotlin-stdlib](../../../../../../../index) / [kotlin.time](../../index) / [TimeSource](../index) / [WithComparableMarks](index) **Platform and version requirements:** JVM (1.8), JS (1.8), Native (1.8) ``` @ExperimentalTime interface WithComparableMarks : TimeSource ``` A [TimeSource](../index) that returns [time marks](../../-comparable-time-mark/index) that can be compared for difference with each other. Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [markNow](mark-now) Marks a point in time on this time source. ``` abstract fun markNow(): ComparableTimeMark ``` kotlin markNow markNow ======= [kotlin-stdlib](../../../../../../../index) / [kotlin.time](../../index) / [TimeSource](../index) / [WithComparableMarks](index) / [markNow](mark-now) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract fun markNow(): ComparableTimeMark ``` Marks a point in time on this time source. The returned [TimeMark](../../-time-mark/index) instance encapsulates the captured time point and allows querying the duration of time interval [elapsed](../../-time-mark/elapsed-now) from that point. kotlin read read ==== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [AbstractLongTimeSource](index) / <read> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` protected abstract fun read(): Long ``` This protected method should be overridden to return the current reading of the time source expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number in the unit specified by the <unit> property. kotlin AbstractLongTimeSource AbstractLongTimeSource ====================== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [AbstractLongTimeSource](index) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime abstract class AbstractLongTimeSource :      WithComparableMarks ``` An abstract class used to implement time sources that return their readings as [Long](../../kotlin/-long/index#kotlin.Long) values in the specified <unit>. Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [<init>](-init-) An abstract class used to implement time sources that return their readings as [Long](../../kotlin/-long/index#kotlin.Long) values in the specified <unit>. ``` AbstractLongTimeSource(unit: DurationUnit) ``` Properties ---------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <unit> The unit in which this time source's readings are expressed. ``` val unit: DurationUnit ``` Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [markNow](mark-now) Marks a point in time on this time source. ``` open fun markNow(): ComparableTimeMark ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <read> This protected method should be overridden to return the current reading of the time source expressed as a [Long](../../kotlin/-long/index#kotlin.Long) number in the unit specified by the <unit> property. ``` abstract fun read(): Long ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [measureTime](../measure-time) Executes the given function [block](../measure-time#kotlin.time%24measureTime(kotlin.time.TimeSource,%20kotlin.Function0((kotlin.Unit)))/block) and returns the duration of elapsed time interval. ``` fun TimeSource.measureTime(block: () -> Unit): Duration ``` **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [measureTimedValue](../measure-timed-value) Executes the given [block](../measure-timed-value#kotlin.time%24measureTimedValue(kotlin.time.TimeSource,%20kotlin.Function0((kotlin.time.measureTimedValue.T)))/block) and returns an instance of [TimedValue](../-timed-value/index) class, containing both the result of function execution and the duration of elapsed time interval. ``` fun <T> TimeSource.measureTimedValue(     block: () -> T ): TimedValue<T> ``` Inheritors ---------- **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) #### [TestTimeSource](../-test-time-source/index) A time source that has programmatically updatable readings. It is useful as a predictable source of time in tests. ``` class TestTimeSource : AbstractLongTimeSource ``` kotlin unit unit ==== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [AbstractLongTimeSource](index) / <unit> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` protected val unit: DurationUnit ``` The unit in which this time source's readings are expressed. Property -------- `unit` - The unit in which this time source's readings are expressed. kotlin markNow markNow ======= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [AbstractLongTimeSource](index) / [markNow](mark-now) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun markNow(): ComparableTimeMark ``` Marks a point in time on this time source. The returned [TimeMark](../-time-mark/index) instance encapsulates the captured time point and allows querying the duration of time interval [elapsed](../-time-mark/elapsed-now) from that point. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [AbstractLongTimeSource](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` AbstractLongTimeSource(unit: DurationUnit) ``` An abstract class used to implement time sources that return their readings as [Long](../../kotlin/-long/index#kotlin.Long) values in the specified <unit>. kotlin ExperimentalTime ExperimentalTime ================ [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [ExperimentalTime](index) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @Target([AnnotationTarget.CLASS, AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.PROPERTY, AnnotationTarget.FIELD, AnnotationTarget.LOCAL_VARIABLE, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.CONSTRUCTOR, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.TYPEALIAS]) annotation class ExperimentalTime ``` This annotation marks the experimental preview of the standard library API for measuring time and working with durations. Note that this API is in a preview state and has a very high chance of being changed in the future. Do not use it if you develop a library since your library will become binary incompatible with the future versions of the standard library. Any usage of a declaration annotated with `@ExperimentalTime` must be accepted either by annotating that usage with the [OptIn](../../kotlin/-opt-in/index) annotation, e.g. `@OptIn(ExperimentalTime::class)`, or by using the compiler argument `-opt-in=kotlin.time.ExperimentalTime`. Constructors ------------ **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [<init>](-init-) This annotation marks the experimental preview of the standard library API for measuring time and working with durations. ``` ExperimentalTime() ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [ExperimentalTime](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` ExperimentalTime() ``` This annotation marks the experimental preview of the standard library API for measuring time and working with durations. Note that this API is in a preview state and has a very high chance of being changed in the future. Do not use it if you develop a library since your library will become binary incompatible with the future versions of the standard library. Any usage of a declaration annotated with `@ExperimentalTime` must be accepted either by annotating that usage with the [OptIn](../../kotlin/-opt-in/index) annotation, e.g. `@OptIn(ExperimentalTime::class)`, or by using the compiler argument `-opt-in=kotlin.time.ExperimentalTime`. kotlin TimeMark TimeMark ======== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TimeMark](index) **Platform and version requirements:** JVM (1.3), JS (1.3), Native (1.3) ``` @ExperimentalTime interface TimeMark ``` Represents a time point notched on a particular [TimeSource](../-time-source/index). Remains bound to the time source it was taken from and allows querying for the duration of time elapsed from that point (see the function [elapsedNow](elapsed-now)). Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [elapsedNow](elapsed-now) Returns the amount of time passed from this mark measured with the time source from which this mark was taken. ``` abstract fun elapsedNow(): Duration ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [hasNotPassedNow](has-not-passed-now) Returns false if this time mark has not passed according to the time source from which this mark was taken. ``` open fun hasNotPassedNow(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [hasPassedNow](has-passed-now) Returns true if this time mark has passed according to the time source from which this mark was taken. ``` open fun hasPassedNow(): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <minus> Returns a time mark on the same time source that is behind this time mark by the specified [duration](minus#kotlin.time.TimeMark%24minus(kotlin.time.Duration)/duration). ``` open operator fun minus(duration: Duration): TimeMark ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <plus> Returns a time mark on the same time source that is ahead of this time mark by the specified [duration](plus#kotlin.time.TimeMark%24plus(kotlin.time.Duration)/duration). ``` open operator fun plus(duration: Duration): TimeMark ``` Inheritors ---------- **Platform and version requirements:** JVM (1.8), JS (1.8), Native (1.8) #### [ComparableTimeMark](../-comparable-time-mark/index) A [TimeMark](index) that can be compared for difference with other time marks obtained from the same [TimeSource.WithComparableMarks](../-time-source/-with-comparable-marks/index) time source. ``` interface ComparableTimeMark :      TimeMark,     Comparable<ComparableTimeMark> ``` kotlin elapsedNow elapsedNow ========== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TimeMark](index) / [elapsedNow](elapsed-now) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract fun elapsedNow(): Duration ``` Returns the amount of time passed from this mark measured with the time source from which this mark was taken. Note that the value returned by this function can change on subsequent invocations. Exceptions ---------- `IllegalArgumentException` - an implementation may throw if calculating the elapsed time involves adding a positive infinite duration to an infinitely distant past time mark or a negative infinite duration to an infinitely distant future time mark. kotlin minus minus ===== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TimeMark](index) / <minus> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open operator fun minus(duration: Duration): TimeMark ``` Returns a time mark on the same time source that is behind this time mark by the specified [duration](minus#kotlin.time.TimeMark%24minus(kotlin.time.Duration)/duration). The returned time mark is more *early* when the [duration](minus#kotlin.time.TimeMark%24minus(kotlin.time.Duration)/duration) is positive, and more *late* when the [duration](minus#kotlin.time.TimeMark%24minus(kotlin.time.Duration)/duration) is negative. If the time mark is adjusted too far in the past or in the future, it may saturate to an infinitely distant time mark. In that case, [elapsedNow](elapsed-now) will return an infinite duration elapsed from such infinitely distant mark. Exceptions ---------- `IllegalArgumentException` - an implementation may throw if a positive infinite duration is subtracted from an infinitely distant future time mark or a negative infinite duration is subtracted from an infinitely distant past time mark.
programming_docs
kotlin hasNotPassedNow hasNotPassedNow =============== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TimeMark](index) / [hasNotPassedNow](has-not-passed-now) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun hasNotPassedNow(): Boolean ``` Returns false if this time mark has not passed according to the time source from which this mark was taken. Note that the value returned by this function can change on subsequent invocations. If the time source is monotonic, it can change only from `true` to `false`, namely, when the time mark becomes behind the current point of the time source. kotlin plus plus ==== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TimeMark](index) / <plus> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open operator fun plus(duration: Duration): TimeMark ``` Returns a time mark on the same time source that is ahead of this time mark by the specified [duration](plus#kotlin.time.TimeMark%24plus(kotlin.time.Duration)/duration). The returned time mark is more *late* when the [duration](plus#kotlin.time.TimeMark%24plus(kotlin.time.Duration)/duration) is positive, and more *early* when the [duration](plus#kotlin.time.TimeMark%24plus(kotlin.time.Duration)/duration) is negative. If the time mark is adjusted too far in the past or in the future, it may saturate to an infinitely distant time mark. In that case, [elapsedNow](elapsed-now) will return an infinite duration elapsed from such infinitely distant mark. Exceptions ---------- `IllegalArgumentException` - an implementation may throw if a positive infinite duration is added to an infinitely distant past time mark or a negative infinite duration is added to an infinitely distant future time mark. kotlin hasPassedNow hasPassedNow ============ [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [TimeMark](index) / [hasPassedNow](has-passed-now) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open fun hasPassedNow(): Boolean ``` Returns true if this time mark has passed according to the time source from which this mark was taken. Note that the value returned by this function can change on subsequent invocations. If the time source is monotonic, it can change only from `false` to `true`, namely, when the time mark becomes behind the current point of the time source. kotlin ComparableTimeMark ComparableTimeMark ================== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [ComparableTimeMark](index) **Platform and version requirements:** JVM (1.8), JS (1.8), Native (1.8) ``` @ExperimentalTime interface ComparableTimeMark :      TimeMark,     Comparable<ComparableTimeMark> ``` A [TimeMark](../-time-mark/index) that can be compared for difference with other time marks obtained from the same [TimeSource.WithComparableMarks](../-time-source/-with-comparable-marks/index) time source. Functions --------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [compareTo](compare-to) Compares this time mark with the [other](compare-to#kotlin.time.ComparableTimeMark%24compareTo(kotlin.time.ComparableTimeMark)/other) time mark for order. ``` open operator fun compareTo(other: ComparableTimeMark): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <equals> Returns `true` if two time marks from the same time source represent the same moment of time, and `false` otherwise, including the situation when the time marks were obtained from different time sources. ``` abstract fun equals(other: Any?): Boolean ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [hashCode](hash-code) Returns a hash code value for the object. The general contract of `hashCode` is: ``` abstract fun hashCode(): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <minus> Returns a time mark on the same time source that is behind this time mark by the specified [duration](../-time-mark/minus#kotlin.time.TimeMark%24minus(kotlin.time.Duration)/duration). ``` open operator fun minus(     duration: Duration ): ComparableTimeMark ``` Returns the duration elapsed between the [other](minus#kotlin.time.ComparableTimeMark%24minus(kotlin.time.ComparableTimeMark)/other) time mark and `this` time mark. ``` abstract operator fun minus(     other: ComparableTimeMark ): Duration ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### <plus> Returns a time mark on the same time source that is ahead of this time mark by the specified [duration](../-time-mark/plus#kotlin.time.TimeMark%24plus(kotlin.time.Duration)/duration). ``` abstract operator fun plus(     duration: Duration ): ComparableTimeMark ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceAtLeast](../../kotlin.ranges/coerce-at-least) Ensures that this value is not less than the specified [minimumValue](../../kotlin.ranges/coerce-at-least#kotlin.ranges%24coerceAtLeast(kotlin.ranges.coerceAtLeast.T,%20kotlin.ranges.coerceAtLeast.T)/minimumValue). ``` fun <T : Comparable<T>> T.coerceAtLeast(minimumValue: T): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceAtMost](../../kotlin.ranges/coerce-at-most) Ensures that this value is not greater than the specified [maximumValue](../../kotlin.ranges/coerce-at-most#kotlin.ranges%24coerceAtMost(kotlin.ranges.coerceAtMost.T,%20kotlin.ranges.coerceAtMost.T)/maximumValue). ``` fun <T : Comparable<T>> T.coerceAtMost(maximumValue: T): T ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [coerceIn](../../kotlin.ranges/coerce-in) Ensures that this value lies in the specified range [minimumValue](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.coerceIn.T?,%20kotlin.ranges.coerceIn.T?)/minimumValue)..[maximumValue](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.coerceIn.T?,%20kotlin.ranges.coerceIn.T?)/maximumValue). ``` fun <T : Comparable<T>> T.coerceIn(     minimumValue: T?,     maximumValue: T? ): T ``` Ensures that this value lies in the specified [range](../../kotlin.ranges/coerce-in#kotlin.ranges%24coerceIn(kotlin.ranges.coerceIn.T,%20kotlin.ranges.ClosedFloatingPointRange((kotlin.ranges.coerceIn.T)))/range). ``` fun <T : Comparable<T>> T.coerceIn(     range: ClosedFloatingPointRange<T> ): T ``` ``` fun <T : Comparable<T>> T.coerceIn(range: ClosedRange<T>): T ``` **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) #### [compareTo](../../kotlin/compare-to) Compares this object with the specified object for order. Returns zero if this object is equal to the specified [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other) object, a negative number if it's less than [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other), or a positive number if it's greater than [other](../../kotlin/compare-to#kotlin%24compareTo(kotlin.Comparable((kotlin.compareTo.T)),%20kotlin.compareTo.T)/other). ``` infix fun <T> Comparable<T>.compareTo(other: T): Int ``` **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) #### [rangeTo](../../kotlin.ranges/range-to) Creates a range from this [Comparable](../../kotlin/-comparable/index#kotlin.Comparable) value to the specified [that](../../kotlin.ranges/range-to#kotlin.ranges%24rangeTo(kotlin.ranges.rangeTo.T,%20kotlin.ranges.rangeTo.T)/that) value. ``` operator fun <T : Comparable<T>> T.rangeTo(     that: T ): ClosedRange<T> ``` **Platform and version requirements:** JVM (1.7), JS (1.7), Native (1.7) #### [rangeUntil](../../kotlin.ranges/range-until) Creates an open-ended range from this [Comparable](../../kotlin/-comparable/index#kotlin.Comparable) value to the specified [that](../../kotlin.ranges/range-until#kotlin.ranges%24rangeUntil(kotlin.ranges.rangeUntil.T,%20kotlin.ranges.rangeUntil.T)/that) value. ``` operator fun <T : Comparable<T>> T.rangeUntil(     that: T ): OpenEndRange<T> ``` kotlin compareTo compareTo ========= [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [ComparableTimeMark](index) / [compareTo](compare-to) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open operator fun compareTo(other: ComparableTimeMark): Int ``` Compares this time mark with the [other](compare-to#kotlin.time.ComparableTimeMark%24compareTo(kotlin.time.ComparableTimeMark)/other) time mark for order. * Returns zero if this time mark represents *the same moment* of time as the [other](compare-to#kotlin.time.ComparableTimeMark%24compareTo(kotlin.time.ComparableTimeMark)/other) time mark. * Returns a negative number if this time mark is *earlier* than the [other](compare-to#kotlin.time.ComparableTimeMark%24compareTo(kotlin.time.ComparableTimeMark)/other) time mark. * Returns a positive number if this time mark is *later* than the [other](compare-to#kotlin.time.ComparableTimeMark%24compareTo(kotlin.time.ComparableTimeMark)/other) time mark. Note that the other time mark must be obtained from the same time source as this one. Exceptions ---------- `IllegalArgumentException` - if time marks were obtained from different time sources. kotlin hashCode hashCode ======== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [ComparableTimeMark](index) / [hashCode](hash-code) **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract fun hashCode(): Int ``` Returns a hash code value for the object. The general contract of `hashCode` is: * Whenever it is invoked on the same object more than once, the `hashCode` method must consistently return the same integer, provided no information used in `equals` comparisons on the object is modified. * If two objects are equal according to the `equals()` method, then calling the `hashCode` method on each of the two objects must produce the same integer result. kotlin equals equals ====== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [ComparableTimeMark](index) / <equals> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract fun equals(other: Any?): Boolean ``` Returns `true` if two time marks from the same time source represent the same moment of time, and `false` otherwise, including the situation when the time marks were obtained from different time sources. kotlin minus minus ===== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [ComparableTimeMark](index) / <minus> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` open operator fun minus(     duration: Duration ): ComparableTimeMark ``` Returns a time mark on the same time source that is behind this time mark by the specified [duration](../-time-mark/minus#kotlin.time.TimeMark%24minus(kotlin.time.Duration)/duration). The returned time mark is more *early* when the [duration](../-time-mark/minus#kotlin.time.TimeMark%24minus(kotlin.time.Duration)/duration) is positive, and more *late* when the [duration](../-time-mark/minus#kotlin.time.TimeMark%24minus(kotlin.time.Duration)/duration) is negative. If the time mark is adjusted too far in the past or in the future, it may saturate to an infinitely distant time mark. In that case, [elapsedNow](../-time-mark/elapsed-now) will return an infinite duration elapsed from such infinitely distant mark. Exceptions ---------- `IllegalArgumentException` - an implementation may throw if a positive infinite duration is subtracted from an infinitely distant future time mark or a negative infinite duration is subtracted from an infinitely distant past time mark. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract operator fun minus(     other: ComparableTimeMark ): Duration ``` Returns the duration elapsed between the [other](minus#kotlin.time.ComparableTimeMark%24minus(kotlin.time.ComparableTimeMark)/other) time mark and `this` time mark. The returned duration can be infinite if the time marks are far away from each other and the result doesn't fit into [Duration](../-duration/index) type, or if one time mark is infinitely distant, or if both `this` and [other](minus#kotlin.time.ComparableTimeMark%24minus(kotlin.time.ComparableTimeMark)/other) time marks lie infinitely distant on the opposite sides of the time scale. Two infinitely distant time marks on the same side of the time scale are considered equal and the duration between them is [Duration.ZERO](../-duration/-z-e-r-o). Note that the other time mark must be obtained from the same time source as this one. Exceptions ---------- `IllegalArgumentException` - if time marks were obtained from different time sources. kotlin plus plus ==== [kotlin-stdlib](../../../../../../index) / [kotlin.time](../index) / [ComparableTimeMark](index) / <plus> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` abstract operator fun plus(     duration: Duration ): ComparableTimeMark ``` Returns a time mark on the same time source that is ahead of this time mark by the specified [duration](../-time-mark/plus#kotlin.time.TimeMark%24plus(kotlin.time.Duration)/duration). The returned time mark is more *late* when the [duration](../-time-mark/plus#kotlin.time.TimeMark%24plus(kotlin.time.Duration)/duration) is positive, and more *early* when the [duration](../-time-mark/plus#kotlin.time.TimeMark%24plus(kotlin.time.Duration)/duration) is negative. If the time mark is adjusted too far in the past or in the future, it may saturate to an infinitely distant time mark. In that case, [elapsedNow](../-time-mark/elapsed-now) will return an infinite duration elapsed from such infinitely distant mark. Exceptions ---------- `IllegalArgumentException` - an implementation may throw if a positive infinite duration is added to an infinitely distant past time mark or a negative infinite duration is added to an infinitely distant future time mark. kotlin readLine readLine ======== [kotlin-stdlib](../../../../../index) / [kotlin.io](index) / [readLine](read-line) **Platform and version requirements:** JVM (1.0), Native (1.3) ``` fun readLine(): String? ``` Reads a line of input from the standard input stream. **Return** the line read or `null` if the input stream is redirected to a file and the end of file has been reached. kotlin Package kotlin.io Package kotlin.io ================= [kotlin-stdlib](../../../../../index) / [kotlin.io](index) IO API for working with files and streams. Types ----- **Platform and version requirements:** JVM (1.0) #### [FileTreeWalk](-file-tree-walk/index) This class is intended to implement different file traversal methods. It allows to iterate through all files inside a given directory. ``` class FileTreeWalk : Sequence<File> ``` **Platform and version requirements:** JVM (1.0) #### [FileWalkDirection](-file-walk-direction/index) An enumeration to describe possible walk directions. There are two of them: beginning from parents, ending with children, and beginning from children, ending with parents. Both use depth-first search. ``` enum class FileWalkDirection ``` **Platform and version requirements:** JVM (1.0) #### [OnErrorAction](-on-error-action/index) Enum that can be used to specify behaviour of the `copyRecursively()` function in exceptional conditions. ``` enum class OnErrorAction ``` Exceptions ---------- **Platform and version requirements:** JVM (1.0) #### [AccessDeniedException](-access-denied-exception/index) An exception class which is used when we have not enough access for some operation. ``` class AccessDeniedException : FileSystemException ``` **Platform and version requirements:** JVM (1.0) #### [FileAlreadyExistsException](-file-already-exists-exception/index) An exception class which is used when some file to create or copy to already exists. ``` class FileAlreadyExistsException : FileSystemException ``` **Platform and version requirements:** JVM (1.0) #### [FileSystemException](-file-system-exception/index) A base exception class for file system exceptions. ``` open class FileSystemException : IOException ``` **Platform and version requirements:** JVM (1.0) #### [NoSuchFileException](-no-such-file-exception/index) An exception class which is used when file to copy does not exist. ``` class NoSuchFileException : FileSystemException ``` Extensions for External Classes ------------------------------- **Platform and version requirements:** JVM (1.0) #### [java.io.BufferedInputStream](java.io.-buffered-input-stream/index) **Platform and version requirements:** JVM (1.0) #### [java.io.BufferedReader](java.io.-buffered-reader/index) **Platform and version requirements:** JVM (1.0) #### [java.io.File](java.io.-file/index) **Platform and version requirements:** JVM (1.0) #### [java.io.InputStream](java.io.-input-stream/index) **Platform and version requirements:** JVM (1.0) #### [java.io.OutputStream](java.io.-output-stream/index) **Platform and version requirements:** JVM (1.0) #### [java.io.Reader](java.io.-reader/index) **Platform and version requirements:** JVM (1.0) #### [java.io.Writer](java.io.-writer/index) **Platform and version requirements:** JVM (1.0) #### [java.net.URL](java.net.-u-r-l/index) Properties ---------- **Platform and version requirements:** JVM (1.0) #### [DEFAULT\_BUFFER\_SIZE](-d-e-f-a-u-l-t_-b-u-f-f-e-r_-s-i-z-e) Returns the default buffer size when working with buffered streams. ``` const val DEFAULT_BUFFER_SIZE: Int ``` Functions --------- **Platform and version requirements:** JVM (1.0) #### [byteInputStream](byte-input-stream) Creates a new byte input stream for the string. ``` fun String.byteInputStream(     charset: Charset = Charsets.UTF_8 ): ByteArrayInputStream ``` **Platform and version requirements:** JVM (1.0) #### [createTempDir](create-temp-dir) Creates an empty directory in the specified [directory](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/directory), using the given [prefix](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/prefix) and [suffix](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/suffix) to generate its name. ``` fun createTempDir(     prefix: String = "tmp",     suffix: String? = null,     directory: File? = null ): File ``` **Platform and version requirements:** JVM (1.0) #### [createTempFile](create-temp-file) Creates a new empty file in the specified [directory](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/directory), using the given [prefix](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/prefix) and [suffix](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/suffix) to generate its name. ``` fun createTempFile(     prefix: String = "tmp",     suffix: String? = null,     directory: File? = null ): File ``` **Platform and version requirements:** JVM (1.0) #### [inputStream](input-stream) Creates an input stream for reading data from this byte array. ``` fun ByteArray.inputStream(): ByteArrayInputStream ``` Creates an input stream for reading data from the specified portion of this byte array. ``` fun ByteArray.inputStream(     offset: Int,     length: Int ): ByteArrayInputStream ``` #### <print> Prints the given [message](print#kotlin.io%24print(kotlin.Int)/message) to the standard output stream. **Platform and version requirements:** JVM (1.0) ``` fun print(message: Int) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Long) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Byte) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Short) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Char) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Boolean) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Float) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Double) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: CharArray) ``` **Platform and version requirements:** Native (1.3) ``` fun print(message: String) ``` **Platform and version requirements:** JVM (1.0), JS (1.1), Native (1.3) ``` fun print(message: Any?) ``` #### <println> Prints the given [message](println#kotlin.io%24println(kotlin.Int)/message) and the line separator to the standard output stream. **Platform and version requirements:** JVM (1.0) ``` fun println(message: Int) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Long) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Byte) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Short) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Char) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Boolean) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Float) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Double) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: CharArray) ``` **Platform and version requirements:** Native (1.3) ``` fun println(message: String) ``` **Platform and version requirements:** JVM (1.0), JS (1.1), Native (1.3) ``` fun println(message: Any?) ``` Prints the line separator to the standard output stream. **Platform and version requirements:** JVM (1.0), JS (1.1), Native (1.3) ``` fun println() ``` **Platform and version requirements:** JVM (1.0) #### <reader> Creates a new reader for the string. ``` fun String.reader(): StringReader ``` **Platform and version requirements:** JVM (1.0), Native (1.0) #### [readLine](read-line) Reads a line of input from the standard input stream. ``` fun readLine(): String? ``` **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) #### <readln> Reads a line of input from the standard input stream and returns it, or throws a [RuntimeException](../kotlin/-runtime-exception/index#kotlin.RuntimeException) if EOF has already been reached when [readln](readln#kotlin.io%24readln()) is called. ``` fun readln(): String ``` **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) #### [readlnOrNull](readln-or-null) Reads a line of input from the standard input stream and returns it, or return `null` if EOF has already been reached when [readlnOrNull](readln-or-null#kotlin.io%24readlnOrNull()) is called. ``` fun readlnOrNull(): String? ``` **Platform and version requirements:** JVM (1.0) #### <use> Executes the given [block](use#kotlin.io%24use(kotlin.io.use.T,%20kotlin.Function1((kotlin.io.use.T,%20kotlin.io.use.R)))/block) function on this resource and then closes it down correctly whether an exception is thrown or not. ``` fun <T : Closeable?, R> T.use(block: (T) -> R): R ```
programming_docs
kotlin byteInputStream byteInputStream =============== [kotlin-stdlib](../../../../../index) / [kotlin.io](index) / [byteInputStream](byte-input-stream) **Platform and version requirements:** JVM (1.0) ``` fun String.byteInputStream(     charset: Charset = Charsets.UTF_8 ): ByteArrayInputStream ``` Creates a new byte input stream for the string. kotlin createTempFile createTempFile ============== [kotlin-stdlib](../../../../../index) / [kotlin.io](index) / [createTempFile](create-temp-file) **Platform and version requirements:** JVM (1.0) ``` fun createTempFile(     prefix: String = "tmp",     suffix: String? = null,     directory: File? = null ): File ``` **Deprecated:** Avoid creating temporary files in the default temp location with this function due to too wide permissions on the newly created file. Use kotlin.io.path.createTempFile instead or resort to java.io.File.createTempFile. Creates a new empty file in the specified [directory](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/directory), using the given [prefix](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/prefix) and [suffix](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/suffix) to generate its name. If [prefix](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/prefix) is not specified then some unspecified string will be used. If [suffix](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/suffix) is not specified then ".tmp" will be used. If [directory](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/directory) is not specified then the default temporary-file directory will be used. The [prefix](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/prefix) argument, if specified, must be at least three characters long. It is recommended that the prefix be a short, meaningful string such as "job" or "mail". To create the new file, the [prefix](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/prefix) and the [suffix](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/suffix) may first be adjusted to fit the limitations of the underlying platform. **Note:** if the new file is created in a directory that is shared with all users, it may get permissions allowing everyone to read it, thus creating a risk of leaking sensitive information stored in this file. To avoid this, it's recommended either to specify an explicit parent [directory](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/directory) that is not shared widely, or to use alternative ways of creating temporary files, such as [java.nio.file.Files.createTempFile](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#createTempFile-java.lang.String-java.lang.String-java.nio.file.attribute.FileAttribute...-) or the experimental `createTempFile` function in the `kotlin.io.path` package. Exceptions ---------- `IOException` - in case of input/output error. `IllegalArgumentException` - if [prefix](create-temp-file#kotlin.io%24createTempFile(kotlin.String,%20kotlin.String?,%20java.io.File?)/prefix) is shorter than three symbols. **Return** a file object corresponding to a newly-created file. kotlin DEFAULT_BUFFER_SIZE DEFAULT\_BUFFER\_SIZE ===================== [kotlin-stdlib](../../../../../index) / [kotlin.io](index) / [DEFAULT\_BUFFER\_SIZE](-d-e-f-a-u-l-t_-b-u-f-f-e-r_-s-i-z-e) **Platform and version requirements:** JVM (1.0) ``` const val DEFAULT_BUFFER_SIZE: Int ``` Returns the default buffer size when working with buffered streams. kotlin readln readln ====== [kotlin-stdlib](../../../../../index) / [kotlin.io](index) / <readln> **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) ``` fun readln(): String ``` ##### For JVM Reads a line of input from the standard input stream and returns it, or throws a [RuntimeException](../kotlin/-runtime-exception/index#kotlin.RuntimeException) if EOF has already been reached when [readln](readln#kotlin.io%24readln()) is called. LF or CRLF is treated as the line terminator. Line terminator is not included in the returned string. The input is decoded using the system default Charset. A [CharacterCodingException](../kotlin.text/-character-coding-exception/index#kotlin.text.CharacterCodingException) is thrown if input is malformed. ##### For Common Reads a line of input from the standard input stream and returns it, or throws a [RuntimeException](../kotlin/-runtime-exception/index#kotlin.RuntimeException) if EOF has already been reached when [readln](readln#kotlin.io%24readln()) is called. LF or CRLF is treated as the line terminator. Line terminator is not included in the returned string. Currently this function is not supported in Kotlin/JS and throws [UnsupportedOperationException](../kotlin/-unsupported-operation-exception/index#kotlin.UnsupportedOperationException). ##### For Native Reads a line of input from the standard input stream and returns it, or throws a [RuntimeException](../kotlin/-runtime-exception/index#kotlin.RuntimeException) if EOF has already been reached when [readln](readln#kotlin.io%24readln()) is called. LF or CRLF is treated as the line terminator. Line terminator is not included in the returned string. The input is interpreted as UTF-8. Invalid bytes are replaced by the replacement character '\uFFFD'. kotlin print print ===== [kotlin-stdlib](../../../../../index) / [kotlin.io](index) / <print> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun print(message: Any?) ``` Prints the given [message](print#kotlin.io%24print(kotlin.Any?)/message) to the standard output stream. **Platform and version requirements:** JVM (1.0) ``` fun print(message: Int) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Long) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Byte) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Short) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Char) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Boolean) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Float) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: Double) ``` **Platform and version requirements:** JVM (1.0) ``` fun print(message: CharArray) ``` **Platform and version requirements:** Native (1.3) ``` fun print(message: String) ``` Prints the given [message](print#kotlin.io%24print(kotlin.Int)/message) to the standard output stream. kotlin reader reader ====== [kotlin-stdlib](../../../../../index) / [kotlin.io](index) / <reader> **Platform and version requirements:** JVM (1.0) ``` fun String.reader(): StringReader ``` Creates a new reader for the string. kotlin use use === [kotlin-stdlib](../../../../../index) / [kotlin.io](index) / <use> **Platform and version requirements:** JVM (1.0) ``` inline fun <T : Closeable?, R> T.use(block: (T) -> R): R ``` Executes the given [block](use#kotlin.io%24use(kotlin.io.use.T,%20kotlin.Function1((kotlin.io.use.T,%20kotlin.io.use.R)))/block) function on this resource and then closes it down correctly whether an exception is thrown or not. Parameters ---------- `block` - a function to process this [Closeable](https://docs.oracle.com/javase/8/docs/api/java/io/Closeable.html) resource. **Return** the result of [block](use#kotlin.io%24use(kotlin.io.use.T,%20kotlin.Function1((kotlin.io.use.T,%20kotlin.io.use.R)))/block) function invoked on this resource. kotlin createTempDir createTempDir ============= [kotlin-stdlib](../../../../../index) / [kotlin.io](index) / [createTempDir](create-temp-dir) **Platform and version requirements:** JVM (1.0) ``` fun createTempDir(     prefix: String = "tmp",     suffix: String? = null,     directory: File? = null ): File ``` **Deprecated:** Avoid creating temporary directories in the default temp location with this function due to too wide permissions on the newly created directory. Use kotlin.io.path.createTempDirectory instead. Creates an empty directory in the specified [directory](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/directory), using the given [prefix](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/prefix) and [suffix](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/suffix) to generate its name. If [prefix](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/prefix) is not specified then some unspecified string will be used. If [suffix](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/suffix) is not specified then ".tmp" will be used. If [directory](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/directory) is not specified then the default temporary-file directory will be used. The [prefix](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/prefix) argument, if specified, must be at least three characters long. It is recommended that the prefix be a short, meaningful string such as "job" or "mail". To create the new file, the [prefix](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/prefix) and the [suffix](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/suffix) may first be adjusted to fit the limitations of the underlying platform. **Note:** if the new directory is created in a directory that is shared with all users, it may get permissions allowing everyone to read it or its content, thus creating a risk of leaking sensitive information stored in this directory. To avoid this, it's recommended either to specify an explicit parent [directory](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/directory) that is not shared widely, or to use alternative ways of creating temporary files, such as [java.nio.file.Files.createTempDirectory](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#createTempDirectory-java.lang.String-java.nio.file.attribute.FileAttribute...-) or the experimental `createTempDirectory` function in the `kotlin.io.path` package. Exceptions ---------- `IOException` - in case of input/output error. `IllegalArgumentException` - if [prefix](create-temp-dir#kotlin.io%24createTempDir(kotlin.String,%20kotlin.String?,%20java.io.File?)/prefix) is shorter than three symbols. **Return** a file object corresponding to a newly-created directory. kotlin readlnOrNull readlnOrNull ============ [kotlin-stdlib](../../../../../index) / [kotlin.io](index) / [readlnOrNull](readln-or-null) **Platform and version requirements:** JVM (1.6), JS (1.6), Native (1.6) ``` fun readlnOrNull(): String? ``` ##### For JVM Reads a line of input from the standard input stream and returns it, or return `null` if EOF has already been reached when [readlnOrNull](readln-or-null#kotlin.io%24readlnOrNull()) is called. LF or CRLF is treated as the line terminator. Line terminator is not included in the returned string. The input is decoded using the system default Charset. A [CharacterCodingException](../kotlin.text/-character-coding-exception/index#kotlin.text.CharacterCodingException) is thrown if input is malformed. ##### For Common Reads a line of input from the standard input stream and returns it, or return `null` if EOF has already been reached when [readlnOrNull](readln-or-null#kotlin.io%24readlnOrNull()) is called. LF or CRLF is treated as the line terminator. Line terminator is not included in the returned string. Currently this function is not supported in Kotlin/JS and throws [UnsupportedOperationException](../kotlin/-unsupported-operation-exception/index#kotlin.UnsupportedOperationException). ##### For Native Reads a line of input from the standard input stream and returns it, or return `null` if EOF has already been reached when [readlnOrNull](readln-or-null#kotlin.io%24readlnOrNull()) is called. LF or CRLF is treated as the line terminator. Line terminator is not included in the returned string. The input is interpreted as UTF-8. Invalid bytes are replaced by the replacement character '\uFFFD'. kotlin println println ======= [kotlin-stdlib](../../../../../index) / [kotlin.io](index) / <println> **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun println() ``` Prints the line separator to the standard output stream. **Platform and version requirements:** JVM (1.0), JS (1.0), Native (1.0) ``` fun println(message: Any?) ``` Prints the given [message](println#kotlin.io%24println(kotlin.Any?)/message) and the line separator to the standard output stream. **Platform and version requirements:** JVM (1.0) ``` fun println(message: Int) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Long) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Byte) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Short) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Char) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Boolean) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Float) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: Double) ``` **Platform and version requirements:** JVM (1.0) ``` fun println(message: CharArray) ``` **Platform and version requirements:** Native (1.3) ``` fun println(message: String) ``` Prints the given [message](println#kotlin.io%24println(kotlin.Int)/message) and the line separator to the standard output stream. kotlin inputStream inputStream =========== [kotlin-stdlib](../../../../../index) / [kotlin.io](index) / [inputStream](input-stream) **Platform and version requirements:** JVM (1.0) ``` fun ByteArray.inputStream(): ByteArrayInputStream ``` Creates an input stream for reading data from this byte array. **Platform and version requirements:** JVM (1.0) ``` fun ByteArray.inputStream(     offset: Int,     length: Int ): ByteArrayInputStream ``` Creates an input stream for reading data from the specified portion of this byte array. Parameters ---------- `offset` - the start offset of the portion of the array to read. `length` - the length of the portion of the array to read. kotlin FileTreeWalk FileTreeWalk ============ [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileTreeWalk](index) **Platform and version requirements:** JVM (1.0) ``` class FileTreeWalk : Sequence<File> ``` This class is intended to implement different file traversal methods. It allows to iterate through all files inside a given directory. Use [File.walk](../java.io.-file/walk), [File.walkTopDown](../java.io.-file/walk-top-down) or [File.walkBottomUp](../java.io.-file/walk-bottom-up) extension functions to instantiate a `FileTreeWalk` instance. If the file path given is just a file, walker iterates only it. If the file path given does not exist, walker iterates nothing, i.e. it's equivalent to an empty sequence. Functions --------- **Platform and version requirements:** JVM (1.0) #### <iterator> Returns an iterator walking through files. ``` fun iterator(): Iterator<File> ``` **Platform and version requirements:** JVM (1.0) #### [maxDepth](max-depth) Sets the maximum [depth](max-depth#kotlin.io.FileTreeWalk%24maxDepth(kotlin.Int)/depth) of a directory tree to traverse. By default there is no limit. ``` fun maxDepth(depth: Int): FileTreeWalk ``` **Platform and version requirements:** JVM (1.0) #### [onEnter](on-enter) Sets a predicate [function](on-enter#kotlin.io.FileTreeWalk%24onEnter(kotlin.Function1((java.io.File,%20kotlin.Boolean)))/function), that is called on any entered directory before its files are visited and before it is visited itself. ``` fun onEnter(function: (File) -> Boolean): FileTreeWalk ``` **Platform and version requirements:** JVM (1.0) #### [onFail](on-fail) Set a callback [function](on-fail#kotlin.io.FileTreeWalk%24onFail(kotlin.Function2((java.io.File,%20java.io.IOException,%20kotlin.Unit)))/function), that is called on a directory when it's impossible to get its file list. ``` fun onFail(     function: (File, IOException) -> Unit ): FileTreeWalk ``` **Platform and version requirements:** JVM (1.0) #### [onLeave](on-leave) Sets a callback [function](on-leave#kotlin.io.FileTreeWalk%24onLeave(kotlin.Function1((java.io.File,%20kotlin.Unit)))/function), that is called on any left directory after its files are visited and after it is visited itself. ``` fun onLeave(function: (File) -> Unit): FileTreeWalk ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0) #### [filterIsInstance](../../kotlin.sequences/filter-is-instance) Returns a sequence containing all elements that are instances of specified class. ``` fun <R> Sequence<*>.filterIsInstance(     klass: Class<R> ): Sequence<R> ``` **Platform and version requirements:** JVM (1.0) #### [filterIsInstanceTo](../../kotlin.sequences/filter-is-instance-to) Appends all elements that are instances of specified class to the given [destination](../../kotlin.sequences/filter-is-instance-to#kotlin.sequences%24filterIsInstanceTo(kotlin.sequences.Sequence((kotlin.Any?)),%20kotlin.sequences.filterIsInstanceTo.C,%20java.lang.Class((kotlin.sequences.filterIsInstanceTo.R)))/destination). ``` fun <C : MutableCollection<in R>, R> Sequence<*>.filterIsInstanceTo(     destination: C,     klass: Class<R> ): C ``` **Platform and version requirements:** JVM (1.0) #### [maxWith](../../kotlin.sequences/max-with) ``` fun <T> Sequence<T>.maxWith(comparator: Comparator<in T>): T? ``` **Platform and version requirements:** JVM (1.0) #### [minWith](../../kotlin.sequences/min-with) ``` fun <T> Sequence<T>.minWith(comparator: Comparator<in T>): T? ``` **Platform and version requirements:** JVM (1.4) #### [sumOf](../../kotlin.sequences/sum-of) Returns the sum of all values produced by [selector](../../kotlin.sequences/sum-of#kotlin.sequences%24sumOf(kotlin.sequences.Sequence((kotlin.sequences.sumOf.T)),%20kotlin.Function1((kotlin.sequences.sumOf.T,%20java.math.BigDecimal)))/selector) function applied to each element in the sequence. ``` fun <T> Sequence<T>.sumOf(     selector: (T) -> BigDecimal ): BigDecimal ``` ``` fun <T> Sequence<T>.sumOf(     selector: (T) -> BigInteger ): BigInteger ``` **Platform and version requirements:** JVM (1.0) #### [toSortedSet](../../kotlin.sequences/to-sorted-set) Returns a new [SortedSet](https://docs.oracle.com/javase/8/docs/api/java/util/SortedSet.html) of all elements. ``` fun <T> Sequence<T>.toSortedSet(     comparator: Comparator<in T> ): SortedSet<T> ``` kotlin onFail onFail ====== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileTreeWalk](index) / [onFail](on-fail) **Platform and version requirements:** JVM (1.0) ``` fun onFail(     function: (File, IOException) -> Unit ): FileTreeWalk ``` Set a callback [function](on-fail#kotlin.io.FileTreeWalk%24onFail(kotlin.Function2((java.io.File,%20java.io.IOException,%20kotlin.Unit)))/function), that is called on a directory when it's impossible to get its file list. [onEnter](on-enter) and [onLeave](on-leave) callback functions are called even in this case.
programming_docs
kotlin iterator iterator ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileTreeWalk](index) / <iterator> **Platform and version requirements:** JVM (1.0) ``` fun iterator(): Iterator<File> ``` Returns an iterator walking through files. kotlin maxDepth maxDepth ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileTreeWalk](index) / [maxDepth](max-depth) **Platform and version requirements:** JVM (1.0) ``` fun maxDepth(depth: Int): FileTreeWalk ``` Sets the maximum [depth](max-depth#kotlin.io.FileTreeWalk%24maxDepth(kotlin.Int)/depth) of a directory tree to traverse. By default there is no limit. The value must be positive and [Int.MAX\_VALUE](../../kotlin/-int/-m-a-x_-v-a-l-u-e#kotlin.Int.Companion%24MAX_VALUE) is used to specify an unlimited depth. With a value of 1, walker visits only the origin directory and all its immediate children, with a value of 2 also grandchildren, etc. kotlin onLeave onLeave ======= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileTreeWalk](index) / [onLeave](on-leave) **Platform and version requirements:** JVM (1.0) ``` fun onLeave(function: (File) -> Unit): FileTreeWalk ``` Sets a callback [function](on-leave#kotlin.io.FileTreeWalk%24onLeave(kotlin.Function1((java.io.File,%20kotlin.Unit)))/function), that is called on any left directory after its files are visited and after it is visited itself. kotlin onEnter onEnter ======= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileTreeWalk](index) / [onEnter](on-enter) **Platform and version requirements:** JVM (1.0) ``` fun onEnter(function: (File) -> Boolean): FileTreeWalk ``` Sets a predicate [function](on-enter#kotlin.io.FileTreeWalk%24onEnter(kotlin.Function1((java.io.File,%20kotlin.Boolean)))/function), that is called on any entered directory before its files are visited and before it is visited itself. If the [function](on-enter#kotlin.io.FileTreeWalk%24onEnter(kotlin.Function1((java.io.File,%20kotlin.Boolean)))/function) returns `false` the directory is not entered and neither it nor its files are visited. kotlin bufferedWriter bufferedWriter ============== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.OutputStream](index) / [bufferedWriter](buffered-writer) **Platform and version requirements:** JVM (1.0) ``` fun OutputStream.bufferedWriter(     charset: Charset = Charsets.UTF_8 ): BufferedWriter ``` Creates a buffered writer on this output stream using UTF-8 or the specified [charset](buffered-writer#kotlin.io%24bufferedWriter(java.io.OutputStream,%20java.nio.charset.Charset)/charset). kotlin Extensions for java.io.OutputStream Extensions for java.io.OutputStream =================================== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.OutputStream](index) **Platform and version requirements:** JVM (1.0) #### <buffered> Creates a buffered output stream wrapping this stream. ``` fun OutputStream.buffered(     bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedOutputStream ``` **Platform and version requirements:** JVM (1.0) #### [bufferedWriter](buffered-writer) Creates a buffered writer on this output stream using UTF-8 or the specified [charset](buffered-writer#kotlin.io%24bufferedWriter(java.io.OutputStream,%20java.nio.charset.Charset)/charset). ``` fun OutputStream.bufferedWriter(     charset: Charset = Charsets.UTF_8 ): BufferedWriter ``` **Platform and version requirements:** JVM (1.0) #### <writer> Creates a writer on this output stream using UTF-8 or the specified [charset](writer#kotlin.io%24writer(java.io.OutputStream,%20java.nio.charset.Charset)/charset). ``` fun OutputStream.writer(     charset: Charset = Charsets.UTF_8 ): OutputStreamWriter ``` kotlin writer writer ====== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.OutputStream](index) / <writer> **Platform and version requirements:** JVM (1.0) ``` fun OutputStream.writer(     charset: Charset = Charsets.UTF_8 ): OutputStreamWriter ``` Creates a writer on this output stream using UTF-8 or the specified [charset](writer#kotlin.io%24writer(java.io.OutputStream,%20java.nio.charset.Charset)/charset). kotlin buffered buffered ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.OutputStream](index) / <buffered> **Platform and version requirements:** JVM (1.0) ``` fun OutputStream.buffered(     bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedOutputStream ``` Creates a buffered output stream wrapping this stream. Parameters ---------- `bufferSize` - the buffer size to use. kotlin FileSystemException FileSystemException =================== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileSystemException](index) **Platform and version requirements:** JVM (1.0) ``` open class FileSystemException : IOException ``` A base exception class for file system exceptions. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) A base exception class for file system exceptions. ``` FileSystemException(     file: File,     other: File? = null,     reason: String? = null) ``` Properties ---------- **Platform and version requirements:** JVM (1.0) #### <file> the file on which the failed operation was performed. ``` val file: File ``` **Platform and version requirements:** JVM (1.0) #### <other> the second file involved in the operation, if any (for example, the target of a copy or move) ``` val other: File? ``` **Platform and version requirements:** JVM (1.0) #### <reason> the description of the error ``` val reason: String? ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [stackTrace](../../kotlin/stack-trace) Returns an array of stack trace elements representing the stack trace pertaining to this throwable. ``` val Throwable.stackTrace: Array<StackTraceElement> ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0) #### [printStackTrace](../../kotlin/print-stack-trace) Prints the [detailed description](../../kotlin/stack-trace-to-string#kotlin%24stackTraceToString(kotlin.Throwable)) of this throwable to the specified [writer](../../kotlin/print-stack-trace#kotlin%24printStackTrace(kotlin.Throwable,%20java.io.PrintWriter)/writer). ``` fun Throwable.printStackTrace(writer: PrintWriter) ``` Prints the [detailed description](../../kotlin/stack-trace-to-string#kotlin%24stackTraceToString(kotlin.Throwable)) of this throwable to the specified [stream](../../kotlin/print-stack-trace#kotlin%24printStackTrace(kotlin.Throwable,%20java.io.PrintStream)/stream). ``` fun Throwable.printStackTrace(stream: PrintStream) ``` Inheritors ---------- **Platform and version requirements:** JVM (1.0) #### [AccessDeniedException](../-access-denied-exception/index) An exception class which is used when we have not enough access for some operation. ``` class AccessDeniedException : FileSystemException ``` **Platform and version requirements:** JVM (1.0) #### [FileAlreadyExistsException](../-file-already-exists-exception/index) An exception class which is used when some file to create or copy to already exists. ``` class FileAlreadyExistsException : FileSystemException ``` **Platform and version requirements:** JVM (1.0) #### [NoSuchFileException](../-no-such-file-exception/index) An exception class which is used when file to copy does not exist. ``` class NoSuchFileException : FileSystemException ``` kotlin file file ==== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileSystemException](index) / <file> **Platform and version requirements:** JVM (1.0) ``` val file: File ``` the file on which the failed operation was performed. Property -------- `file` - the file on which the failed operation was performed. kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileSystemException](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` FileSystemException(     file: File,     other: File? = null,     reason: String? = null) ``` A base exception class for file system exceptions. kotlin reason reason ====== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileSystemException](index) / <reason> **Platform and version requirements:** JVM (1.0) ``` val reason: String? ``` the description of the error Property -------- `reason` - the description of the error kotlin other other ===== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileSystemException](index) / <other> **Platform and version requirements:** JVM (1.0) ``` val other: File? ``` the second file involved in the operation, if any (for example, the target of a copy or move) Property -------- `other` - the second file involved in the operation, if any (for example, the target of a copy or move) kotlin forEachLine forEachLine =========== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.Reader](index) / [forEachLine](for-each-line) **Platform and version requirements:** JVM (1.0) ``` fun Reader.forEachLine(action: (String) -> Unit) ``` Iterates through each line of this reader, calls [action](for-each-line#kotlin.io%24forEachLine(java.io.Reader,%20kotlin.Function1((kotlin.String,%20kotlin.Unit)))/action) for each line read and closes the [Reader](https://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) when it's completed. Parameters ---------- `action` - function to process file lines. kotlin Extensions for java.io.Reader Extensions for java.io.Reader ============================= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.Reader](index) **Platform and version requirements:** JVM (1.0) #### <buffered> Returns a buffered reader wrapping this Reader, or this Reader itself if it is already buffered. ``` fun Reader.buffered(     bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedReader ``` **Platform and version requirements:** JVM (1.0) #### [copyTo](copy-to) Copies this reader to the given [out](copy-to#kotlin.io%24copyTo(java.io.Reader,%20java.io.Writer,%20kotlin.Int)/out) writer, returning the number of characters copied. ``` fun Reader.copyTo(     out: Writer,     bufferSize: Int = DEFAULT_BUFFER_SIZE ): Long ``` **Platform and version requirements:** JVM (1.0) #### [forEachLine](for-each-line) Iterates through each line of this reader, calls [action](for-each-line#kotlin.io%24forEachLine(java.io.Reader,%20kotlin.Function1((kotlin.String,%20kotlin.Unit)))/action) for each line read and closes the [Reader](https://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) when it's completed. ``` fun Reader.forEachLine(action: (String) -> Unit) ``` **Platform and version requirements:** JVM (1.0) #### [readLines](read-lines) Reads this reader content as a list of lines. ``` fun Reader.readLines(): List<String> ``` **Platform and version requirements:** JVM (1.0) #### [readText](read-text) Reads this reader completely as a String. ``` fun Reader.readText(): String ``` **Platform and version requirements:** JVM (1.0) #### [useLines](use-lines) Calls the [block](use-lines#kotlin.io%24useLines(java.io.Reader,%20kotlin.Function1((kotlin.sequences.Sequence((kotlin.String)),%20kotlin.io.useLines.T)))/block) callback giving it a sequence of all the lines in this file and closes the reader once the processing is complete. ``` fun <T> Reader.useLines(block: (Sequence<String>) -> T): T ``` kotlin buffered buffered ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.Reader](index) / <buffered> **Platform and version requirements:** JVM (1.0) ``` fun Reader.buffered(     bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedReader ``` Returns a buffered reader wrapping this Reader, or this Reader itself if it is already buffered. kotlin copyTo copyTo ====== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.Reader](index) / [copyTo](copy-to) **Platform and version requirements:** JVM (1.0) ``` fun Reader.copyTo(     out: Writer,     bufferSize: Int = DEFAULT_BUFFER_SIZE ): Long ``` Copies this reader to the given [out](copy-to#kotlin.io%24copyTo(java.io.Reader,%20java.io.Writer,%20kotlin.Int)/out) writer, returning the number of characters copied. **Note** it is the caller's responsibility to close both of these resources. Parameters ---------- `out` - writer to write to. `bufferSize` - size of character buffer to use in process. **Return** number of characters copied. kotlin useLines useLines ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.Reader](index) / [useLines](use-lines) **Platform and version requirements:** JVM (1.0) ``` inline fun <T> Reader.useLines(     block: (Sequence<String>) -> T ): T ``` Calls the [block](use-lines#kotlin.io%24useLines(java.io.Reader,%20kotlin.Function1((kotlin.sequences.Sequence((kotlin.String)),%20kotlin.io.useLines.T)))/block) callback giving it a sequence of all the lines in this file and closes the reader once the processing is complete. **Return** the value returned by [block](use-lines#kotlin.io%24useLines(java.io.Reader,%20kotlin.Function1((kotlin.sequences.Sequence((kotlin.String)),%20kotlin.io.useLines.T)))/block). kotlin readText readText ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.Reader](index) / [readText](read-text) **Platform and version requirements:** JVM (1.0) ``` fun Reader.readText(): String ``` Reads this reader completely as a String. *Note*: It is the caller's responsibility to close this reader. **Return** the string with corresponding file content. kotlin readLines readLines ========= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.Reader](index) / [readLines](read-lines) **Platform and version requirements:** JVM (1.0) ``` fun Reader.readLines(): List<String> ``` Reads this reader content as a list of lines. Do not use this function for huge files. kotlin Extensions for java.net.URL Extensions for java.net.URL =========================== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.net.URL](index) **Platform and version requirements:** JVM (1.0) #### [readBytes](read-bytes) Reads the entire content of the URL as byte array. ``` fun URL.readBytes(): ByteArray ``` **Platform and version requirements:** JVM (1.0) #### [readText](read-text) Reads the entire content of this URL as a String using UTF-8 or the specified [charset](read-text#kotlin.io%24readText(java.net.URL,%20java.nio.charset.Charset)/charset). ``` fun URL.readText(charset: Charset = Charsets.UTF_8): String ``` kotlin readText readText ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.net.URL](index) / [readText](read-text) **Platform and version requirements:** JVM (1.0) ``` fun URL.readText(charset: Charset = Charsets.UTF_8): String ``` Reads the entire content of this URL as a String using UTF-8 or the specified [charset](read-text#kotlin.io%24readText(java.net.URL,%20java.nio.charset.Charset)/charset). This method is not recommended on huge files. Parameters ---------- `charset` - a character set to use. **Return** a string with this URL entire content. kotlin readBytes readBytes ========= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.net.URL](index) / [readBytes](read-bytes) **Platform and version requirements:** JVM (1.0) ``` fun URL.readBytes(): ByteArray ``` Reads the entire content of the URL as byte array. This method is not recommended on huge files. **Return** a byte array with this URL entire content. kotlin Extensions for java.io.BufferedInputStream Extensions for java.io.BufferedInputStream ========================================== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.BufferedInputStream](index) **Platform and version requirements:** JVM (1.0) #### <iterator> Returns an [Iterator](../../kotlin.collections/-iterator/index#kotlin.collections.Iterator) of bytes read from this input stream. ``` operator fun BufferedInputStream.iterator(): ByteIterator ``` kotlin iterator iterator ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.BufferedInputStream](index) / <iterator> **Platform and version requirements:** JVM (1.0) ``` operator fun BufferedInputStream.iterator(): ByteIterator ``` Returns an [Iterator](../../kotlin.collections/-iterator/index#kotlin.collections.Iterator) of bytes read from this input stream. kotlin NoSuchFileException NoSuchFileException =================== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [NoSuchFileException](index) **Platform and version requirements:** JVM (1.0) ``` class NoSuchFileException : FileSystemException ``` An exception class which is used when file to copy does not exist. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) An exception class which is used when file to copy does not exist. ``` NoSuchFileException(     file: File,     other: File? = null,     reason: String? = null) ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [stackTrace](../../kotlin/stack-trace) Returns an array of stack trace elements representing the stack trace pertaining to this throwable. ``` val Throwable.stackTrace: Array<StackTraceElement> ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0) #### [printStackTrace](../../kotlin/print-stack-trace) Prints the [detailed description](../../kotlin/stack-trace-to-string#kotlin%24stackTraceToString(kotlin.Throwable)) of this throwable to the specified [writer](../../kotlin/print-stack-trace#kotlin%24printStackTrace(kotlin.Throwable,%20java.io.PrintWriter)/writer). ``` fun Throwable.printStackTrace(writer: PrintWriter) ``` Prints the [detailed description](../../kotlin/stack-trace-to-string#kotlin%24stackTraceToString(kotlin.Throwable)) of this throwable to the specified [stream](../../kotlin/print-stack-trace#kotlin%24printStackTrace(kotlin.Throwable,%20java.io.PrintStream)/stream). ``` fun Throwable.printStackTrace(stream: PrintStream) ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [NoSuchFileException](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` NoSuchFileException(     file: File,     other: File? = null,     reason: String? = null) ``` An exception class which is used when file to copy does not exist. kotlin AccessDeniedException AccessDeniedException ===================== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [AccessDeniedException](index) **Platform and version requirements:** JVM (1.0) ``` class AccessDeniedException : FileSystemException ``` An exception class which is used when we have not enough access for some operation. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) An exception class which is used when we have not enough access for some operation. ``` AccessDeniedException(     file: File,     other: File? = null,     reason: String? = null) ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [stackTrace](../../kotlin/stack-trace) Returns an array of stack trace elements representing the stack trace pertaining to this throwable. ``` val Throwable.stackTrace: Array<StackTraceElement> ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0) #### [printStackTrace](../../kotlin/print-stack-trace) Prints the [detailed description](../../kotlin/stack-trace-to-string#kotlin%24stackTraceToString(kotlin.Throwable)) of this throwable to the specified [writer](../../kotlin/print-stack-trace#kotlin%24printStackTrace(kotlin.Throwable,%20java.io.PrintWriter)/writer). ``` fun Throwable.printStackTrace(writer: PrintWriter) ``` Prints the [detailed description](../../kotlin/stack-trace-to-string#kotlin%24stackTraceToString(kotlin.Throwable)) of this throwable to the specified [stream](../../kotlin/print-stack-trace#kotlin%24printStackTrace(kotlin.Throwable,%20java.io.PrintStream)/stream). ``` fun Throwable.printStackTrace(stream: PrintStream) ```
programming_docs
kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [AccessDeniedException](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` AccessDeniedException(     file: File,     other: File? = null,     reason: String? = null) ``` An exception class which is used when we have not enough access for some operation. kotlin FileAlreadyExistsException FileAlreadyExistsException ========================== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileAlreadyExistsException](index) **Platform and version requirements:** JVM (1.0) ``` class FileAlreadyExistsException : FileSystemException ``` An exception class which is used when some file to create or copy to already exists. Constructors ------------ **Platform and version requirements:** JVM (1.0) #### [<init>](-init-) An exception class which is used when some file to create or copy to already exists. ``` FileAlreadyExistsException(     file: File,     other: File? = null,     reason: String? = null) ``` Extension Properties -------------------- **Platform and version requirements:** JVM (1.0) #### [stackTrace](../../kotlin/stack-trace) Returns an array of stack trace elements representing the stack trace pertaining to this throwable. ``` val Throwable.stackTrace: Array<StackTraceElement> ``` Extension Functions ------------------- **Platform and version requirements:** JVM (1.0) #### [printStackTrace](../../kotlin/print-stack-trace) Prints the [detailed description](../../kotlin/stack-trace-to-string#kotlin%24stackTraceToString(kotlin.Throwable)) of this throwable to the specified [writer](../../kotlin/print-stack-trace#kotlin%24printStackTrace(kotlin.Throwable,%20java.io.PrintWriter)/writer). ``` fun Throwable.printStackTrace(writer: PrintWriter) ``` Prints the [detailed description](../../kotlin/stack-trace-to-string#kotlin%24stackTraceToString(kotlin.Throwable)) of this throwable to the specified [stream](../../kotlin/print-stack-trace#kotlin%24printStackTrace(kotlin.Throwable,%20java.io.PrintStream)/stream). ``` fun Throwable.printStackTrace(stream: PrintStream) ``` kotlin <init> <init> ====== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileAlreadyExistsException](index) / [<init>](-init-) **Platform and version requirements:** JVM (1.0) ``` FileAlreadyExistsException(     file: File,     other: File? = null,     reason: String? = null) ``` An exception class which is used when some file to create or copy to already exists. kotlin Extensions for java.io.BufferedReader Extensions for java.io.BufferedReader ===================================== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.BufferedReader](index) **Platform and version requirements:** JVM (1.0) #### [lineSequence](line-sequence) Returns a sequence of corresponding file lines. ``` fun BufferedReader.lineSequence(): Sequence<String> ``` kotlin lineSequence lineSequence ============ [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.BufferedReader](index) / [lineSequence](line-sequence) **Platform and version requirements:** JVM (1.0) ``` fun BufferedReader.lineSequence(): Sequence<String> ``` Returns a sequence of corresponding file lines. *Note*: the caller must close the underlying `BufferedReader` when the iteration is finished; as the user may not complete the iteration loop (e.g. using a method like find() or any() on the iterator may terminate the iteration early. We suggest you try the method [useLines](../java.io.-file/use-lines) instead which closes the stream when the processing is complete. **Return** a sequence of corresponding file lines. The sequence returned can be iterated only once. kotlin OnErrorAction OnErrorAction ============= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [OnErrorAction](index) **Platform and version requirements:** JVM (1.0) ``` enum class OnErrorAction ``` Enum that can be used to specify behaviour of the `copyRecursively()` function in exceptional conditions. Enum Values ----------- **Platform and version requirements:** JVM (1.0) #### [SKIP](-s-k-i-p) Skip this file and go to the next. **Platform and version requirements:** JVM (1.0) #### [TERMINATE](-t-e-r-m-i-n-a-t-e) Terminate the evaluation of the function. Extension Properties -------------------- **Platform and version requirements:** JVM (1.7) #### [declaringJavaClass](../../kotlin.jvm/declaring-java-class) Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance of the enum the given constant belongs to. ``` val <E : Enum<E>> Enum<E>.declaringJavaClass: Class<E> ``` kotlin SKIP SKIP ==== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [OnErrorAction](index) / [SKIP](-s-k-i-p) **Platform and version requirements:** JVM (1.0) ``` SKIP ``` Skip this file and go to the next. kotlin TERMINATE TERMINATE ========= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [OnErrorAction](index) / [TERMINATE](-t-e-r-m-i-n-a-t-e) **Platform and version requirements:** JVM (1.0) ``` TERMINATE ``` Terminate the evaluation of the function. kotlin FileWalkDirection FileWalkDirection ================= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileWalkDirection](index) **Platform and version requirements:** JVM (1.0) ``` enum class FileWalkDirection ``` An enumeration to describe possible walk directions. There are two of them: beginning from parents, ending with children, and beginning from children, ending with parents. Both use depth-first search. Enum Values ----------- **Platform and version requirements:** JVM (1.0) #### [TOP\_DOWN](-t-o-p_-d-o-w-n) Depth-first search, directory is visited BEFORE its files **Platform and version requirements:** JVM (1.0) #### [BOTTOM\_UP](-b-o-t-t-o-m_-u-p) Depth-first search, directory is visited AFTER its files Extension Properties -------------------- **Platform and version requirements:** JVM (1.7) #### [declaringJavaClass](../../kotlin.jvm/declaring-java-class) Returns a Java [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) instance of the enum the given constant belongs to. ``` val <E : Enum<E>> Enum<E>.declaringJavaClass: Class<E> ``` kotlin BOTTOM_UP BOTTOM\_UP ========== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileWalkDirection](index) / [BOTTOM\_UP](-b-o-t-t-o-m_-u-p) **Platform and version requirements:** JVM (1.0) ``` BOTTOM_UP ``` Depth-first search, directory is visited AFTER its files kotlin TOP_DOWN TOP\_DOWN ========= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [FileWalkDirection](index) / [TOP\_DOWN](-t-o-p_-d-o-w-n) **Platform and version requirements:** JVM (1.0) ``` TOP_DOWN ``` Depth-first search, directory is visited BEFORE its files kotlin bufferedReader bufferedReader ============== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.InputStream](index) / [bufferedReader](buffered-reader) **Platform and version requirements:** JVM (1.0) ``` fun InputStream.bufferedReader(     charset: Charset = Charsets.UTF_8 ): BufferedReader ``` Creates a buffered reader on this input stream using UTF-8 or the specified [charset](buffered-reader#kotlin.io%24bufferedReader(java.io.InputStream,%20java.nio.charset.Charset)/charset). kotlin Extensions for java.io.InputStream Extensions for java.io.InputStream ================================== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.InputStream](index) **Platform and version requirements:** JVM (1.0) #### <buffered> Creates a buffered input stream wrapping this stream. ``` fun InputStream.buffered(     bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedInputStream ``` **Platform and version requirements:** JVM (1.0) #### [bufferedReader](buffered-reader) Creates a buffered reader on this input stream using UTF-8 or the specified [charset](buffered-reader#kotlin.io%24bufferedReader(java.io.InputStream,%20java.nio.charset.Charset)/charset). ``` fun InputStream.bufferedReader(     charset: Charset = Charsets.UTF_8 ): BufferedReader ``` **Platform and version requirements:** JVM (1.0) #### [copyTo](copy-to) Copies this stream to the given output stream, returning the number of bytes copied ``` fun InputStream.copyTo(     out: OutputStream,     bufferSize: Int = DEFAULT_BUFFER_SIZE ): Long ``` **Platform and version requirements:** JVM (1.0) #### [readBytes](read-bytes) Reads this stream completely into a byte array. ``` fun InputStream.readBytes(     estimatedSize: Int = DEFAULT_BUFFER_SIZE ): ByteArray ``` ``` fun InputStream.readBytes(): ByteArray ``` **Platform and version requirements:** JVM (1.0) #### <reader> Creates a reader on this input stream using UTF-8 or the specified [charset](reader#kotlin.io%24reader(java.io.InputStream,%20java.nio.charset.Charset)/charset). ``` fun InputStream.reader(     charset: Charset = Charsets.UTF_8 ): InputStreamReader ``` kotlin reader reader ====== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.InputStream](index) / <reader> **Platform and version requirements:** JVM (1.0) ``` fun InputStream.reader(     charset: Charset = Charsets.UTF_8 ): InputStreamReader ``` Creates a reader on this input stream using UTF-8 or the specified [charset](reader#kotlin.io%24reader(java.io.InputStream,%20java.nio.charset.Charset)/charset). kotlin buffered buffered ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.InputStream](index) / <buffered> **Platform and version requirements:** JVM (1.0) ``` fun InputStream.buffered(     bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedInputStream ``` Creates a buffered input stream wrapping this stream. Parameters ---------- `bufferSize` - the buffer size to use. kotlin copyTo copyTo ====== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.InputStream](index) / [copyTo](copy-to) **Platform and version requirements:** JVM (1.0) ``` fun InputStream.copyTo(     out: OutputStream,     bufferSize: Int = DEFAULT_BUFFER_SIZE ): Long ``` Copies this stream to the given output stream, returning the number of bytes copied **Note** It is the caller's responsibility to close both of these resources. kotlin readBytes readBytes ========= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.InputStream](index) / [readBytes](read-bytes) **Platform and version requirements:** JVM (1.0) ``` @DeprecatedSinceKotlin("1.3", "1.5") fun InputStream.readBytes(     estimatedSize: Int = DEFAULT_BUFFER_SIZE ): ByteArray ``` **Deprecated:** Use readBytes() overload without estimatedSize parameter ``` fun InputStream.readBytes(): ByteArray ``` Reads this stream completely into a byte array. **Note**: It is the caller's responsibility to close this stream. kotlin Extensions for java.io.Writer Extensions for java.io.Writer ============================= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.Writer](index) **Platform and version requirements:** JVM (1.0) #### <buffered> Returns a buffered writer wrapping this Writer, or this Writer itself if it is already buffered. ``` fun Writer.buffered(     bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedWriter ``` kotlin buffered buffered ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.Writer](index) / <buffered> **Platform and version requirements:** JVM (1.0) ``` fun Writer.buffered(     bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedWriter ``` Returns a buffered writer wrapping this Writer, or this Writer itself if it is already buffered. kotlin forEachLine forEachLine =========== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [forEachLine](for-each-line) **Platform and version requirements:** JVM (1.0) ``` fun File.forEachLine(     charset: Charset = Charsets.UTF_8,     action: (line: String) -> Unit) ``` Reads this file line by line using the specified [charset](for-each-line#kotlin.io%24forEachLine(java.io.File,%20java.nio.charset.Charset,%20kotlin.Function1((kotlin.String,%20kotlin.Unit)))/charset) and calls [action](for-each-line#kotlin.io%24forEachLine(java.io.File,%20java.nio.charset.Charset,%20kotlin.Function1((kotlin.String,%20kotlin.Unit)))/action) for each line. Default charset is UTF-8. You may use this function on huge files. Parameters ---------- `charset` - character set to use. `action` - function to process file lines. kotlin printWriter printWriter =========== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [printWriter](print-writer) **Platform and version requirements:** JVM (1.0) ``` fun File.printWriter(     charset: Charset = Charsets.UTF_8 ): PrintWriter ``` Returns a new [PrintWriter](https://docs.oracle.com/javase/8/docs/api/java/io/PrintWriter.html) for writing the content of this file. kotlin isRooted isRooted ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [isRooted](is-rooted) **Platform and version requirements:** JVM (1.0) ``` val File.isRooted: Boolean ``` Determines whether this file has a root or it represents a relative path. Returns `true` when this file has non-empty root. kotlin bufferedWriter bufferedWriter ============== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [bufferedWriter](buffered-writer) **Platform and version requirements:** JVM (1.0) ``` fun File.bufferedWriter(     charset: Charset = Charsets.UTF_8,     bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedWriter ``` Returns a new [BufferedWriter](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedWriter.html) for writing the content of this file. Parameters ---------- `bufferSize` - necessary size of the buffer. kotlin extension extension ========= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / <extension> **Platform and version requirements:** JVM (1.0) ``` val File.extension: String ``` Returns the extension of this file (not including the dot), or an empty string if it doesn't have one. kotlin forEachBlock forEachBlock ============ [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [forEachBlock](for-each-block) **Platform and version requirements:** JVM (1.0) ``` fun File.forEachBlock(     action: (buffer: ByteArray, bytesRead: Int) -> Unit) ``` Reads file by byte blocks and calls [action](for-each-block#kotlin.io%24forEachBlock(java.io.File,%20kotlin.Function2((kotlin.ByteArray,%20kotlin.Int,%20kotlin.Unit)))/action) for each block read. Block has default size which is implementation-dependent. This functions passes the byte array and amount of bytes in the array to the [action](for-each-block#kotlin.io%24forEachBlock(java.io.File,%20kotlin.Function2((kotlin.ByteArray,%20kotlin.Int,%20kotlin.Unit)))/action) function. You can use this function for huge files. Parameters ---------- `action` - function to process file blocks. **Platform and version requirements:** JVM (1.0) ``` fun File.forEachBlock(     blockSize: Int,     action: (buffer: ByteArray, bytesRead: Int) -> Unit) ``` Reads file by byte blocks and calls [action](for-each-block#kotlin.io%24forEachBlock(java.io.File,%20kotlin.Int,%20kotlin.Function2((kotlin.ByteArray,%20kotlin.Int,%20kotlin.Unit)))/action) for each block read. This functions passes the byte array and amount of bytes in the array to the [action](for-each-block#kotlin.io%24forEachBlock(java.io.File,%20kotlin.Int,%20kotlin.Function2((kotlin.ByteArray,%20kotlin.Int,%20kotlin.Unit)))/action) function. You can use this function for huge files. Parameters ---------- `action` - function to process file blocks. `blockSize` - size of a block, replaced by 512 if it's less, 4096 by default. kotlin bufferedReader bufferedReader ============== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [bufferedReader](buffered-reader) **Platform and version requirements:** JVM (1.0) ``` fun File.bufferedReader(     charset: Charset = Charsets.UTF_8,     bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedReader ``` Returns a new [BufferedReader](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html) for reading the content of this file. Parameters ---------- `bufferSize` - necessary size of the buffer. kotlin deleteRecursively deleteRecursively ================= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [deleteRecursively](delete-recursively) **Platform and version requirements:** JVM (1.0) ``` fun File.deleteRecursively(): Boolean ``` Delete this file with all its children. Note that if this operation fails then partial deletion may have taken place. **Return** `true` if the file or directory is successfully deleted, `false` otherwise. kotlin Extensions for java.io.File Extensions for java.io.File =========================== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) **Platform and version requirements:** JVM (1.0) #### [appendBytes](append-bytes) Appends an [array](append-bytes#kotlin.io%24appendBytes(java.io.File,%20kotlin.ByteArray)/array) of bytes to the content of this file. ``` fun File.appendBytes(array: ByteArray) ``` **Platform and version requirements:** JVM (1.0) #### [appendText](append-text) Appends [text](append-text#kotlin.io%24appendText(java.io.File,%20kotlin.String,%20java.nio.charset.Charset)/text) to the content of this file using UTF-8 or the specified [charset](append-text#kotlin.io%24appendText(java.io.File,%20kotlin.String,%20java.nio.charset.Charset)/charset). ``` fun File.appendText(     text: String,     charset: Charset = Charsets.UTF_8) ``` **Platform and version requirements:** JVM (1.0) #### [bufferedReader](buffered-reader) Returns a new [BufferedReader](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html) for reading the content of this file. ``` fun File.bufferedReader(     charset: Charset = Charsets.UTF_8,     bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedReader ``` **Platform and version requirements:** JVM (1.0) #### [bufferedWriter](buffered-writer) Returns a new [BufferedWriter](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedWriter.html) for writing the content of this file. ``` fun File.bufferedWriter(     charset: Charset = Charsets.UTF_8,     bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedWriter ``` **Platform and version requirements:** JVM (1.0) #### [copyRecursively](copy-recursively) Copies this file with all its children to the specified destination [target](copy-recursively#kotlin.io%24copyRecursively(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Function2((java.io.File,%20java.io.IOException,%20kotlin.io.OnErrorAction)))/target) path. If some directories on the way to the destination are missing, then they will be created. ``` fun File.copyRecursively(     target: File,     overwrite: Boolean = false,     onError: (File, IOException) -> OnErrorAction = { _, exception -> throw exception } ): Boolean ``` **Platform and version requirements:** JVM (1.0) #### [copyTo](copy-to) Copies this file to the given [target](copy-to#kotlin.io%24copyTo(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Int)/target) file. ``` fun File.copyTo(     target: File,     overwrite: Boolean = false,     bufferSize: Int = DEFAULT_BUFFER_SIZE ): File ``` **Platform and version requirements:** JVM (1.0) #### [deleteRecursively](delete-recursively) Delete this file with all its children. Note that if this operation fails then partial deletion may have taken place. ``` fun File.deleteRecursively(): Boolean ``` **Platform and version requirements:** JVM (1.0) #### [endsWith](ends-with) Determines whether this file path ends with the path of [other](ends-with#kotlin.io%24endsWith(java.io.File,%20java.io.File)/other) file. ``` fun File.endsWith(other: File): Boolean ``` Determines whether this file belongs to the same root as [other](ends-with#kotlin.io%24endsWith(java.io.File,%20kotlin.String)/other) and ends with all components of [other](ends-with#kotlin.io%24endsWith(java.io.File,%20kotlin.String)/other) in the same order. So if [other](ends-with#kotlin.io%24endsWith(java.io.File,%20kotlin.String)/other) has N components, last N components of `this` must be the same as in [other](ends-with#kotlin.io%24endsWith(java.io.File,%20kotlin.String)/other). For relative [other](ends-with#kotlin.io%24endsWith(java.io.File,%20kotlin.String)/other), `this` can belong to any root. ``` fun File.endsWith(other: String): Boolean ``` **Platform and version requirements:** JVM (1.0) #### <extension> Returns the extension of this file (not including the dot), or an empty string if it doesn't have one. ``` val File.extension: String ``` **Platform and version requirements:** JVM (1.0) #### [forEachBlock](for-each-block) Reads file by byte blocks and calls [action](for-each-block#kotlin.io%24forEachBlock(java.io.File,%20kotlin.Function2((kotlin.ByteArray,%20kotlin.Int,%20kotlin.Unit)))/action) for each block read. Block has default size which is implementation-dependent. This functions passes the byte array and amount of bytes in the array to the [action](for-each-block#kotlin.io%24forEachBlock(java.io.File,%20kotlin.Function2((kotlin.ByteArray,%20kotlin.Int,%20kotlin.Unit)))/action) function. ``` fun File.forEachBlock(     action: (buffer: ByteArray, bytesRead: Int) -> Unit) ``` Reads file by byte blocks and calls [action](for-each-block#kotlin.io%24forEachBlock(java.io.File,%20kotlin.Int,%20kotlin.Function2((kotlin.ByteArray,%20kotlin.Int,%20kotlin.Unit)))/action) for each block read. This functions passes the byte array and amount of bytes in the array to the [action](for-each-block#kotlin.io%24forEachBlock(java.io.File,%20kotlin.Int,%20kotlin.Function2((kotlin.ByteArray,%20kotlin.Int,%20kotlin.Unit)))/action) function. ``` fun File.forEachBlock(     blockSize: Int,     action: (buffer: ByteArray, bytesRead: Int) -> Unit) ``` **Platform and version requirements:** JVM (1.0) #### [forEachLine](for-each-line) Reads this file line by line using the specified [charset](for-each-line#kotlin.io%24forEachLine(java.io.File,%20java.nio.charset.Charset,%20kotlin.Function1((kotlin.String,%20kotlin.Unit)))/charset) and calls [action](for-each-line#kotlin.io%24forEachLine(java.io.File,%20java.nio.charset.Charset,%20kotlin.Function1((kotlin.String,%20kotlin.Unit)))/action) for each line. Default charset is UTF-8. ``` fun File.forEachLine(     charset: Charset = Charsets.UTF_8,     action: (line: String) -> Unit) ``` **Platform and version requirements:** JVM (1.0) #### [inputStream](input-stream) Constructs a new FileInputStream of this file and returns it as a result. ``` fun File.inputStream(): FileInputStream ``` **Platform and version requirements:** JVM (1.0) #### [invariantSeparatorsPath](invariant-separators-path) Returns [path](https://docs.oracle.com/javase/8/docs/api/java/io/File.html#path) of this File using the invariant separator '/' to separate the names in the name sequence. ``` val File.invariantSeparatorsPath: String ``` **Platform and version requirements:** JVM (1.0) #### [isRooted](is-rooted) Determines whether this file has a root or it represents a relative path. ``` val File.isRooted: Boolean ``` **Platform and version requirements:** JVM (1.0) #### [nameWithoutExtension](name-without-extension) Returns file's name without an extension. ``` val File.nameWithoutExtension: String ``` **Platform and version requirements:** JVM (1.0) #### <normalize> Removes all . and resolves all possible .. in this file name. For instance, `File("/foo/./bar/gav/../baaz").normalize()` is `File("/foo/bar/baaz")`. ``` fun File.normalize(): File ``` **Platform and version requirements:** JVM (1.0) #### [outputStream](output-stream) Constructs a new FileOutputStream of this file and returns it as a result. ``` fun File.outputStream(): FileOutputStream ``` **Platform and version requirements:** JVM (1.0) #### [printWriter](print-writer) Returns a new [PrintWriter](https://docs.oracle.com/javase/8/docs/api/java/io/PrintWriter.html) for writing the content of this file. ``` fun File.printWriter(     charset: Charset = Charsets.UTF_8 ): PrintWriter ``` **Platform and version requirements:** JVM (1.0) #### [readBytes](read-bytes) Gets the entire content of this file as a byte array. ``` fun File.readBytes(): ByteArray ``` **Platform and version requirements:** JVM (1.0) #### <reader> Returns a new [FileReader](https://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html) for reading the content of this file. ``` fun File.reader(     charset: Charset = Charsets.UTF_8 ): InputStreamReader ``` **Platform and version requirements:** JVM (1.0) #### [readLines](read-lines) Reads the file content as a list of lines. ``` fun File.readLines(     charset: Charset = Charsets.UTF_8 ): List<String> ``` **Platform and version requirements:** JVM (1.0) #### [readText](read-text) Gets the entire content of this file as a String using UTF-8 or specified [charset](read-text#kotlin.io%24readText(java.io.File,%20java.nio.charset.Charset)/charset). ``` fun File.readText(charset: Charset = Charsets.UTF_8): String ``` **Platform and version requirements:** JVM (1.0) #### [relativeTo](relative-to) Calculates the relative path for this file from [base](relative-to#kotlin.io%24relativeTo(java.io.File,%20java.io.File)/base) file. Note that the [base](relative-to#kotlin.io%24relativeTo(java.io.File,%20java.io.File)/base) file is treated as a directory. If this file matches the [base](relative-to#kotlin.io%24relativeTo(java.io.File,%20java.io.File)/base) file, then a [File](https://docs.oracle.com/javase/8/docs/api/java/io/File.html) with empty path will be returned. ``` fun File.relativeTo(base: File): File ``` **Platform and version requirements:** JVM (1.0) #### [relativeToOrNull](relative-to-or-null) Calculates the relative path for this file from [base](relative-to-or-null#kotlin.io%24relativeToOrNull(java.io.File,%20java.io.File)/base) file. Note that the [base](relative-to-or-null#kotlin.io%24relativeToOrNull(java.io.File,%20java.io.File)/base) file is treated as a directory. If this file matches the [base](relative-to-or-null#kotlin.io%24relativeToOrNull(java.io.File,%20java.io.File)/base) file, then a [File](https://docs.oracle.com/javase/8/docs/api/java/io/File.html) with empty path will be returned. ``` fun File.relativeToOrNull(base: File): File? ``` **Platform and version requirements:** JVM (1.0) #### [relativeToOrSelf](relative-to-or-self) Calculates the relative path for this file from [base](relative-to-or-self#kotlin.io%24relativeToOrSelf(java.io.File,%20java.io.File)/base) file. Note that the [base](relative-to-or-self#kotlin.io%24relativeToOrSelf(java.io.File,%20java.io.File)/base) file is treated as a directory. If this file matches the [base](relative-to-or-self#kotlin.io%24relativeToOrSelf(java.io.File,%20java.io.File)/base) file, then a [File](https://docs.oracle.com/javase/8/docs/api/java/io/File.html) with empty path will be returned. ``` fun File.relativeToOrSelf(base: File): File ``` **Platform and version requirements:** JVM (1.0) #### <resolve> Adds [relative](resolve#kotlin.io%24resolve(java.io.File,%20java.io.File)/relative) file to this, considering this as a directory. If [relative](resolve#kotlin.io%24resolve(java.io.File,%20java.io.File)/relative) has a root, [relative](resolve#kotlin.io%24resolve(java.io.File,%20java.io.File)/relative) is returned back. For instance, `File("/foo/bar").resolve(File("gav"))` is `File("/foo/bar/gav")`. This function is complementary with [relativeTo](relative-to), so `f.resolve(g.relativeTo(f)) == g` should be always `true` except for different roots case. ``` fun File.resolve(relative: File): File ``` Adds [relative](resolve#kotlin.io%24resolve(java.io.File,%20kotlin.String)/relative) name to this, considering this as a directory. If [relative](resolve#kotlin.io%24resolve(java.io.File,%20kotlin.String)/relative) has a root, [relative](resolve#kotlin.io%24resolve(java.io.File,%20kotlin.String)/relative) is returned back. For instance, `File("/foo/bar").resolve("gav")` is `File("/foo/bar/gav")`. ``` fun File.resolve(relative: String): File ``` **Platform and version requirements:** JVM (1.0) #### [resolveSibling](resolve-sibling) Adds [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20java.io.File)/relative) file to this parent directory. If [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20java.io.File)/relative) has a root or this has no parent directory, [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20java.io.File)/relative) is returned back. For instance, `File("/foo/bar").resolveSibling(File("gav"))` is `File("/foo/gav")`. ``` fun File.resolveSibling(relative: File): File ``` Adds [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20kotlin.String)/relative) name to this parent directory. If [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20kotlin.String)/relative) has a root or this has no parent directory, [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20kotlin.String)/relative) is returned back. For instance, `File("/foo/bar").resolveSibling("gav")` is `File("/foo/gav")`. ``` fun File.resolveSibling(relative: String): File ``` **Platform and version requirements:** JVM (1.0) #### [startsWith](starts-with) Determines whether this file belongs to the same root as [other](starts-with#kotlin.io%24startsWith(java.io.File,%20java.io.File)/other) and starts with all components of [other](starts-with#kotlin.io%24startsWith(java.io.File,%20java.io.File)/other) in the same order. So if [other](starts-with#kotlin.io%24startsWith(java.io.File,%20java.io.File)/other) has N components, first N components of `this` must be the same as in [other](starts-with#kotlin.io%24startsWith(java.io.File,%20java.io.File)/other). ``` fun File.startsWith(other: File): Boolean ``` ``` fun File.startsWith(other: String): Boolean ``` **Platform and version requirements:** JVM (1.0) #### [toRelativeString](to-relative-string) Calculates the relative path for this file from [base](to-relative-string#kotlin.io%24toRelativeString(java.io.File,%20java.io.File)/base) file. Note that the [base](to-relative-string#kotlin.io%24toRelativeString(java.io.File,%20java.io.File)/base) file is treated as a directory. If this file matches the [base](to-relative-string#kotlin.io%24toRelativeString(java.io.File,%20java.io.File)/base) file, then an empty string will be returned. ``` fun File.toRelativeString(base: File): String ``` **Platform and version requirements:** JVM (1.0) #### [useLines](use-lines) Calls the [block](use-lines#kotlin.io%24useLines(java.io.File,%20java.nio.charset.Charset,%20kotlin.Function1((kotlin.sequences.Sequence((kotlin.String)),%20kotlin.io.useLines.T)))/block) callback giving it a sequence of all the lines in this file and closes the reader once the processing is complete. ``` fun <T> File.useLines(     charset: Charset = Charsets.UTF_8,     block: (Sequence<String>) -> T ): T ``` **Platform and version requirements:** JVM (1.0) #### <walk> Gets a sequence for visiting this directory and all its content. ``` fun File.walk(     direction: FileWalkDirection = FileWalkDirection.TOP_DOWN ): FileTreeWalk ``` **Platform and version requirements:** JVM (1.0) #### [walkBottomUp](walk-bottom-up) Gets a sequence for visiting this directory and all its content in bottom-up order. Depth-first search is used and directories are visited after all their files. ``` fun File.walkBottomUp(): FileTreeWalk ``` **Platform and version requirements:** JVM (1.0) #### [walkTopDown](walk-top-down) Gets a sequence for visiting this directory and all its content in top-down order. Depth-first search is used and directories are visited before all their files. ``` fun File.walkTopDown(): FileTreeWalk ``` **Platform and version requirements:** JVM (1.0) #### [writeBytes](write-bytes) Sets the content of this file as an [array](write-bytes#kotlin.io%24writeBytes(java.io.File,%20kotlin.ByteArray)/array) of bytes. If this file already exists, it becomes overwritten. ``` fun File.writeBytes(array: ByteArray) ``` **Platform and version requirements:** JVM (1.0) #### <writer> Returns a new [FileWriter](https://docs.oracle.com/javase/8/docs/api/java/io/FileWriter.html) for writing the content of this file. ``` fun File.writer(     charset: Charset = Charsets.UTF_8 ): OutputStreamWriter ``` **Platform and version requirements:** JVM (1.0) #### [writeText](write-text) Sets the content of this file as [text](write-text#kotlin.io%24writeText(java.io.File,%20kotlin.String,%20java.nio.charset.Charset)/text) encoded using UTF-8 or specified [charset](write-text#kotlin.io%24writeText(java.io.File,%20kotlin.String,%20java.nio.charset.Charset)/charset). If this file exists, it becomes overwritten. ``` fun File.writeText(     text: String,     charset: Charset = Charsets.UTF_8) ```
programming_docs
kotlin writeText writeText ========= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [writeText](write-text) **Platform and version requirements:** JVM (1.0) ``` fun File.writeText(     text: String,     charset: Charset = Charsets.UTF_8) ``` Sets the content of this file as [text](write-text#kotlin.io%24writeText(java.io.File,%20kotlin.String,%20java.nio.charset.Charset)/text) encoded using UTF-8 or specified [charset](write-text#kotlin.io%24writeText(java.io.File,%20kotlin.String,%20java.nio.charset.Charset)/charset). If this file exists, it becomes overwritten. Parameters ---------- `text` - text to write into file. `charset` - character set to use. kotlin endsWith endsWith ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [endsWith](ends-with) **Platform and version requirements:** JVM (1.0) ``` fun File.endsWith(other: File): Boolean ``` Determines whether this file path ends with the path of [other](ends-with#kotlin.io%24endsWith(java.io.File,%20java.io.File)/other) file. If [other](ends-with#kotlin.io%24endsWith(java.io.File,%20java.io.File)/other) is rooted path it must be equal to this. If [other](ends-with#kotlin.io%24endsWith(java.io.File,%20java.io.File)/other) is relative path then last N components of `this` must be the same as all components in [other](ends-with#kotlin.io%24endsWith(java.io.File,%20java.io.File)/other), where N is the number of components in [other](ends-with#kotlin.io%24endsWith(java.io.File,%20java.io.File)/other). **Return** `true` if this path ends with [other](ends-with#kotlin.io%24endsWith(java.io.File,%20java.io.File)/other) path, `false` otherwise. **Platform and version requirements:** JVM (1.0) ``` fun File.endsWith(other: String): Boolean ``` Determines whether this file belongs to the same root as [other](ends-with#kotlin.io%24endsWith(java.io.File,%20kotlin.String)/other) and ends with all components of [other](ends-with#kotlin.io%24endsWith(java.io.File,%20kotlin.String)/other) in the same order. So if [other](ends-with#kotlin.io%24endsWith(java.io.File,%20kotlin.String)/other) has N components, last N components of `this` must be the same as in [other](ends-with#kotlin.io%24endsWith(java.io.File,%20kotlin.String)/other). For relative [other](ends-with#kotlin.io%24endsWith(java.io.File,%20kotlin.String)/other), `this` can belong to any root. **Return** `true` if this path ends with [other](ends-with#kotlin.io%24endsWith(java.io.File,%20kotlin.String)/other) path, `false` otherwise. kotlin copyRecursively copyRecursively =============== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [copyRecursively](copy-recursively) **Platform and version requirements:** JVM (1.0) ``` fun File.copyRecursively(     target: File,     overwrite: Boolean = false,     onError: (File, IOException) -> OnErrorAction = { _, exception -> throw exception } ): Boolean ``` Copies this file with all its children to the specified destination [target](copy-recursively#kotlin.io%24copyRecursively(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Function2((java.io.File,%20java.io.IOException,%20kotlin.io.OnErrorAction)))/target) path. If some directories on the way to the destination are missing, then they will be created. If this file path points to a single file, then it will be copied to a file with the path [target](copy-recursively#kotlin.io%24copyRecursively(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Function2((java.io.File,%20java.io.IOException,%20kotlin.io.OnErrorAction)))/target). If this file path points to a directory, then its children will be copied to a directory with the path [target](copy-recursively#kotlin.io%24copyRecursively(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Function2((java.io.File,%20java.io.IOException,%20kotlin.io.OnErrorAction)))/target). If the [target](copy-recursively#kotlin.io%24copyRecursively(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Function2((java.io.File,%20java.io.IOException,%20kotlin.io.OnErrorAction)))/target) already exists, it will be deleted before copying when the [overwrite](copy-recursively#kotlin.io%24copyRecursively(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Function2((java.io.File,%20java.io.IOException,%20kotlin.io.OnErrorAction)))/overwrite) parameter permits so. The operation doesn't preserve copied file attributes such as creation/modification date, permissions, etc. If any errors occur during the copying, then further actions will depend on the result of the call to `onError(File, IOException)` function, that will be called with arguments, specifying the file that caused the error and the exception itself. By default this function rethrows exceptions. Exceptions that can be passed to the `onError` function: * [NoSuchFileException](../-no-such-file-exception/index) - if there was an attempt to copy a non-existent file * [FileAlreadyExistsException](../-file-already-exists-exception/index) - if there is a conflict * [AccessDeniedException](../-access-denied-exception/index) - if there was an attempt to open a directory that didn't succeed. * [IOException](https://docs.oracle.com/javase/8/docs/api/java/io/IOException.html) - if some problems occur when copying. Note that if this function fails, then partial copying may have taken place. Parameters ---------- `overwrite` - `true` if it is allowed to overwrite existing destination files and directories. **Return** `false` if the copying was terminated, `true` otherwise. kotlin relativeTo relativeTo ========== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [relativeTo](relative-to) **Platform and version requirements:** JVM (1.0) ``` fun File.relativeTo(base: File): File ``` Calculates the relative path for this file from [base](relative-to#kotlin.io%24relativeTo(java.io.File,%20java.io.File)/base) file. Note that the [base](relative-to#kotlin.io%24relativeTo(java.io.File,%20java.io.File)/base) file is treated as a directory. If this file matches the [base](relative-to#kotlin.io%24relativeTo(java.io.File,%20java.io.File)/base) file, then a [File](https://docs.oracle.com/javase/8/docs/api/java/io/File.html) with empty path will be returned. Exceptions ---------- `IllegalArgumentException` - if this and base paths have different roots. **Return** File with relative path from [base](relative-to#kotlin.io%24relativeTo(java.io.File,%20java.io.File)/base) to this. kotlin writer writer ====== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / <writer> **Platform and version requirements:** JVM (1.0) ``` fun File.writer(     charset: Charset = Charsets.UTF_8 ): OutputStreamWriter ``` Returns a new [FileWriter](https://docs.oracle.com/javase/8/docs/api/java/io/FileWriter.html) for writing the content of this file. kotlin appendText appendText ========== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [appendText](append-text) **Platform and version requirements:** JVM (1.0) ``` fun File.appendText(     text: String,     charset: Charset = Charsets.UTF_8) ``` Appends [text](append-text#kotlin.io%24appendText(java.io.File,%20kotlin.String,%20java.nio.charset.Charset)/text) to the content of this file using UTF-8 or the specified [charset](append-text#kotlin.io%24appendText(java.io.File,%20kotlin.String,%20java.nio.charset.Charset)/charset). Parameters ---------- `text` - text to append to file. `charset` - character set to use. kotlin reader reader ====== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / <reader> **Platform and version requirements:** JVM (1.0) ``` fun File.reader(     charset: Charset = Charsets.UTF_8 ): InputStreamReader ``` Returns a new [FileReader](https://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html) for reading the content of this file. kotlin relativeToOrSelf relativeToOrSelf ================ [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [relativeToOrSelf](relative-to-or-self) **Platform and version requirements:** JVM (1.0) ``` fun File.relativeToOrSelf(base: File): File ``` Calculates the relative path for this file from [base](relative-to-or-self#kotlin.io%24relativeToOrSelf(java.io.File,%20java.io.File)/base) file. Note that the [base](relative-to-or-self#kotlin.io%24relativeToOrSelf(java.io.File,%20java.io.File)/base) file is treated as a directory. If this file matches the [base](relative-to-or-self#kotlin.io%24relativeToOrSelf(java.io.File,%20java.io.File)/base) file, then a [File](https://docs.oracle.com/javase/8/docs/api/java/io/File.html) with empty path will be returned. **Return** File with relative path from [base](relative-to-or-self#kotlin.io%24relativeToOrSelf(java.io.File,%20java.io.File)/base) to this, or `this` if this and base paths have different roots. kotlin nameWithoutExtension nameWithoutExtension ==================== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [nameWithoutExtension](name-without-extension) **Platform and version requirements:** JVM (1.0) ``` val File.nameWithoutExtension: String ``` Returns file's name without an extension. kotlin relativeToOrNull relativeToOrNull ================ [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [relativeToOrNull](relative-to-or-null) **Platform and version requirements:** JVM (1.0) ``` fun File.relativeToOrNull(base: File): File? ``` Calculates the relative path for this file from [base](relative-to-or-null#kotlin.io%24relativeToOrNull(java.io.File,%20java.io.File)/base) file. Note that the [base](relative-to-or-null#kotlin.io%24relativeToOrNull(java.io.File,%20java.io.File)/base) file is treated as a directory. If this file matches the [base](relative-to-or-null#kotlin.io%24relativeToOrNull(java.io.File,%20java.io.File)/base) file, then a [File](https://docs.oracle.com/javase/8/docs/api/java/io/File.html) with empty path will be returned. **Return** File with relative path from [base](relative-to-or-null#kotlin.io%24relativeToOrNull(java.io.File,%20java.io.File)/base) to this, or `null` if this and base paths have different roots. kotlin appendBytes appendBytes =========== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [appendBytes](append-bytes) **Platform and version requirements:** JVM (1.0) ``` fun File.appendBytes(array: ByteArray) ``` Appends an [array](append-bytes#kotlin.io%24appendBytes(java.io.File,%20kotlin.ByteArray)/array) of bytes to the content of this file. Parameters ---------- `array` - byte array to append to this file. kotlin writeBytes writeBytes ========== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [writeBytes](write-bytes) **Platform and version requirements:** JVM (1.0) ``` fun File.writeBytes(array: ByteArray) ``` Sets the content of this file as an [array](write-bytes#kotlin.io%24writeBytes(java.io.File,%20kotlin.ByteArray)/array) of bytes. If this file already exists, it becomes overwritten. Parameters ---------- `array` - byte array to write into this file. kotlin walkTopDown walkTopDown =========== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [walkTopDown](walk-top-down) **Platform and version requirements:** JVM (1.0) ``` fun File.walkTopDown(): FileTreeWalk ``` Gets a sequence for visiting this directory and all its content in top-down order. Depth-first search is used and directories are visited before all their files. kotlin walkBottomUp walkBottomUp ============ [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [walkBottomUp](walk-bottom-up) **Platform and version requirements:** JVM (1.0) ``` fun File.walkBottomUp(): FileTreeWalk ``` Gets a sequence for visiting this directory and all its content in bottom-up order. Depth-first search is used and directories are visited after all their files. kotlin resolveSibling resolveSibling ============== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [resolveSibling](resolve-sibling) **Platform and version requirements:** JVM (1.0) ``` fun File.resolveSibling(relative: File): File ``` Adds [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20java.io.File)/relative) file to this parent directory. If [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20java.io.File)/relative) has a root or this has no parent directory, [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20java.io.File)/relative) is returned back. For instance, `File("/foo/bar").resolveSibling(File("gav"))` is `File("/foo/gav")`. **Return** concatenated this.parent and [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20java.io.File)/relative) paths, or just [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20java.io.File)/relative) if it's absolute or this has no parent. **Platform and version requirements:** JVM (1.0) ``` fun File.resolveSibling(relative: String): File ``` Adds [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20kotlin.String)/relative) name to this parent directory. If [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20kotlin.String)/relative) has a root or this has no parent directory, [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20kotlin.String)/relative) is returned back. For instance, `File("/foo/bar").resolveSibling("gav")` is `File("/foo/gav")`. **Return** concatenated this.parent and [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20kotlin.String)/relative) paths, or just [relative](resolve-sibling#kotlin.io%24resolveSibling(java.io.File,%20kotlin.String)/relative) if it's absolute or this has no parent. kotlin outputStream outputStream ============ [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [outputStream](output-stream) **Platform and version requirements:** JVM (1.0) ``` fun File.outputStream(): FileOutputStream ``` Constructs a new FileOutputStream of this file and returns it as a result. kotlin startsWith startsWith ========== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [startsWith](starts-with) **Platform and version requirements:** JVM (1.0) ``` fun File.startsWith(other: File): Boolean ``` ``` fun File.startsWith(other: String): Boolean ``` Determines whether this file belongs to the same root as [other](starts-with#kotlin.io%24startsWith(java.io.File,%20java.io.File)/other) and starts with all components of [other](starts-with#kotlin.io%24startsWith(java.io.File,%20java.io.File)/other) in the same order. So if [other](starts-with#kotlin.io%24startsWith(java.io.File,%20java.io.File)/other) has N components, first N components of `this` must be the same as in [other](starts-with#kotlin.io%24startsWith(java.io.File,%20java.io.File)/other). **Return** `true` if this path starts with [other](starts-with#kotlin.io%24startsWith(java.io.File,%20java.io.File)/other) path, `false` otherwise. kotlin copyTo copyTo ====== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [copyTo](copy-to) **Platform and version requirements:** JVM (1.0) ``` fun File.copyTo(     target: File,     overwrite: Boolean = false,     bufferSize: Int = DEFAULT_BUFFER_SIZE ): File ``` Copies this file to the given [target](copy-to#kotlin.io%24copyTo(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Int)/target) file. If some directories on a way to the [target](copy-to#kotlin.io%24copyTo(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Int)/target) are missing, then they will be created. If the [target](copy-to#kotlin.io%24copyTo(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Int)/target) file already exists, this function will fail unless [overwrite](copy-to#kotlin.io%24copyTo(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Int)/overwrite) argument is set to `true`. When [overwrite](copy-to#kotlin.io%24copyTo(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Int)/overwrite) is `true` and [target](copy-to#kotlin.io%24copyTo(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Int)/target) is a directory, it is replaced only if it is empty. If this file is a directory, it is copied without its content, i.e. an empty [target](copy-to#kotlin.io%24copyTo(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Int)/target) directory is created. If you want to copy directory including its contents, use [copyRecursively](copy-recursively). The operation doesn't preserve copied file attributes such as creation/modification date, permissions, etc. Parameters ---------- `overwrite` - `true` if destination overwrite is allowed. `bufferSize` - the buffer size to use when copying. Exceptions ---------- `NoSuchFileException` - if the source file doesn't exist. `FileAlreadyExistsException` - if the destination file already exists and [overwrite](copy-to#kotlin.io%24copyTo(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Int)/overwrite) argument is set to `false`. `IOException` - if any errors occur while copying. **Return** the [target](copy-to#kotlin.io%24copyTo(java.io.File,%20java.io.File,%20kotlin.Boolean,%20kotlin.Int)/target) file. kotlin useLines useLines ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [useLines](use-lines) **Platform and version requirements:** JVM (1.0) ``` inline fun <T> File.useLines(     charset: Charset = Charsets.UTF_8,     block: (Sequence<String>) -> T ): T ``` Calls the [block](use-lines#kotlin.io%24useLines(java.io.File,%20java.nio.charset.Charset,%20kotlin.Function1((kotlin.sequences.Sequence((kotlin.String)),%20kotlin.io.useLines.T)))/block) callback giving it a sequence of all the lines in this file and closes the reader once the processing is complete. Parameters ---------- `charset` - character set to use. By default uses UTF-8 charset. **Return** the value returned by [block](use-lines#kotlin.io%24useLines(java.io.File,%20java.nio.charset.Charset,%20kotlin.Function1((kotlin.sequences.Sequence((kotlin.String)),%20kotlin.io.useLines.T)))/block). kotlin readText readText ======== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [readText](read-text) **Platform and version requirements:** JVM (1.0) ``` fun File.readText(charset: Charset = Charsets.UTF_8): String ``` Gets the entire content of this file as a String using UTF-8 or specified [charset](read-text#kotlin.io%24readText(java.io.File,%20java.nio.charset.Charset)/charset). This method is not recommended on huge files. It has an internal limitation of 2 GB file size. Parameters ---------- `charset` - character set to use. **Return** the entire content of this file as a String. kotlin readLines readLines ========= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [readLines](read-lines) **Platform and version requirements:** JVM (1.0) ``` fun File.readLines(     charset: Charset = Charsets.UTF_8 ): List<String> ``` Reads the file content as a list of lines. Do not use this function for huge files. Parameters ---------- `charset` - character set to use. By default uses UTF-8 charset. **Return** list of file lines.
programming_docs
kotlin readBytes readBytes ========= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [readBytes](read-bytes) **Platform and version requirements:** JVM (1.0) ``` fun File.readBytes(): ByteArray ``` Gets the entire content of this file as a byte array. This method is not recommended on huge files. It has an internal limitation of 2 GB byte array size. **Return** the entire content of this file as a byte array. kotlin toRelativeString toRelativeString ================ [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [toRelativeString](to-relative-string) **Platform and version requirements:** JVM (1.0) ``` fun File.toRelativeString(base: File): String ``` Calculates the relative path for this file from [base](to-relative-string#kotlin.io%24toRelativeString(java.io.File,%20java.io.File)/base) file. Note that the [base](to-relative-string#kotlin.io%24toRelativeString(java.io.File,%20java.io.File)/base) file is treated as a directory. If this file matches the [base](to-relative-string#kotlin.io%24toRelativeString(java.io.File,%20java.io.File)/base) file, then an empty string will be returned. Exceptions ---------- `IllegalArgumentException` - if this and base paths have different roots. **Return** relative path from [base](to-relative-string#kotlin.io%24toRelativeString(java.io.File,%20java.io.File)/base) to this. kotlin normalize normalize ========= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / <normalize> **Platform and version requirements:** JVM (1.0) ``` fun File.normalize(): File ``` Removes all . and resolves all possible .. in this file name. For instance, `File("/foo/./bar/gav/../baaz").normalize()` is `File("/foo/bar/baaz")`. **Return** normalized pathname with . and possibly .. removed. kotlin walk walk ==== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / <walk> **Platform and version requirements:** JVM (1.0) ``` fun File.walk(     direction: FileWalkDirection = FileWalkDirection.TOP_DOWN ): FileTreeWalk ``` Gets a sequence for visiting this directory and all its content. Parameters ---------- `direction` - walk direction, top-down (by default) or bottom-up. kotlin inputStream inputStream =========== [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [inputStream](input-stream) **Platform and version requirements:** JVM (1.0) ``` fun File.inputStream(): FileInputStream ``` Constructs a new FileInputStream of this file and returns it as a result. kotlin invariantSeparatorsPath invariantSeparatorsPath ======================= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / [invariantSeparatorsPath](invariant-separators-path) **Platform and version requirements:** JVM (1.0) ``` val File.invariantSeparatorsPath: String ``` Returns [path](https://docs.oracle.com/javase/8/docs/api/java/io/File.html#path) of this File using the invariant separator '/' to separate the names in the name sequence. kotlin resolve resolve ======= [kotlin-stdlib](../../../../../../index) / [kotlin.io](../index) / [java.io.File](index) / <resolve> **Platform and version requirements:** JVM (1.0) ``` fun File.resolve(relative: File): File ``` Adds [relative](resolve#kotlin.io%24resolve(java.io.File,%20java.io.File)/relative) file to this, considering this as a directory. If [relative](resolve#kotlin.io%24resolve(java.io.File,%20java.io.File)/relative) has a root, [relative](resolve#kotlin.io%24resolve(java.io.File,%20java.io.File)/relative) is returned back. For instance, `File("/foo/bar").resolve(File("gav"))` is `File("/foo/bar/gav")`. This function is complementary with [relativeTo](relative-to), so `f.resolve(g.relativeTo(f)) == g` should be always `true` except for different roots case. **Return** concatenated this and [relative](resolve#kotlin.io%24resolve(java.io.File,%20java.io.File)/relative) paths, or just [relative](resolve#kotlin.io%24resolve(java.io.File,%20java.io.File)/relative) if it's absolute. **Platform and version requirements:** JVM (1.0) ``` fun File.resolve(relative: String): File ``` Adds [relative](resolve#kotlin.io%24resolve(java.io.File,%20kotlin.String)/relative) name to this, considering this as a directory. If [relative](resolve#kotlin.io%24resolve(java.io.File,%20kotlin.String)/relative) has a root, [relative](resolve#kotlin.io%24resolve(java.io.File,%20kotlin.String)/relative) is returned back. For instance, `File("/foo/bar").resolve("gav")` is `File("/foo/bar/gav")`. **Return** concatenated this and [relative](resolve#kotlin.io%24resolve(java.io.File,%20kotlin.String)/relative) paths, or just [relative](resolve#kotlin.io%24resolve(java.io.File,%20kotlin.String)/relative) if it's absolute. http Proxy servers and tunneling Proxy servers and tunneling =========================== Proxy servers and tunneling =========================== When navigating through different networks of the Internet, proxy servers and HTTP tunnels are facilitating access to content on the World Wide Web. A proxy can be on the user's local computer, or anywhere between the user's computer and a destination server on the Internet. This page outlines some basics about proxies and introduces a few configuration options. There are two types of proxies: **forward proxies** (or tunnel, or gateway) and **reverse proxies** (used to control and protect access to a server for load-balancing, authentication, decryption or caching). Forward proxies --------------- A forward proxy, or gateway, or just "proxy" provides proxy services to a client or a group of clients. There are likely hundreds of thousands of open forward proxies on the Internet. They store and forward Internet services (like the DNS, or web pages) to reduce and control the bandwidth used by the group. Forward proxies can also be anonymous proxies and allow users to hide their IP address while browsing the Web or using other Internet services. [TOR](https://www.torproject.org/) (The Onion Router), routes internet traffic through multiple proxies for anonymity. Reverse proxies --------------- As the name implies, a reverse proxy does the opposite of what a forward proxy does: A forward proxy acts on behalf of clients (or requesting hosts). Forward proxies can hide the identities of clients whereas reverse proxies can hide the identities of servers. Reverse proxies have several use cases, a few are: * Load balancing: distribute the load to several web servers, * Cache static content: offload the web servers by caching static content like pictures, * Compression: compress and optimize content to speed up load time. Forwarding client information through proxies --------------------------------------------- Proxies can make requests appear as if they originated from the proxy's IP address. This can be useful if a proxy is used to provide client anonymity, but in other cases information from the original request is lost. The IP address of the original client is often used for debugging, statistics, or generating location-dependent content. A common way to disclose this information is by using the following HTTP headers: The standardized header: [`Forwarded`](headers/forwarded) Contains information from the client-facing side of proxy servers that is altered or lost when a proxy is involved in the path of the request. Or the de-facto standard versions: [`X-Forwarded-For`](headers/x-forwarded-for) Non-standard Identifies the originating IP addresses of a client connecting to a web server through an HTTP proxy or a load balancer. [`X-Forwarded-Host`](headers/x-forwarded-host) Non-standard Identifies the original host requested that a client used to connect to your proxy or load balancer. [`X-Forwarded-Proto`](headers/x-forwarded-proto) Non-standard identifies the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer. To provide information about the proxy itself (not about the client connecting to it), the `Via` header can be used. [`Via`](headers/via) Added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers. HTTP tunneling -------------- Tunneling transmits private network data and protocol information through public network by encapsulating the data. HTTP tunneling is using a protocol of higher level (HTTP) to transport a lower level protocol (TCP). The HTTP protocol specifies a request method called [`CONNECT`](methods/connect). It starts two-way communications with the requested resource and can be used to open a tunnel. This is how a client behind an HTTP proxy can access websites using SSL (i.e. HTTPS, port 443). Note, however, that not all proxy servers support the `CONNECT` method or limit it to port 443 only. See also the [HTTP tunnel article on Wikipedia](https://en.wikipedia.org/wiki/HTTP_tunnel). Proxy Auto-Configuration (PAC) ------------------------------ A [Proxy Auto-Configuration (PAC)](proxy_servers_and_tunneling/proxy_auto-configuration_pac_file) file is a [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) function that determines whether web browser requests (HTTP, HTTPS, and FTP) go directly to the destination or are forwarded to a web proxy server. The JavaScript function contained in the PAC file defines the function: The auto-config file should be saved to a file with a `.pac` filename extension: `proxy.pac`. And the MIME type set to `application/x-ns-proxy-autoconfig`. The file consists of a function called `FindProxyForURL`. The example below will work in an environment where the internal DNS server is set up so that it can only resolve internal host names, and the goal is to use a proxy only for hosts that aren't resolvable: ``` function FindProxyForURL(url, host) { if (isResolvable(host)) { return "DIRECT"; } return "PROXY proxy.mydomain.com:8080"; } ``` See [Proxy Auto-Configuration (PAC)](proxy_servers_and_tunneling/proxy_auto-configuration_pac_file) for more examples. See also -------- * [`CONNECT`](methods/connect) * [Proxy server on Wikipedia](https://en.wikipedia.org/wiki/Proxy_server) http Protocol upgrade mechanism Protocol upgrade mechanism ========================== Protocol upgrade mechanism ========================== The [HTTP/1.1 protocol](index) provides a special mechanism that can be used to upgrade an already established connection to a different protocol, using the [`Upgrade`](headers/upgrade) header field. This mechanism is optional; it cannot be used to insist on a protocol change. Implementations can choose not to take advantage of an upgrade even if they support the new protocol, and in practice, this mechanism is used mostly to bootstrap a WebSockets connection. Note also that HTTP/2 explicitly disallows the use of this mechanism; it is specific to HTTP/1.1. Upgrading HTTP/1.1 Connections ------------------------------ The [`Upgrade`](headers/upgrade) header field is used by clients to invite the server to switch to one of the listed protocols, in descending preference order. Because `Upgrade` is a hop-by-hop header, it also needs to be listed in the [`Connection`](headers/connection) header field. This means that a typical request that includes Upgrade would look something like: ``` GET /index.html HTTP/1.1 Host: www.example.com Connection: upgrade Upgrade: example/1, foo/2 ``` Other headers may be required depending on the requested protocol; for example, [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) upgrades allow additional headers to configure details about the WebSocket connection as well as to offer a degree of security in opening the connection. See [Upgrading to a WebSocket connection](#upgrading_to_a_websocket_connection) for more details. If the server decides to upgrade the connection, it sends back a [`101 Switching Protocols`](status/101) response status with an Upgrade header that specifies the protocol(s) being switched to. If it does not (or cannot) upgrade the connection, it ignores the `Upgrade` header and sends back a regular response (for example, a [`200 OK`](status/200)). Right after sending the `101` status code, the server can begin speaking the new protocol, performing any additional protocol-specific handshakes as necessary. Effectively, the connection becomes a two-way pipe as soon as the upgraded response is complete, and the request that initiated the upgrade can be completed over the new protocol. Common uses for this mechanism ------------------------------ Here we look at the most common use cases for the [`Upgrade`](headers/upgrade) header. ### Upgrading to a WebSocket connection By far, the most common use case for upgrading an HTTP connection is to use WebSockets, which are always implemented by upgrading an HTTP or HTTPS connection. Keep in mind that if you're opening a new connection using the [WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket), or any library that does WebSockets, most or all of this is done for you. For example, opening a WebSocket connection is as simple as: ``` webSocket = new WebSocket("ws://destination.server.ext", "optionalProtocol"); ``` The [`WebSocket()`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket) constructor does all the work of creating an initial HTTP/1.1 connection then handling the handshaking and upgrade process for you. **Note:** You can also use the `"wss://"` URL scheme to open a secure WebSocket connection. If you need to create a WebSocket connection from scratch, you'll have to handle the handshaking process yourself. After creating the initial HTTP/1.1 session, you need to request the upgrade by adding to a standard request the [`Upgrade`](headers/upgrade) and [`Connection`](headers/connection) headers, as follows: ``` Connection: Upgrade Upgrade: websocket ``` ### WebSocket-specific headers The following headers are involved in the WebSocket upgrade process. Other than the [`Upgrade`](headers/upgrade) and [`Connection`](headers/connection) headers, the rest are generally optional or handled for you by the browser and server when they're talking to each other. #### [`Sec-WebSocket-Extensions`](headers/sec-websocket-extensions) Specifies one or more protocol-level WebSocket extensions to ask the server to use. Using more than one `Sec-WebSocket-Extension` header in a request is permitted; the result is the same as if you included all of the listed extensions in one such header. ``` Sec-WebSocket-Extensions: extensions ``` `extensions` A comma-separated list of extensions to request (or agree to support). These should be selected from the [IANA WebSocket Extension Name Registry](https://www.iana.org/assignments/websocket/websocket.xml#extension-name). Extensions which take parameters do so by using semicolon delineation. For example: ``` Sec-WebSocket-Extensions: superspeed, colormode; depth=16 ``` #### [`Sec-WebSocket-Key`](headers/sec-websocket-key) Provides information to the server which is needed in order to confirm that the client is entitled to request an upgrade to WebSocket. This header can be used when insecure (HTTP) clients wish to upgrade, in order to offer some degree of protection against abuse. The value of the key is computed using an algorithm defined in the WebSocket specification, so this *does not provide security*. Instead, it helps to prevent non-WebSocket clients from inadvertently, or through misuse, requesting a WebSocket connection. In essence, then, this key confirms that "Yes, I really mean to open a WebSocket connection." This header is automatically added by clients that choose to use it; it cannot be added using the [`XMLHttpRequest.setRequestHeader()`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader) method. ``` Sec-WebSocket-Key: key ``` `key` The key for this request to upgrade. The client adds this if it wishes to do so, and the server will include in the response a key of its own, which the client will validate before delivering the upgrade response to you. The server's response's [`Sec-WebSocket-Accept`](headers/sec-websocket-accept) header will have a value computed based upon the specified `key`. #### [`Sec-WebSocket-Protocol`](headers/sec-websocket-protocol) The `Sec-WebSocket-Protocol` header specifies one or more WebSocket protocols that you wish to use, in order of preference. The first one that is supported by the server will be selected and returned by the server in a `Sec-WebSocket-Protocol` header included in the response. You can use this more than once in the header, as well; the result is the same as if you used a comma-delineated list of subprotocol identifiers in a single header. ``` Sec-WebSocket-Protocol: subprotocols ``` `subprotocols` A comma-separated list of subprotocol names, in the order of preference. The subprotocols may be selected from the [IANA WebSocket Subprotocol Name Registry](https://www.iana.org/assignments/websocket/websocket.xml#subprotocol-name) or may be a custom name jointly understood by the client and the server. #### [`Sec-WebSocket-Version`](headers/sec-websocket-version) ##### Request header Specifies the WebSocket protocol version the client wishes to use, so the server can confirm whether or not that version is supported on its end. ``` Sec-WebSocket-Version: version ``` `version` The WebSocket protocol version the client wishes to use when communicating with the server. This number should be the most recent version possible listed in the [IANA WebSocket Version Number Registry](https://www.iana.org/assignments/websocket/websocket.xml#version-number). The most recent final version of the WebSocket protocol is version 13. ##### Response header If the server can't communicate using the specified version of the WebSocket protocol, it will respond with an error (such as 426 Upgrade Required) that includes in its headers a `Sec-WebSocket-Version` header with a comma-separated list of the supported protocol versions. If the server does support the requested protocol version, no `Sec-WebSocket-Version` header is included in the response. ``` Sec-WebSocket-Version: supportedVersions ``` `supportedVersions` A comma-delineated list of the WebSocket protocol versions supported by the server. ### Response-only headers The response from the server may include these. #### [`Sec-WebSocket-Accept`](headers/sec-websocket-accept) Included in the response message from the server during the opening handshake process when the server is willing to initiate a WebSocket connection. It will appear no more than once in the response headers. ``` Sec-WebSocket-Accept: hash ``` `hash` If a [`Sec-WebSocket-Key`](headers/sec-websocket-key) header was provided, the value of this header is computed by taking the value of the key, concatenating the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" to it, taking the [SHA-1](https://en.wikipedia.org/wiki/SHA-1) hash of that concatenated string, resulting in a 20-byte value. That value is then [base64](https://developer.mozilla.org/en-US/docs/Glossary/Base64) encoded to obtain the value of this property. References ---------- * [WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) * [HTTP](index) * Specifications and RFCs: + [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230) + [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455) + [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) http Caching Caching ======= HTTP caching ============ Overview -------- The HTTP cache stores a response associated with a request and reuses the stored response for subsequent requests. There are several advantages to reusability. First, since there is no need to deliver the request to the origin server, then the closer the client and cache are, the faster the response will be. The most typical example is when the browser itself stores a cache for browser requests. Also, when a response is reusable, the origin server does not need to process the request — so it does not need to parse and route the request, restore the session based on the cookie, query the DB for results, or render the template engine. That reduces the load on the server. Proper operation of the cache is critical to the health of the system. Types of caches --------------- In the [HTTP Caching](https://httpwg.org/specs/rfc9111.html) spec, there are two main types of caches: **private caches** and **shared caches**. ### Private caches A private cache is a cache tied to a specific client — typically a browser cache. Since the stored response is not shared with other clients, a private cache can store a personalized response for that user. On the other hand, if personalized contents are stored in a cache other than a private cache, then other users may be able to retrieve those contents — which may cause unintentional information leakage. If a response contains personalized content and you want to store the response only in the private cache, you must specify a `private` directive. ``` Cache-Control: private ``` Personalized contents are usually controlled by cookies, but the presence of a cookie does not always indicate that it is private, and thus a cookie alone does not make the response private. Note that if the response has an `Authorization` header, it cannot be stored in the private cache (or a shared cache, unless `public` is specified). ### Shared cache The shared cache is located between the client and the server and can store responses that can be shared among users. And shared caches can be further sub-classified into **proxy caches** and **managed caches**. #### Proxy caches In addition to the function of access control, some proxies implement caching to reduce traffic out of the network. This is usually not managed by the service developer, so it must be controlled by appropriate HTTP headers and so on. However, in the past, outdated proxy-cache implementations — such as implementations that do not properly understand the HTTP Caching standard — have often caused problems for developers. **Kitchen-sink headers** like the following are used to try to work around "old and not updated proxy cache" implementations that do not understand current HTTP Caching spec directives like `no-store`. ``` Cache-Control: no-store, no-cache, max-age=0, must-revalidate, proxy-revalidate ``` However, in recent years, as HTTPS has become more common and client/server communication has become encrypted, proxy caches in the path can only tunnel a response and can't behave as a cache, in many cases. So in that scenario, there is no need to worry about outdated proxy cache implementations that cannot even see the response. On the other hand, if a [TLS](https://developer.mozilla.org/en-US/docs/Glossary/TLS) bridge proxy decrypts all communications in a person-in-the-middle manner by installing a certificate from a [CA (certificate authority)](https://developer.mozilla.org/en-US/docs/Glossary/Certificate_authority) managed by the organization on the PC, and performs access control, etc. — it is possible to see the contents of the response and cache it. However, since [CT (certificate transparency)](https://developer.mozilla.org/en-US/docs/Web/Security/Certificate_Transparency) has become widespread in recent years, and some browsers only allow certificates issued with an SCT (signed certificate timestamp), this method requires the application of an enterprise policy. In such a controlled environment, there is no need to worry about the proxy cache being "out of date and not updated". #### Managed caches Managed caches are explicitly deployed by service developers to offload the origin server and to deliver content efficiently. Examples include reverse proxies, CDNs, and service workers in combination with the Cache API. The characteristics of managed caches vary depending on the product deployed. In most cases, you can control the cache's behavior through the `Cache-Control` header and your own configuration files or dashboards. For example, the HTTP Caching specification essentially does not define a way to explicitly delete a cache — but with a managed cache, the stored response can be deleted at any time through dashboard operations, API calls, restarts, and so on. That allows for a more proactive caching strategy. It is also possible to ignore the standard HTTP Caching spec protocols in favor of explicit manipulation. For example, the following can be specified to opt-out of a private cache or proxy cache, while using your own strategy to cache only in a managed cache. ``` Cache-Control: no-store ``` For example, Varnish Cache uses VCL (Varnish Configuration Language, a type of [DSL](https://developer.mozilla.org/en-US/docs/Glossary/DSL/Domain_specific_language)) logic to handle cache storage, while service workers in combination with the Cache API allow you to create that logic in JavaScript. That means if a managed cache intentionally ignores a `no-store` directive, there is no need to perceive it as being "non-compliant" with the standard. What you should do is, avoid using kitchen-sink headers, but carefully read the documentation of whatever managed-cache mechanism you're using, and ensure you're controlling the cache properly in the ways provided by the mechanism you've chosen to use. Note that some CDNs provide their own headers that are effective only for that CDN (for example, `Surrogate-Control`). Currently, work is underway to define a [`CDN-Cache-Control`](https://httpwg.org/specs/rfc9213.html) header to standardize those. Heuristic caching ----------------- HTTP is designed to cache as much as possible, so even if no `Cache-Control` is given, responses will get stored and reused if certain conditions are met. This is called **heuristic caching**. For example, take the following response. This response was last updated 1 year ago. ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1024 Date: Tue, 22 Feb 2022 22:22:22 GMT Last-Modified: Tue, 22 Feb 2021 22:22:22 GMT <!doctype html> … ``` It is heuristically known that content which has not been updated for a full year will not be updated for some time after that. Therefore, the client stores this response (despite the lack of `max-age`) and reuses it for a while. How long to reuse is up to the implementation, but the specification recommends about 10% (in this case 0.1 year) of the time after storing. Heuristic caching is a workaround that came before `Cache-Control` support became widely adopted, and basically all responses should explicitly specify a `Cache-Control` header. Fresh and stale based on age ---------------------------- Stored HTTP responses have two states: **fresh** and **stale**. The *fresh* state usually indicates that the response is still valid and can be reused, while the *stale* state means that the cached response has already expired. The criterion for determining when a response is fresh and when it is stale is **age**. In HTTP, age is the time elapsed since the response was generated. This is similar to the [TTL](https://developer.mozilla.org/en-US/docs/Glossary/TTL) in other caching mechanisms. Take the following example response (604800 seconds is one week): ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1024 Date: Tue, 22 Feb 2022 22:22:22 GMT Cache-Control: max-age=604800 <!doctype html> … ``` The cache that stored the example response calculates the time elapsed since the response was generated and uses the result as the response's *age*. For the example response, the meaning of `max-age` is the following: * If the age of the response is *less* than one week, the response is *fresh*. * If the age of the response is *more* than one week, the response is *stale*. As long as the stored response remains fresh, it will be used to fulfill client requests. When a response is stored in a shared cache, it is necessary to inform the client of the response's age. Continuing with the example, if the shared cache stored the response for one day, the shared cache would send the following response to subsequent client requests. ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1024 Date: Tue, 22 Feb 2022 22:22:22 GMT Cache-Control: max-age=604800 Age: 86400 <!doctype html> … ``` The client which receives that response will find it to be fresh for the remaining 518400 seconds, the difference between the response's `max-age` and `Age`. Expires or max-age ------------------ In HTTP/1.0, freshness used to be specified by the `Expires` header. The `Expires` header specifies the lifetime of the cache using an explicit time rather than by specifying an elapsed time. ``` Expires: Tue, 28 Feb 2022 22:22:22 GMT ``` However, the time format is difficult to parse, many implementation bugs were found, and it is possible to induce problems by intentionally shifting the system clock; therefore, `max-age` — for specifying an elapsed time — was adopted for `Cache-Control` in HTTP/1.1. If both `Expires` and `Cache-Control: max-age` are available, `max-age` is defined to be preferred. So it is not necessary to provide `Expires` now that HTTP/1.1 is widely used. Vary ---- The way that responses are distinguished from one another is essentially based on their URLs: But the contents of responses are not always the same, even if they have the same URL. Especially when content negotiation is performed, the response from the server can depend on the values of the `Accept`, `Accept-Language`, and `Accept-Encoding` request headers. For example, for English content returned with an `Accept-Language: en` header and cached, it is undesirable to then reuse that cached response for requests that have an `Accept-Language: ja` request header. In this case, you can cause the responses to be cached separately — based on language — by adding "`Accept-Language`" to the value of the `Vary` header. ``` Vary: Accept-Language ``` That causes the cache to be keyed based on a composite of the response URL and the `Accept-Language` request header — rather than being based just on the response URL. Also, if you are providing content optimization (for example, for responsive design) based on the user agent, you may be tempted to include "`User-Agent`" in the value of the `Vary` header. However, the `User-Agent` request header generally has a very large number of variations, which drastically reduces the chance that the cache will be reused. So if possible, instead consider a way to vary behavior based on feature detection rather than based on the `User-Agent` request header. For applications that employ cookies to prevent others from reusing cached personalized content, you should specify `Cache-Control: private` instead of specifying a cookie for `Vary`. Validation ---------- Stale responses are not immediately discarded. HTTP has a mechanism to transform a stale response into a fresh one by asking the origin server. This is called **validation**, or sometimes, **revalidation**. Validation is done by using a **conditional request** that includes an `If-Modified-Since` or `If-None-Match` request header. ### If-Modified-Since The following response was generated at 22:22:22 and has a `max-age` of 1 hour, so you know that it is fresh until 23:22:22. ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1024 Date: Tue, 22 Feb 2022 22:22:22 GMT Last-Modified: Tue, 22 Feb 2022 22:00:00 GMT Cache-Control: max-age=3600 <!doctype html> … ``` At 23:22:22, the response becomes stale and the cache cannot be reused. So the request below shows a client sending a request with an `If-Modified-Since` request header, to ask the server if there have been any changes made since the specified time. ``` GET /index.html HTTP/1.1 Host: example.com Accept: text/html If-Modified-Since: Tue, 22 Feb 2022 22:00:00 GMT ``` The server will respond with `304 Not Modified` if the content has not changed since the specified time. Since this response only indicates "no change", there is no response body — there's just a status code — so the transfer size is extremely small. ``` HTTP/1.1 304 Not Modified Content-Type: text/html Date: Tue, 22 Feb 2022 23:22:22 GMT Last-Modified: Tue, 22 Feb 2022 22:00:00 GMT Cache-Control: max-age=3600 ``` Upon receiving that response, the client reverts the stored stale response back to being fresh and can reuse it during the remaining 1 hour. The server can obtain the modification time from the operating-system file system, which is relatively easy to do for the case of serving static files. However, there are some problems; for example, the time format is complex and difficult to parse, and distributed servers have difficulty synchronizing file-update times. To solve such problems, the `ETag` response header was standardized as an alternative. ### ETag/If-None-Match The value of the `ETag` response header is an arbitrary value generated by the server. There are no restrictions on how the server must generate the value, so servers are free to set the value based on whatever means they choose — such as a hash of the body contents or a version number. As an example, if a hash value is used for the `ETag` header and the hash value of the `index.html` resource is `33a64df5`, the response will be as follows: ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1024 Date: Tue, 22 Feb 2022 22:22:22 GMT ETag: "33a64df5" Cache-Control: max-age=3600 <!doctype html> … ``` If that response is stale, the client takes the value of the `ETag` response header for the cached response, and puts it into the `If-None-Match` request header, to ask the server if the resource has been modified: ``` GET /index.html HTTP/1.1 Host: example.com Accept: text/html If-None-Match: "33a64df5" ``` The server will return `304 Not Modified` if the value of the `ETag` header it determines for the requested resource is the same as the `If-None-Match` value in the request. But if the server determines the requested resource should now have a different `ETag` value, the server will instead respond with a `200 OK` and the latest version of the resource. **Note:** When evaluating how to use `ETag` and `Last-Modified`, consider the following: During cache revalidation, if both `ETag` and `Last-Modified` are present, `ETag` takes precedence. Therefore, if you are only considering caching, you may think that `Last-Modified` is unnecessary. However, `Last-Modified` is not just useful for caching; instead, it is a standard HTTP header that is also used by content-management (CMS) systems to display the last-modified time, by crawlers to adjust crawl frequency, and for other various purposes. So considering the overall HTTP ecosystem, it is preferable to provide both `ETag` and `Last-Modified`. ### Force Revalidation If you do not want a response to be reused, but instead want to always fetch the latest content from the server, you can use the `no-cache` directive to force validation. By adding `Cache-Control: no-cache` to the response along with `Last-Modified` and `ETag` — as shown below — the client will receive a `200 OK` response if the requested resource has been updated, or will otherwise receive a `304 Not Modified` response if the requested resource has not been updated. ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1024 Date: Tue, 22 Feb 2022 22:22:22 GMT Last-Modified: Tue, 22 Feb 2022 22:00:00 GMT ETag: deadbeef Cache-Control: no-cache <!doctype html> … ``` It is often stated that the combination of `max-age=0` and `must-revalidate` has the same meaning as `no-cache`. ``` Cache-Control: max-age=0, must-revalidate ``` `max-age=0` means that the response is immediately stale, and `must-revalidate` means that it must not be reused without revalidation once it is stale — so, in combination, the semantics seem to be the same as `no-cache`. However, that usage of `max-age=0` is a remnant of the fact that many implementations prior to HTTP/1.1 were unable to handle the `no-cache` directive — and so to deal with that limitation, `max-age=0` was used as a workaround. But now that HTTP/1.1-conformant servers are widely deployed, there's no reason to ever use that `max-age=0` and `must-revalidate` combination — you should instead just use `no-cache`. Don't cache ----------- The `no-cache` directive does not prevent the storing of responses but instead prevents the reuse of responses without revalidation. If you don't want a response stored in any cache, use `no-store`. ``` Cache-Control: no-store ``` However, in general, a "do not cache" requirement in practice amounts to the following set of circumstances: * Don't want the response stored by anyone other than the specific client, for privacy reasons. * Want to provide up-to-date information always. * Don't know what could happen in outdated implementations. Under that set of circumstances, `no-store` is not always the most-appropriate directive. The following sections look at the circumstances in more detail. ### Do not share with others It would be problematic if a response with personalized content is unexpectedly visible to other users of a cache. In such a case, using the `private` directive will cause the personalized response to only be stored with the specific client and not be leaked to any other user of the cache. ``` Cache-Control: private ``` In such a case, even if `no-store` is given, `private` must also be given. ### Provide up-to-date content every time The `no-store` directive prevents a response from being stored, but does not delete any already-stored response for the same URL. In other words, if there is an old response already stored for a particular URL, returning `no-store` will not prevent the old response from being reused. However, a `no-cache` directive will force the client to send a validation request before reusing any stored response. ``` Cache-Control: no-cache ``` If the server does not support conditional requests, you can force the client to access the server every time and always get the latest response with `200 OK`. ### Dealing with outdated implementations As a workaround for outdated implementations that ignore `no-store`, you may see kitchen-sink headers such as the following being used. ``` Cache-Control: no-store, no-cache, max-age=0, must-revalidate, proxy-revalidate ``` It is [recommended](https://docs.microsoft.com/troubleshoot/developer/browsers/connectivity-navigation/how-to-prevent-caching) to use `no-cache` as an alternative for dealing with such outdated implementations, and it is not a problem if `no-cache` is given from the beginning, since the server will always receive the request. If it is the shared cache that you are concerned about, you can make sure to prevent unintended caching by also adding `private`: ``` Cache-Control: no-cache, private ``` ### What's lost by `no-store` You may think adding `no-store` would be the right way to opt-out of caching. However, it's not recommended to grant `no-store` liberally, because you lose many advantages that HTTP and browsers have, including the browser's back/forward cache. Therefore, to get the advantages of the full feature set of the web platform, prefer the use of `no-cache` in combination with `private`. Reload and force reload ----------------------- Validation can be performed for requests as well as responses. The **reload** and **force reload** actions are common examples of validation performed from the browser side. ### Reload For recovering from window corruption or updating to the latest version of the resource, browsers provide a reload function for users. A simplified view of the HTTP request sent during a browser reload looks as follows: ``` GET / HTTP/1.1 Host: example.com Cache-Control: max-age=0 If-None-Match: "deadbeef" If-Modified-Since: Tue, 22 Feb 2022 20:20:20 GMT ``` (The requests from Chrome, Edge, and Firefox look very much like the above; the requests from Safari will look a bit different.) The `max-age=0` directive in the request specifies "reuse of responses with an age of 0 or less" — so, in effect, intermediately stored responses are not reused. As a result, a request is validated by `If-None-Match` and `If-Modified-Since`. That behavior is also defined in the [Fetch](https://fetch.spec.whatwg.org/#http-network-or-cache-fetch) standard and can be reproduced in JavaScript by calling `fetch()` with the cache mode set to `no-cache` (note that `reload` is not the right mode for this case): ``` // Note: "reload" is not the right mode for a normal reload; "no-cache" is fetch("/", { cache: "no-cache" }); ``` ### Force reload Browsers use `max-age=0` during reloads for backward-compatibility reasons — because many outdated implementations prior to HTTP/1.1 did not understand `no-cache`. But `no-cache` is fine now in this use case, and **force reload** is an additional way to bypass cached responses. The HTTP Request during a browser **force reload** looks as follows: ``` GET / HTTP/1.1 Host: example.com Pragma: no-cache Cache-Control: no-cache ``` (The requests from Chrome, Edge, and Firefox look very much like the above; the requests from Safari will look a bit different.) Since that's not a conditional request with `no-cache`, you can be sure you'll get a `200 OK` from the origin server. That behavior is also defined in the [Fetch](https://fetch.spec.whatwg.org/#http-network-or-cache-fetch) standard and can be reproduced in JavaScript by calling `fetch()` with the cache mode set to `reload` (note that it's not `force-reload`): ``` // Note: "reload" — rather than "no-cache" — is the right mode for a "force reload" fetch("/", { cache: "reload" }); ``` ### Avoiding revalidation Content that never changes should be given a long `max-age` by using cache busting — that is, by including a version number, hash value, etc., in the request URL. However, when the user reloads, a revalidation request is sent even though the server knows that the content is immutable. To prevent that, the `immutable` directive can be used to explicitly indicate that revalidation is not required because the content never changes. ``` Cache-Control: max-age=31536000, immutable ``` That prevents unnecessary revalidation during reloads. Note that, instead of implementing that directive, [Chrome has changed its implementation](https://blog.chromium.org/2017/01/reload-reloaded-faster-and-leaner-page_26.html) so that revalidation is not performed during reloads for subresources. Deleting stored responses ------------------------- There is basically no way to delete responses that have already been stored with a long `max-age`. Imagine that the following response from `https://example.com/` was stored. ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1024 Cache-Control: max-age=31536000 <!doctype html> … ``` You may want to overwrite that response once it expired on the server, but there is nothing the server can do once the response is stored — since no more requests reach the server due to caching. One of the methods mentioned in the specification is to send a request for the same URL with an unsafe method such as `POST`, but that is usually difficult to intentionally do for many clients. There is also a specification for a `Clear-Site-Data: cache` header and value, but [not all browsers support it](https://groups.google.com/a/mozilla.org/g/dev-platform/c/I939w1yrTp4) — and even when it's used, it only affects browser caches and has no effect on intermediate caches. Therefore, it should be assumed that any stored response will remain for its `max-age` period unless the user manually performs a reload, force-reload, or clear-history action. Caching reduces access to the server, which means that the server loses control of that URL. If the server does not want to lose control of a URL — for example, in the case that a resource is frequently updated — you should add `no-cache` so that the server will always receive requests and send the intended responses. Request collapse ---------------- The shared cache is primarily located before the origin server and is intended to reduce traffic to the origin server. Thus, if multiple identical requests arrive at a shared cache at the same time, the intermediate cache will forward a single request on behalf of itself to the origin, which can then reuse the result for all clients. This is called ***request collapse***. Request collapse occurs when requests are arriving at the same time, so even if `max-age=0` or `no-cache` is given in the response, it will be reused. If the response is personalized to a particular user and you do not want it to be shared in collapse, you should add the `private` directive: Common caching patterns ----------------------- There are many directives in the `Cache-Control` spec, and it may be difficult to understand all of them. But most websites can be covered by a combination of a handful of patterns. This section describes the common patterns in designing caches. ### Default settings As mentioned above, the default behavior for caching (that is, for a response without `Cache-Control`) is not simply "don't cache" but implicit caching according to so-called "heuristic caching". To avoid that heuristic caching, it's preferable to explicitly give all responses a default `Cache-Control` header. To ensure that by default the latest versions of resources will always be transferred, it's common practice to make the default `Cache-Control` value include `no-cache`: ``` Cache-Control: no-cache ``` In addition, if the service implements cookies or other login methods, and the content is personalized for each user, `private` must be given too, to prevent sharing with other users: ``` Cache-Control: no-cache, private ``` ### Cache Busting The resources that work best with caching are static immutable files whose contents never change. And for resources that *do* change, it is a common best practice to change the URL each time the content changes, so that the URL unit can be cached for a longer period. As an example, consider the following HTML: ``` <script src="bundle.js"></script> <link rel="stylesheet" href="build.css" /> <body> hello </body> ``` In modern web development, JavaScript and CSS resources are frequently updated as development progresses. Also, if the versions of JavaScript and CSS resources that a client uses are out of sync, the display will break. So the HTML above makes it difficult to cache `bundle.js` and `build.css` with `max-age`. Therefore, you can serve the JavaScript and CSS with URLs that include a changing part based on a version number or hash value. Some of the ways to do that are shown below. ``` # version in filename bundle.v123.js # version in query bundle.js?v=123 # hash in filename bundle.YsAIAAAA-QG4G6kCMAMBAAAAAAAoK.js # hash in query bundle.js?v=YsAIAAAA-QG4G6kCMAMBAAAAAAAoK ``` Since the cache distinguishes resources from one another based on their URLs, the cache will not be reused again if the URL changes when a resource is updated. ``` <script src="bundle.v123.js"></script> <link rel="stylesheet" href="build.v123.css" /> <body> hello </body> ``` With that design, both JavaScript and CSS resources can be cached for a long time. So how long should `max-age` be set to? The QPACK specification provides an answer to that question. [QPACK](https://datatracker.ietf.org/doc/html/rfc9204) is a standard for compressing HTTP header fields, with tables of commonly-used field values defined. Some commonly-used cache-header values are shown below. ``` 36 cache-control max-age=0 37 cache-control max-age=604800 38 cache-control max-age=2592000 39 cache-control no-cache 40 cache-control no-store 41 cache-control public, max-age=31536000 ``` If you select one of those numbered options, you can compress values in 1 byte when transferred via HTTP3. Numbers `37`, `38`, and `41` are for periods of one week, one month, and one year. Because the cache removes old entries when new entries are saved, the probability that a stored response still exists after one week is not that high — even if `max-age` is set to 1 week. Therefore, in practice, it does not make much difference which one you choose. Note that number `41` has the longest `max-age` (1 year), but with `public`. The `public` value has the effect of making the response storable even if the `Authorization` header is present. **Note:** The `public` directive should only be used if there is a need to store the response when the `Authorization` header is set. It is not required otherwise, because a response will be stored in the shared cache as long as `max-age` is given. So if the response is personalized with basic authentication, the presence of `public` may cause problems. If you are concerned about that, you can choose the second-longest value, `38` (1 month). ``` # response for bundle.v123.js # If you never personalize responses via Authorization Cache-Control: public, max-age=31536000 # If you can't be certain Cache-Control: max-age=2592000 ``` ### Validation Don't forget to set the `Last-Modified` and `ETag` headers, so that you don't have to re-transmit a resource when reloading. It's easy to generate those headers for pre-built static files. The `ETag` value here may be a hash of the file. ``` # response for bundle.v123.js Last-Modified: Tue, 22 Feb 2022 20:20:20 GMT ETag: YsAIAAAA-QG4G6kCMAMBAAAAAAAoK ``` In addition, `immutable` can be added to prevent validation on reload. The combined result is shown below. ``` # bundle.v123.js HTTP/1.1 200 OK Content-Type: application/javascript Content-Length: 1024 Cache-Control: public, max-age=31536000, immutable Last-Modified: Tue, 22 Feb 2022 20:20:20 GMT ETag: YsAIAAAA-QG4G6kCMAMBAAAAAAAoK ``` **Cache busting** is a technique to make a response cacheable over a long period by changing the URL when the content changes. The technique can be applied to all subresources, such as images. **Note:** When evaluating the use of `immutable` and QPACK: If you're concerned that `immutable` changes the predefined value provided by QPACK, consider that in this case, the `immutable` part can be encoded separately by splitting the `Cache-Control` value into two lines — though this is dependent on the encoding algorithm a particular QPACK implementation uses. ``` Cache-Control: public, max-age=31536000 Cache-Control: immutable ``` ### Main resources Unlike subresources, main resources cannot be cache busted because their URLs can't be decorated in the same way that subresource URLs can be. If the following HTML itself is stored, the latest version cannot be displayed even if the content is updated on the server side. ``` <script src="bundle.v123.js"></script> <link rel="stylesheet" href="build.v123.css" /> <body> hello </body> ``` For that case, `no-cache` would be appropriate — rather than `no-store` — since we don't want to store HTML, but instead just want it to always be up-to-date. Furthermore, adding `Last-Modified` and `ETag` will allow clients to send conditional requests, and a `304 Not Modified` can be returned if there have been no updates to the HTML: ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1024 Cache-Control: no-cache Last-Modified: Tue, 22 Feb 2022 20:20:20 GMT ETag: AAPuIbAOdvAGEETbgAAAAAAABAAE ``` That setting is appropriate for non-personalized HTML, but for a response that gets personalized using cookies — for example, after a login — don't forget to also specify `private`: ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1024 Cache-Control: no-cache, private Last-Modified: Tue, 22 Feb 2022 20:20:20 GMT ETag: AAPuIbAOdvAGEETbgAAAAAAABAAE Set-Cookie: \_\_Host-SID=AHNtAyt3fvJrUL5g5tnGwER; Secure; Path=/; HttpOnly ``` The same can be used for `favicon.ico`, `manifest.json`, `.well-known`, and API endpoints whose URLs cannot be changed using cache busting. Most web content can be covered by a combination of the two patterns described above. ### More about managed caches With the method described in previous sections, subresources can be cached for a long time by using cache busting, but main resources (which are usually HTML documents) can't be. Caching main resources is difficult because, using just standard directives from the HTTP Caching specification, there's no way to actively delete cache contents when content is updated on the server. However, it is possible by deploying a managed cache such as a CDN or service worker. For example, a CDN that allows cache purging via an API or dashboard operation would allow for a more aggressive caching strategy by storing the main resource and explicitly purging the relevant cache only when an update occurs on the server. A service worker could do the same if it could delete the contents in the Cache API when an update occurs on the server. For more information, see the documentation for your CDN, and consult the [service worker documentation](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API). See also -------- * [RFC 9111: Hypertext Transfer Protocol (HTTP/1.1): Caching](https://datatracker.ietf.org/doc/html/RFC9111) * [Caching Tutorial - Mark Nottingham](https://www.mnot.net/cache_docs/)
programming_docs
http Status Status ====== HTTP response status codes ========================== HTTP response status codes indicate whether a specific [HTTP](index) request has been successfully completed. Responses are grouped in five classes: 1. [Informational responses](#information_responses) (`100` – `199`) 2. [Successful responses](#successful_responses) (`200` – `299`) 3. [Redirection messages](#redirection_messages) (`300` – `399`) 4. [Client error responses](#client_error_responses) (`400` – `499`) 5. [Server error responses](#server_error_responses) (`500` – `599`) The status codes listed below are defined by [RFC 9110](https://httpwg.org/specs/rfc9110.html#overview.of.status.codes). **Note:** If you receive a response that is not in [this list](#information_responses), it is a non-standard response, possibly custom to the server's software. Information responses --------------------- [`100 Continue`](status/100) This interim response indicates that the client should continue the request or ignore the response if the request is already finished. [`101 Switching Protocols`](status/101) This code is sent in response to an [`Upgrade`](headers/upgrade) request header from the client and indicates the protocol the server is switching to. [`102 Processing`](status/102) ([WebDAV](https://developer.mozilla.org/en-US/docs/Glossary/WebDAV)) This code indicates that the server has received and is processing the request, but no response is available yet. [`103 Early Hints`](status/103) This status code is primarily intended to be used with the [`Link`](headers/link) header, letting the user agent start [preloading](https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types/preload) resources while the server prepares a response. Successful responses -------------------- [`200 OK`](status/200) The request succeeded. The result meaning of "success" depends on the HTTP method: * `GET`: The resource has been fetched and transmitted in the message body. * `HEAD`: The representation headers are included in the response without any message body. * `PUT` or `POST`: The resource describing the result of the action is transmitted in the message body. * `TRACE`: The message body contains the request message as received by the server. [`201 Created`](status/201) The request succeeded, and a new resource was created as a result. This is typically the response sent after `POST` requests, or some `PUT` requests. [`202 Accepted`](status/202) The request has been received but not yet acted upon. It is noncommittal, since there is no way in HTTP to later send an asynchronous response indicating the outcome of the request. It is intended for cases where another process or server handles the request, or for batch processing. [`203 Non-Authoritative Information`](status/203) This response code means the returned metadata is not exactly the same as is available from the origin server, but is collected from a local or a third-party copy. This is mostly used for mirrors or backups of another resource. Except for that specific case, the `200 OK` response is preferred to this status. [`204 No Content`](status/204) There is no content to send for this request, but the headers may be useful. The user agent may update its cached headers for this resource with the new ones. [`205 Reset Content`](status/205) Tells the user agent to reset the document which sent this request. [`206 Partial Content`](status/206) This response code is used when the [`Range`](headers/range) header is sent from the client to request only part of a resource. [`207 Multi-Status`](status/207) ([WebDAV](https://developer.mozilla.org/en-US/docs/Glossary/WebDAV)) Conveys information about multiple resources, for situations where multiple status codes might be appropriate. [`208 Already Reported`](status/208) ([WebDAV](https://developer.mozilla.org/en-US/docs/Glossary/WebDAV)) Used inside a `<dav:propstat>` response element to avoid repeatedly enumerating the internal members of multiple bindings to the same collection. [`226 IM Used`](status/226) ([HTTP Delta encoding](https://datatracker.ietf.org/doc/html/rfc3229)) The server has fulfilled a `GET` request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance. Redirection messages -------------------- [`300 Multiple Choices`](status/300) The request has more than one possible response. The user agent or user should choose one of them. (There is no standardized way of choosing one of the responses, but HTML links to the possibilities are recommended so the user can pick.) [`301 Moved Permanently`](status/301) The URL of the requested resource has been changed permanently. The new URL is given in the response. [`302 Found`](status/302) This response code means that the URI of requested resource has been changed *temporarily*. Further changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests. [`303 See Other`](status/303) The server sent this response to direct the client to get the requested resource at another URI with a GET request. [`304 Not Modified`](status/304) This is used for caching purposes. It tells the client that the response has not been modified, so the client can continue to use the same cached version of the response. `305 Use Proxy` Deprecated Defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy. `306 unused` This response code is no longer used; it is just reserved. It was used in a previous version of the HTTP/1.1 specification. [`307 Temporary Redirect`](status/307) The server sends this response to direct the client to get the requested resource at another URI with same method that was used in the prior request. This has the same semantics as the `302 Found` HTTP response code, with the exception that the user agent *must not* change the HTTP method used: if a `POST` was used in the first request, a `POST` must be used in the second request. [`308 Permanent Redirect`](status/308) This means that the resource is now permanently located at another URI, specified by the `Location:` HTTP Response header. This has the same semantics as the `301 Moved Permanently` HTTP response code, with the exception that the user agent *must not* change the HTTP method used: if a `POST` was used in the first request, a `POST` must be used in the second request. Client error responses ---------------------- [`400 Bad Request`](status/400) The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). [`401 Unauthorized`](status/401) Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response. [`402 Payment Required`](status/402) Experimental This response code is reserved for future use. The initial aim for creating this code was using it for digital payment systems, however this status code is used very rarely and no standard convention exists. [`403 Forbidden`](status/403) The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource. Unlike `401 Unauthorized`, the client's identity is known to the server. [`404 Not Found`](status/404) The server cannot find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of `403 Forbidden` to hide the existence of a resource from an unauthorized client. This response code is probably the most well known due to its frequent occurrence on the web. [`405 Method Not Allowed`](status/405) The request method is known by the server but is not supported by the target resource. For example, an API may not allow calling `DELETE` to remove a resource. [`406 Not Acceptable`](status/406) This response is sent when the web server, after performing [server-driven content negotiation](content_negotiation#server-driven_negotiation), doesn't find any content that conforms to the criteria given by the user agent. [`407 Proxy Authentication Required`](status/407) This is similar to `401 Unauthorized` but authentication is needed to be done by a proxy. [`408 Request Timeout`](status/408) This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message. [`409 Conflict`](status/409) This response is sent when a request conflicts with the current state of the server. [`410 Gone`](status/410) This response is sent when the requested content has been permanently deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code. [`411 Length Required`](status/411) Server rejected the request because the `Content-Length` header field is not defined and the server requires it. [`412 Precondition Failed`](status/412) The client has indicated preconditions in its headers which the server does not meet. [`413 Payload Too Large`](status/413) Request entity is larger than limits defined by server. The server might close the connection or return an `Retry-After` header field. [`414 URI Too Long`](status/414) The URI requested by the client is longer than the server is willing to interpret. [`415 Unsupported Media Type`](status/415) The media format of the requested data is not supported by the server, so the server is rejecting the request. [`416 Range Not Satisfiable`](status/416) The range specified by the `Range` header field in the request cannot be fulfilled. It's possible that the range is outside the size of the target URI's data. [`417 Expectation Failed`](status/417) This response code means the expectation indicated by the `Expect` request header field cannot be met by the server. [`418 I'm a teapot`](status/418) The server refuses the attempt to brew coffee with a teapot. [`421 Misdirected Request`](status/421) The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI. [`422 Unprocessable Entity`](status/422) ([WebDAV](https://developer.mozilla.org/en-US/docs/Glossary/WebDAV)) The request was well-formed but was unable to be followed due to semantic errors. [`423 Locked`](status/423) ([WebDAV](https://developer.mozilla.org/en-US/docs/Glossary/WebDAV)) The resource that is being accessed is locked. [`424 Failed Dependency`](status/424) ([WebDAV](https://developer.mozilla.org/en-US/docs/Glossary/WebDAV)) The request failed due to failure of a previous request. [`425 Too Early`](status/425) Experimental Indicates that the server is unwilling to risk processing a request that might be replayed. [`426 Upgrade Required`](status/426) The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server sends an [`Upgrade`](headers/upgrade) header in a 426 response to indicate the required protocol(s). [`428 Precondition Required`](status/428) The origin server requires the request to be conditional. This response is intended to prevent the 'lost update' problem, where a client `GET`s a resource's state, modifies it and `PUT`s it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict. [`429 Too Many Requests`](status/429) The user has sent too many requests in a given amount of time ("rate limiting"). [`431 Request Header Fields Too Large`](status/431) The server is unwilling to process the request because its header fields are too large. The request may be resubmitted after reducing the size of the request header fields. [`451 Unavailable For Legal Reasons`](status/451) The user agent requested a resource that cannot legally be provided, such as a web page censored by a government. Server error responses ---------------------- [`500 Internal Server Error`](status/500) The server has encountered a situation it does not know how to handle. [`501 Not Implemented`](status/501) The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are `GET` and `HEAD`. [`502 Bad Gateway`](status/502) This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response. [`503 Service Unavailable`](status/503) The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This response should be used for temporary conditions and the `Retry-After` HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached. [`504 Gateway Timeout`](status/504) This error response is given when the server is acting as a gateway and cannot get a response in time. [`505 HTTP Version Not Supported`](status/505) The HTTP version used in the request is not supported by the server. [`506 Variant Also Negotiates`](status/506) The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process. [`507 Insufficient Storage`](status/507) ([WebDAV](https://developer.mozilla.org/en-US/docs/Glossary/WebDAV)) The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. [`508 Loop Detected`](status/508) ([WebDAV](https://developer.mozilla.org/en-US/docs/Glossary/WebDAV)) The server detected an infinite loop while processing the request. [`510 Not Extended`](status/510) Further extensions to the request are required for the server to fulfill it. [`511 Network Authentication Required`](status/511) Indicates that the client needs to authenticate to gain network access. Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `100` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `103` | 103 | No | No | No | No | No | ? | 103 | ? | ? | ? | ? | | `200` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `201` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `204` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `206` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `301` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `302` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `303` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `304` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `307` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `308` | 36 | 12 | 14 | 11 Does not work below Windows 10. | 24 | 7 | 37 | 36 | 14 | 24 | 7 | 3.0 | | `401` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `403` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `404` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `406` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `407` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `409` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `410` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `412` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `416` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `418` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `425` | No | No | 58 | No | No | No | No | No | 58 | No | No | No | | `451` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `500` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `501` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `502` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `503` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `504` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [List of HTTP status codes on Wikipedia](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) * [IANA official registry of HTTP status codes](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) http HTTP HTTP ==== HTTP ==== ***Hypertext Transfer Protocol (HTTP)*** is an [application-layer](https://en.wikipedia.org/wiki/Application_Layer) protocol for transmitting hypermedia documents, such as HTML. It was designed for communication between web browsers and web servers, but it can also be used for other purposes. HTTP follows a classical [client-server model](https://en.wikipedia.org/wiki/Client%E2%80%93server_model), with a client opening a connection to make a request, then waiting until it receives a response. HTTP is a [stateless protocol](https://en.wikipedia.org/wiki/Stateless_protocol), meaning that the server does not keep any data (state) between two requests. Tutorials --------- Learn how to use HTTP with guides and tutorials. [Overview of HTTP](overview) The basic features of the client-server protocol: what it can do and its intended uses. [HTTP Cache](caching) Caching is very important for fast Web sites. This article describes different methods of caching and how to use HTTP Headers to control them. [HTTP Cookies](cookies) How cookies work is defined by [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265). When serving an HTTP request, a server can send a `Set-Cookie` HTTP header with the response. The client then returns the cookie's value with every request to the same server in the form of a `Cookie` request header. The cookie can also be set to expire on a certain date, or restricted to a specific domain and path. [Cross-Origin Resource Sharing (CORS)](cors) **Cross-site HTTP requests** are HTTP requests for resources from a **different domain** than the domain of the resource making the request. For instance, an HTML page from Domain A (`http://domaina.example/`) makes a request for an image on Domain B (`http://domainb.foo/image.jpg`) via the `img` element. Web pages today very commonly load cross-site resources, including CSS stylesheets, images, scripts, and other resources. CORS allows web developers to control how their site reacts to cross-site requests. [HTTP Client Hints](client_hints) **Client Hints** are a set of response headers that a server can use to proactively request information from a client about the device, network, user, and user-agent-specific preferences. The server can then determine which resources to send, based on the information that the client chooses to provide. [Evolution of HTTP](basics_of_http/evolution_of_http) A brief description of the changes between the early versions of HTTP, to the modern HTTP/2, the emergent HTTP/3 and beyond. [Mozilla web security guidelines](https://infosec.mozilla.org/guidelines/web_security) A collection of tips to help operational teams with creating secure web applications. [HTTP Messages](messages) Describes the type and structure of the different kind of messages of HTTP/1.x and HTTP/2. [A typical HTTP session](session) Shows and explains the flow of a usual HTTP session. [Connection management in HTTP/1.x](connection_management_in_http_1.x) Describes the three connection management models available in HTTP/1.x, their strengths, and their weaknesses. Reference --------- Browse through detailed HTTP reference documentation. [HTTP Headers](headers) HTTP message headers are used to describe a resource, or the behavior of the server or the client. Header fields are kept in an [IANA registry](https://www.iana.org/assignments/message-headers/message-headers.xhtml#perm-headers). IANA also maintains a [registry of proposed new HTTP message headers](https://www.iana.org/assignments/message-headers/message-headers.xhtml#prov-headers). [HTTP Request Methods](methods) The different operations that can be done with HTTP: [`GET`](methods/get), [`POST`](methods/post), and also less common requests like [`OPTIONS`](methods/options), [`DELETE`](methods/delete), or [`TRACE`](methods/trace). [HTTP Status Response Codes](status) HTTP response codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: informational responses, successful responses, redirections, client errors, and servers errors. [CSP directives](headers/content-security-policy) The [`Content-Security-Policy`](headers/content-security-policy) response header fields allows website administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. Tools & resources ----------------- Helpful tools and resources for understanding and debugging HTTP. [Firefox Developer Tools](https://firefox-source-docs.mozilla.org/devtools-user/index.html) [Network monitor](https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/index.html) [Mozilla Observatory](https://observatory.mozilla.org/) A project designed to help developers, system administrators, and security professionals configure their sites safely and securely. [RedBot](https://redbot.org/) Tools to check your cache-related headers. [How Browsers Work (2011)](https://web.dev/howbrowserswork/) A very comprehensive article on browser internals and request flow through HTTP protocol. A MUST-READ for any web developer.
programming_docs
http Cross-Origin Resource Policy (CORP) Cross-Origin Resource Policy (CORP) =================================== Cross-Origin Resource Policy (CORP) =================================== **Cross-Origin Resource Policy** is a policy set by the [`Cross-Origin-Resource-Policy` HTTP header](headers/cross-origin-resource-policy) that lets web sites and applications opt in to protection against certain requests from other origins (such as those issued with elements like `<script>` and `<img>`), to mitigate speculative side-channel attacks, like [Spectre](https://en.wikipedia.org/wiki/Spectre_(security_vulnerability)), as well as Cross-Site Script Inclusion attacks. CORP is an additional layer of protection beyond the default [same-origin policy](https://developer.mozilla.org/en-US/docs/Glossary/Same-origin_policy). Cross-Origin Resource Policy complements [Cross-Origin Read Blocking](https://fetch.spec.whatwg.org/#corb) (CORB), which is a mechanism to prevent some cross-origin reads by default. **Note:** The policy is only effective for [`no-cors`](https://fetch.spec.whatwg.org/#concept-request-mode) requests, which are issued by default for CORS-safelisted methods/headers. As this policy is expressed via a *[response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header)*, the actual request is not prevented—rather, the browser prevents the *result* from being leaked by stripping the response body. Usage ----- **Note:** Due to a [bug in Chrome](https://bugs.chromium.org/p/chromium/issues/detail?id=1074261), setting Cross-Origin-Resource-Policy can break PDF rendering, preventing visitors from being able to read past the first page of some PDFs. Exercise caution using this header in a production environment. Web applications set a Cross-Origin Resource Policy via the [`Cross-Origin-Resource-Policy`](headers/cross-origin-resource-policy) HTTP response header, which accepts one of three values: `same-site` Only requests from the same *[Site](https://developer.mozilla.org/en-US/docs/Glossary/Site)* can read the resource. **Warning:** This is less secure than an [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin). The [algorithm for checking if two origins are same site](https://html.spec.whatwg.org/multipage/origin.html#same-site) is defined in the HTML standard and involves checking the *registrable domain*. `same-origin` Only requests from the same *[origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin)* (i.e. scheme + host + port) can read the resource. `cross-origin` Requests from any *[origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin)* (both same-site and cross-site) can read the resource. This is useful when COEP is used (see below). ``` Cross-Origin-Resource-Policy: same-site | same-origin | cross-origin ``` During a cross-origin resource policy check, if the header is set, the browser will deny `no-cors` requests issued from a different origin/site. Relationship to cross-origin embedder policy (COEP) --------------------------------------------------- The [`Cross-Origin-Embedder-Policy`](headers/cross-origin-embedder-policy) HTTP response header, when used upon a document, can be used to require subresources to either be same-origin with the document, or come with a [`Cross-Origin-Resource-Policy`](headers/cross-origin-resource-policy) HTTP response header to indicate they are okay with being embedded. This is why the `cross-origin` value exists. History ------- The concept was originally proposed in 2012 (as `From-Origin`), but [resurrected](https://github.com/whatwg/fetch/issues/687) in Q2 of 2018 and implemented in Safari and Chromium. In early 2018, two side-channel hardware vulnerabilities known as *Meltdown* and *Spectre* were disclosed. These vulnerabilities allowed sensitive data disclosure due to a race condition which arose as part of speculative execution functionality, designed to improve performance. In response, Chromium shipped [Cross-Origin Read Blocking](https://fetch.spec.whatwg.org/#corb), which automatically protects certain resources (of `Content-Type` HTML, JSON and XML) against cross-origin reads. If the application does not serve a [`no-sniff` directive](headers/x-content-type-options), Chromium will attempt to guess the `Content-Type` and apply the protection anyway. `Cross-Origin-Resource-Policy` is an opt-in response header which can protect *any* resource; there is no need for browsers to sniff MIME types. Specifications -------------- | Specification | | --- | | [Fetch Standard # cross-origin-resource-policy-header](https://fetch.spec.whatwg.org/#cross-origin-resource-policy-header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Cross-Origin_Resource_Policy_(CORP)` | 73 ["Until version 75, downloads for files with this header would fail in Chrome. See [bug 952834](https://crbug.com/952834).", "From version 80 to 85, linearized PDFs served inline with this header fail to render properly. See [bug 1074261](https://crbug.com/1074261). From version 86, partial PDF loading is disabled."] | 79 | 74 | No | No | 12 | 73 ["Until version 75, downloads for files with this header would fail in Chrome. See [bug 952834](https://crbug.com/952834).", "From version 80 to 85, linearized PDFs served inline with this header fail to render properly. See [bug 1074261](https://crbug.com/1074261). From version 86, partial PDF loading is disabled."] | 73 ["Until version 75, downloads for files with this header would fail in Chrome. See [bug 952834](https://crbug.com/952834).", "From version 80 to 85, linearized PDFs served inline with this header fail to render properly. See [bug 1074261](https://crbug.com/1074261). From version 86, partial PDF loading is disabled."] | No | No | 12 | 11.0 | See also -------- * [`Cross-Origin-Resource-Policy`](headers/cross-origin-resource-policy) HTTP Header http Content negotiation Content negotiation =================== Content negotiation =================== In [HTTP](https://developer.mozilla.org/en-US/docs/Glossary/HTTP), ***content negotiation*** is the mechanism that is used for serving different [representations](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header) of a resource to the same URI to help the user agent specify which representation is best suited for the user (for example, which document language, which image format, or which content encoding). **Note:** You'll find some disadvantages of HTTP content negotiation in [a wiki page from WHATWG](https://wiki.whatwg.org/wiki/Why_not_conneg). HTML provides alternatives to content negotiation via, for example, the [`<source>` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source). Principles of content negotiation --------------------------------- A specific document is called a *resource*. When a client wants to obtain a resource, the client requests it via a URL. The server uses this URL to choose one of the variants available–each variant is called a *representation*–and returns a specific representation to the client. The overall resource, as well as each of the representations, has a specific URL. *Content negotiation* determines how a specific representation is chosen when the resource is called. There are several ways of negotiating between the client and the server. The best-suited representation is identified through one of two mechanisms: * Specific [HTTP headers](headers) by the client (*server-driven negotiation* or *proactive negotiation*), which is the standard way of negotiating a specific kind of resource. * The [`300`](status/300) (Multiple Choices) or [`406`](status/406) (Not Acceptable), [`415`](status/415) (Unsupported Media Type) [HTTP response codes](status) by the server (*agent-driven negotiation* or *reactive negotiation*), that are used as fallback mechanisms. Over the years, other content negotiation proposals, like [transparent content negotiation](https://datatracker.ietf.org/doc/html/rfc2295) and the `Alternates` header, have been proposed. They failed to get traction and were abandoned. Server-driven content negotiation --------------------------------- In *server-driven content negotiation*, or proactive content negotiation, the browser (or any other kind of user agent) sends several HTTP headers along with the URL. These headers describe the user's preferred choice. The server uses them as hints and an internal algorithm chooses the best content to serve to the client. If it can't provide a suitable resource, it might respond with [`406`](status/406) (Not Acceptable) or [`415`](status/415) (Unsupported Media Type) and set headers for the types of media that it does support (e.g., using the [`Accept-Post`](headers/accept-post) or [`Accept-Patch`](headers/accept-patch) for POST and PATCH requests, respectively). The algorithm is server-specific and not defined in the standard. See the [Apache negotiation algorithm](https://httpd.apache.org/docs/current/en/content-negotiation.html#algorithm). The HTTP/1.1 standard defines list of the standard headers that start server-driven negotiation (such as [`Accept`](headers/accept), [`Accept-Encoding`](headers/accept-encoding), and [`Accept-Language`](headers/accept-language)). Though [`User-Agent`](headers/user-agent) isn't in this list, it's sometimes also used to send a specific representation of the requested resource. However, this isn't always considered a good practice. The server uses the [`Vary`](headers/vary) header to indicate which headers it actually used for content negotiation (or more precisely, the associated request headers), so that [caches](caching) can work optimally. In addition to these, there's an experimental proposal to add more headers to the list of available headers, called *client hints*. Client hints advertise what kind of device the user agent runs on (for example, a desktop computer or a mobile device). Even if server-driven content negotiation is the most common way to agree on a specific representation of a resource, it has several drawbacks: * The server doesn't have total knowledge of the browser. Even with the Client Hints extension, it doesn't have a complete knowledge of the capabilities of the browser. Unlike reactive content negotiation where the client makes the choice, the server choice is always somewhat arbitrary. * The information from the client is quite verbose (HTTP/2 header compression mitigates this problem) and a privacy risk (HTTP fingerprinting). * As several representations of a given resource are sent, shared caches are less efficient and server implementations are more complex. ### The `Accept` header The [`Accept`](headers/accept) header lists the MIME types of media resources that the agent is willing to process. This is a comma-separated list of MIME types, each combined with a quality factor, a parameter that indicates the relative degree of preference between the different MIME types. The `Accept` header is defined by the browser, or any other user agent, and can vary according to the context. For example, fetching an HTML page or an image, a video, or a script. It's different when fetching a document entered in the address bar or an element linked via an [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img), [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video), or [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) element. Browsers are free to use the value of the header that they think is the most adequate; an exhaustive list of [default values for common browsers](content_negotiation/list_of_default_accept_values) is available. ### The `Accept-CH` header Experimental **Note:** This is part of an **experimental** technology called *Client Hints*. Initial support comes in Chrome 46 or later. The Device-Memory value is in Chrome 61 or later. The experimental [`Accept-CH`](headers/accept-ch) lists configuration data that the server can use to select an appropriate response. Valid values are: | Value | Meaning | | --- | --- | | `Device-Memory` | Indicates the approximate amount of device RAM. This value is an approximation given by rounding to the nearest power of 2 and dividing that number by 1024. For example, 512 megabytes will be reported as `0.5`. | | `Viewport-Width` | Indicates the layout viewport width in CSS pixels. | | `Width` | Indicates the resource width in physical pixels (in other words the intrinsic size of an image). | ### The `Accept-CH-Lifetime` header **Note:** This is part of an **experimental** technology called *Client Hints* and is only available in Chrome 61 or later. The [`Accept-CH-Lifetime`](headers/accept-ch-lifetime) header is used with the `Device-Memory` value of the `Accept-CH` header and indicates the amount of time the device should opt in to sharing the device memory with the server. The value is given in milliseconds and it's optional. ### The `Accept-Encoding` header The [`Accept-Encoding`](headers/accept-encoding) header defines the acceptable content encoding (supported compressions). The value is a q-factor list (e.g., `br, gzip;q=0.8`) that indicates the priority of the encoding values. The default value `identity` is at the lowest priority (unless otherwise noted). Compressing HTTP messages is one of the most important ways to improve the performance of a website. It shrinks the size of the data transmitted and makes better use of the available bandwidth. Browsers always send this header and the server should be configured to use compression. ### The `Accept-Language` header The [`Accept-Language`](headers/accept-language) header is used to indicate the language preference of the user. It's a list of values with quality factors (e.g., `"de, en;q=0.7`"). A default value is often set according to the language of the graphical interface of the user agent, but most browsers allow different language preferences to be set. Due to the [configuration-based entropy](https://www.eff.org/deeplinks/2010/01/primer-information-theory-and-privacy) increase, a modified value can be used to fingerprint the user. It's not recommended to change it and a website can't trust this value to reflect the actual intention of the user. It's best for site designers to avoid using language detection via this header as it can lead to a poor user experience. * They should always provide a way to override the server-chosen language, e.g., by providing a language menu on the site. Most user agents provide a default value for the `Accept-Language` header that's adapted to the user interface language. End users often don't modify it because they either don't know how or aren't able to do so based on their computing environment. * Once a user has overridden the server-chosen language, a site should no longer use language detection and should stick with the explicitly chosen language. In other words, only entry pages for a site should use this header to select the proper language. ### The `User-Agent` header **Note:** Though there are legitimate uses of this header for selecting content, [it's considered bad practice](browser_detection_using_the_user_agent) to rely on it to define what features are supported by the user agent. The [`User-Agent`](headers/user-agent) header identifies the browser sending the request. This string may contain a space-separated list of *product tokens* and *comments*. A *product token* is a name followed by a '`/`' and a version number, like `Firefox/4.0.1`. The user agent can include as many of these as it wants. A *comment* is an optional string delimited by parentheses. The information provided in a comment isn't standardized, though several browsers add several tokens to it separated by '`;`'. ### The `Vary` response header In contrast to the previous `Accept-*` headers, which are sent by the client, the [`Vary`](headers/vary) HTTP header is sent by the web server in its response. It indicates the list of headers the server uses during the server-driven content negotiation phase. The `Vary` header is needed to inform the cache of the decision criteria so that it can reproduce it. This allows the cache to be functional while ensuring that the right content is served to the user. The special value '`*`' means that the server-driven content negotiation also uses information not conveyed in a header to choose the appropriate content. The `Vary` header was added in version 1.1 of HTTP and allows caches to work appropriately. To work with server-driven content negotiation, a cache needs to know which criteria the server used to select the transmitted content. That way, the cache can replay the algorithm and will be able to serve acceptable content directly, without more requests to the server. Obviously, the wildcard '`*`' prevents caching from occurring, as the cache can't know what element is behind it. For more information, see [HTTP caching > Varying responses](caching#varying_responses). Agent-driven negotiation ------------------------ Server-driven negotiation has a few drawbacks: it doesn't scale well. One header per feature is used in the negotiation. If you want to use screen size, resolution, or other dimensions, you need to create a new HTTP header. The headers must then be sent with every request. This isn't an issue if there are only a few headers, but as the number of headers increases, the message size could eventually affect performance. The more precisely headers are sent, the more entropy is sent, allowing for more HTTP fingerprinting and corresponding privacy concerns. HTTP allows another negotiation type: *agent-driven negotiation* or *reactive negotiation*. In this case, the server sends back a page that contains links to the available alternative resources when faced with an ambiguous request. The user is presented the resources and chooses the one to use. Unfortunately, the HTTP standard doesn't specify the format of the page for choosing between the available resources, which prevents the process from being automated. Besides falling back to the *server-driven negotiation*, this method is almost always used with scripting, especially with JavaScript redirection: after having checked for the negotiation criteria, the script performs the redirection. A second problem is that one more request is needed to fetch the real resource, slowing the availability of the resource to the user. http HTTP Semantics Internet Engineering Task Force (IETF) R. Fielding, Ed. Request for Comments: 9110 Adobe STD: 97 M. Nottingham, Ed. Obsoletes: [2818](https://datatracker.ietf.org/doc/html/rfc2818), [7230](https://datatracker.ietf.org/doc/html/rfc7230), [7231](https://datatracker.ietf.org/doc/html/rfc7231), [7232](https://datatracker.ietf.org/doc/html/rfc7232), [7233](https://datatracker.ietf.org/doc/html/rfc7233), [7235](https://datatracker.ietf.org/doc/html/rfc7235), Fastly [7538](https://datatracker.ietf.org/doc/html/rfc7538), [7615](https://datatracker.ietf.org/doc/html/rfc7615), [7694](https://datatracker.ietf.org/doc/html/rfc7694) J. Reschke, Ed. Updates: [3864](https://datatracker.ietf.org/doc/html/rfc3864) greenbytes Category: Standards Track June 2022 ISSN: 2070-1721 HTTP Semantics ============== Abstract The Hypertext Transfer Protocol (HTTP) is a stateless application- level protocol for distributed, collaborative, hypertext information systems. This document describes the overall architecture of HTTP, establishes common terminology, and defines aspects of the protocol that are shared by all versions. In this definition are core protocol elements, extensibility mechanisms, and the "http" and "https" Uniform Resource Identifier (URI) schemes. This document updates [RFC 3864](https://datatracker.ietf.org/doc/html/rfc3864) and obsoletes RFCs 2818, 7231, 7232, 7233, 7235, 7538, 7615, 7694, and portions of 7230. Status of This Memo This is an Internet Standards Track document. This document is a product of the Internet Engineering Task Force (IETF). It represents the consensus of the IETF community. It has received public review and has been approved for publication by the Internet Engineering Steering Group (IESG). Further information on Internet Standards is available in [Section 2 of RFC 7841](https://datatracker.ietf.org/doc/html/rfc7841#section-2). Information about the current status of this document, any errata, and how to provide feedback on it may be obtained at <https://www.rfc-editor.org/info/rfc9110>. Copyright Notice Copyright (c) 2022 IETF Trust and the persons identified as the document authors. All rights reserved. This document is subject to [BCP 78](https://datatracker.ietf.org/doc/html/bcp78) and the IETF Trust's Legal Provisions Relating to IETF Documents (<https://trustee.ietf.org/license-info>) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Revised BSD License text as described in [Section 4](#section-4).e of the Trust Legal Provisions and are provided without warranty as described in the Revised BSD License. This document may contain material from IETF Documents or IETF Contributions published or made publicly available before November 10, 2008. The person(s) controlling the copyright in some of this material may not have granted the IETF Trust the right to allow modifications of such material outside the IETF Standards Process. Without obtaining an adequate license from the person(s) controlling the copyright in such materials, this document may not be modified outside the IETF Standards Process, and derivative works of it may not be created outside the IETF Standards Process, except to format it for publication as an RFC or to translate it into languages other than English. Table of Contents 1. Introduction 1.1. Purpose 1.2. History and Evolution 1.3. Core Semantics 1.4. Specifications Obsoleted by This Document 2. Conformance 2.1. Syntax Notation 2.2. Requirements Notation 2.3. Length Requirements 2.4. Error Handling 2.5. Protocol Version 3. Terminology and Core Concepts 3.1. Resources 3.2. Representations 3.3. Connections, Clients, and Servers 3.4. Messages 3.5. User Agents 3.6. Origin Server 3.7. Intermediaries 3.8. Caches 3.9. Example Message Exchange 4. Identifiers in HTTP 4.1. URI References 4.2. HTTP-Related URI Schemes 4.2.1. http URI Scheme 4.2.2. https URI Scheme 4.2.3. http(s) Normalization and Comparison 4.2.4. Deprecation of userinfo in http(s) URIs 4.2.5. http(s) References with Fragment Identifiers 4.3. Authoritative Access 4.3.1. URI Origin 4.3.2. http Origins 4.3.3. https Origins 4.3.4. https Certificate Verification 4.3.5. IP-ID Reference Identity 5. Fields 5.1. Field Names 5.2. Field Lines and Combined Field Value 5.3. Field Order 5.4. Field Limits 5.5. Field Values 5.6. Common Rules for Defining Field Values 5.6.1. Lists (#rule ABNF Extension) 5.6.1.1. Sender Requirements 5.6.1.2. Recipient Requirements 5.6.2. Tokens 5.6.3. Whitespace 5.6.4. Quoted Strings 5.6.5. Comments 5.6.6. Parameters 5.6.7. Date/Time Formats 6. Message Abstraction 6.1. Framing and Completeness 6.2. Control Data 6.3. Header Fields 6.4. Content 6.4.1. Content Semantics 6.4.2. Identifying Content 6.5. Trailer Fields 6.5.1. Limitations on Use of Trailers 6.5.2. Processing Trailer Fields 6.6. Message Metadata 6.6.1. Date 6.6.2. Trailer 7. Routing HTTP Messages 7.1. Determining the Target Resource 7.2. Host and :authority 7.3. Routing Inbound Requests 7.3.1. To a Cache 7.3.2. To a Proxy 7.3.3. To the Origin 7.4. Rejecting Misdirected Requests 7.5. Response Correlation 7.6. Message Forwarding 7.6.1. Connection 7.6.2. Max-Forwards 7.6.3. Via 7.7. Message Transformations 7.8. Upgrade 8. Representation Data and Metadata 8.1. Representation Data 8.2. Representation Metadata 8.3. Content-Type 8.3.1. Media Type 8.3.2. Charset 8.3.3. Multipart Types 8.4. Content-Encoding 8.4.1. Content Codings 8.4.1.1. Compress Coding 8.4.1.2. Deflate Coding 8.4.1.3. Gzip Coding 8.5. Content-Language 8.5.1. Language Tags 8.6. Content-Length 8.7. Content-Location 8.8. Validator Fields 8.8.1. Weak versus Strong 8.8.2. Last-Modified 8.8.2.1. Generation 8.8.2.2. Comparison 8.8.3. ETag 8.8.3.1. Generation 8.8.3.2. Comparison 8.8.3.3. Example: Entity Tags Varying on Content-Negotiated Resources 9. Methods 9.1. Overview 9.2. Common Method Properties 9.2.1. Safe Methods 9.2.2. Idempotent Methods 9.2.3. Methods and Caching 9.3. Method Definitions 9.3.1. GET 9.3.2. HEAD 9.3.3. POST 9.3.4. PUT 9.3.5. DELETE 9.3.6. CONNECT 9.3.7. OPTIONS 9.3.8. TRACE 10. Message Context 10.1. Request Context Fields 10.1.1. Expect 10.1.2. From 10.1.3. Referer 10.1.4. TE 10.1.5. User-Agent 10.2. Response Context Fields 10.2.1. Allow 10.2.2. Location 10.2.3. Retry-After 10.2.4. Server 11. HTTP Authentication 11.1. Authentication Scheme 11.2. Authentication Parameters 11.3. Challenge and Response 11.4. Credentials 11.5. Establishing a Protection Space (Realm) 11.6. Authenticating Users to Origin Servers 11.6.1. WWW-Authenticate 11.6.2. Authorization 11.6.3. Authentication-Info 11.7. Authenticating Clients to Proxies 11.7.1. Proxy-Authenticate 11.7.2. Proxy-Authorization 11.7.3. Proxy-Authentication-Info 12. Content Negotiation 12.1. Proactive Negotiation 12.2. Reactive Negotiation 12.3. Request Content Negotiation 12.4. Content Negotiation Field Features 12.4.1. Absence 12.4.2. Quality Values 12.4.3. Wildcard Values 12.5. Content Negotiation Fields 12.5.1. Accept 12.5.2. Accept-Charset 12.5.3. Accept-Encoding 12.5.4. Accept-Language 12.5.5. Vary 13. Conditional Requests 13.1. Preconditions 13.1.1. If-Match 13.1.2. If-None-Match 13.1.3. If-Modified-Since 13.1.4. If-Unmodified-Since 13.1.5. If-Range 13.2. Evaluation of Preconditions 13.2.1. When to Evaluate 13.2.2. Precedence of Preconditions 14. Range Requests 14.1. Range Units 14.1.1. Range Specifiers 14.1.2. Byte Ranges 14.2. Range 14.3. Accept-Ranges 14.4. Content-Range 14.5. Partial PUT 14.6. Media Type multipart/byteranges 15. Status Codes 15.1. Overview of Status Codes 15.2. Informational 1xx 15.2.1. 100 Continue 15.2.2. 101 Switching Protocols 15.3. Successful 2xx 15.3.1. 200 OK 15.3.2. 201 Created 15.3.3. 202 Accepted 15.3.4. 203 Non-Authoritative Information 15.3.5. 204 No Content 15.3.6. 205 Reset Content 15.3.7. 206 Partial Content 15.3.7.1. Single Part 15.3.7.2. Multiple Parts 15.3.7.3. Combining Parts 15.4. Redirection 3xx 15.4.1. 300 Multiple Choices 15.4.2. 301 Moved Permanently 15.4.3. 302 Found 15.4.4. 303 See Other 15.4.5. 304 Not Modified 15.4.6. 305 Use Proxy 15.4.7. 306 (Unused) 15.4.8. 307 Temporary Redirect 15.4.9. 308 Permanent Redirect 15.5. Client Error 4xx 15.5.1. 400 Bad Request 15.5.2. 401 Unauthorized 15.5.3. 402 Payment Required 15.5.4. 403 Forbidden 15.5.5. 404 Not Found 15.5.6. 405 Method Not Allowed 15.5.7. 406 Not Acceptable 15.5.8. 407 Proxy Authentication Required 15.5.9. 408 Request Timeout 15.5.10. 409 Conflict 15.5.11. 410 Gone 15.5.12. 411 Length Required 15.5.13. 412 Precondition Failed 15.5.14. 413 Content Too Large 15.5.15. 414 URI Too Long 15.5.16. 415 Unsupported Media Type 15.5.17. 416 Range Not Satisfiable 15.5.18. 417 Expectation Failed 15.5.19. 418 (Unused) 15.5.20. 421 Misdirected Request 15.5.21. 422 Unprocessable Content 15.5.22. 426 Upgrade Required 15.6. Server Error 5xx 15.6.1. 500 Internal Server Error 15.6.2. 501 Not Implemented 15.6.3. 502 Bad Gateway 15.6.4. 503 Service Unavailable 15.6.5. 504 Gateway Timeout 15.6.6. 505 HTTP Version Not Supported 16. Extending HTTP 16.1. Method Extensibility 16.1.1. Method Registry 16.1.2. Considerations for New Methods 16.2. Status Code Extensibility 16.2.1. Status Code Registry 16.2.2. Considerations for New Status Codes 16.3. Field Extensibility 16.3.1. Field Name Registry 16.3.2. Considerations for New Fields 16.3.2.1. Considerations for New Field Names 16.3.2.2. Considerations for New Field Values 16.4. Authentication Scheme Extensibility 16.4.1. Authentication Scheme Registry 16.4.2. Considerations for New Authentication Schemes 16.5. Range Unit Extensibility 16.5.1. Range Unit Registry 16.5.2. Considerations for New Range Units 16.6. Content Coding Extensibility 16.6.1. Content Coding Registry 16.6.2. Considerations for New Content Codings 16.7. Upgrade Token Registry 17. Security Considerations 17.1. Establishing Authority 17.2. Risks of Intermediaries 17.3. Attacks Based on File and Path Names 17.4. Attacks Based on Command, Code, or Query Injection 17.5. Attacks via Protocol Element Length 17.6. Attacks Using Shared-Dictionary Compression 17.7. Disclosure of Personal Information 17.8. Privacy of Server Log Information 17.9. Disclosure of Sensitive Information in URIs 17.10. Application Handling of Field Names 17.11. Disclosure of Fragment after Redirects 17.12. Disclosure of Product Information 17.13. Browser Fingerprinting 17.14. Validator Retention 17.15. Denial-of-Service Attacks Using Range 17.16. Authentication Considerations 17.16.1. Confidentiality of Credentials 17.16.2. Credentials and Idle Clients 17.16.3. Protection Spaces 17.16.4. Additional Response Fields 18. IANA Considerations 18.1. URI Scheme Registration 18.2. Method Registration 18.3. Status Code Registration 18.4. Field Name Registration 18.5. Authentication Scheme Registration 18.6. Content Coding Registration 18.7. Range Unit Registration 18.8. Media Type Registration 18.9. Port Registration 18.10. Upgrade Token Registration 19. References 19.1. Normative References 19.2. Informative References [Appendix A](#appendix-A). Collected ABNF [Appendix B](#appendix-B). Changes from Previous RFCs B.1. Changes from [RFC 2818](https://datatracker.ietf.org/doc/html/rfc2818) B.2. Changes from [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230) B.3. Changes from [RFC 7231](https://datatracker.ietf.org/doc/html/rfc7231) B.4. Changes from [RFC 7232](https://datatracker.ietf.org/doc/html/rfc7232) B.5. Changes from [RFC 7233](https://datatracker.ietf.org/doc/html/rfc7233) B.6. Changes from [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235) B.7. Changes from [RFC 7538](https://datatracker.ietf.org/doc/html/rfc7538) B.8. Changes from [RFC 7615](https://datatracker.ietf.org/doc/html/rfc7615) B.9. Changes from [RFC 7694](https://datatracker.ietf.org/doc/html/rfc7694) Acknowledgements Index Authors' Addresses 1. Introduction --------------- ### 1.1. Purpose The Hypertext Transfer Protocol (HTTP) is a family of stateless, application-level, request/response protocols that share a generic interface, extensible semantics, and self-descriptive messages to enable flexible interaction with network-based hypertext information systems. HTTP hides the details of how a service is implemented by presenting a uniform interface to clients that is independent of the types of resources provided. Likewise, servers do not need to be aware of each client's purpose: a request can be considered in isolation rather than being associated with a specific type of client or a predetermined sequence of application steps. This allows general- purpose implementations to be used effectively in many different contexts, reduces interaction complexity, and enables independent evolution over time. HTTP is also designed for use as an intermediation protocol, wherein proxies and gateways can translate non-HTTP information systems into a more generic interface. One consequence of this flexibility is that the protocol cannot be defined in terms of what occurs behind the interface. Instead, we are limited to defining the syntax of communication, the intent of received communication, and the expected behavior of recipients. If the communication is considered in isolation, then successful actions ought to be reflected in corresponding changes to the observable interface provided by servers. However, since multiple clients might act in parallel and perhaps at cross-purposes, we cannot require that such changes be observable beyond the scope of a single response. ### 1.2. History and Evolution HTTP has been the primary information transfer protocol for the World Wide Web since its introduction in 1990. It began as a trivial mechanism for low-latency requests, with a single method (GET) to request transfer of a presumed hypertext document identified by a given pathname. As the Web grew, HTTP was extended to enclose requests and responses within messages, transfer arbitrary data formats using MIME-like media types, and route requests through intermediaries. These protocols were eventually defined as HTTP/0.9 and HTTP/1.0 (see [HTTP/1.0]). HTTP/1.1 was designed to refine the protocol's features while retaining compatibility with the existing text-based messaging syntax, improving its interoperability, scalability, and robustness across the Internet. This included length-based data delimiters for both fixed and dynamic (chunked) content, a consistent framework for content negotiation, opaque validators for conditional requests, cache controls for better cache consistency, range requests for partial updates, and default persistent connections. HTTP/1.1 was introduced in 1995 and published on the Standards Track in 1997 [[RFC2068](https://datatracker.ietf.org/doc/html/rfc2068)], revised in 1999 [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)], and revised again in 2014 ([[RFC7230](https://datatracker.ietf.org/doc/html/rfc7230)] through [[RFC7235](https://datatracker.ietf.org/doc/html/rfc7235)]). HTTP/2 ([HTTP/2]) introduced a multiplexed session layer on top of the existing TLS and TCP protocols for exchanging concurrent HTTP messages with efficient field compression and server push. HTTP/3 ([HTTP/3]) provides greater independence for concurrent messages by using QUIC as a secure multiplexed transport over UDP instead of TCP. All three major versions of HTTP rely on the semantics defined by this document. They have not obsoleted each other because each one has specific benefits and limitations depending on the context of use. Implementations are expected to choose the most appropriate transport and messaging syntax for their particular context. This revision of HTTP separates the definition of semantics (this document) and caching ([[CACHING](#ref-CACHING)]) from the current HTTP/1.1 messaging syntax ([HTTP/1.1]) to allow each major protocol version to progress independently while referring to the same core semantics. ### 1.3. Core Semantics HTTP provides a uniform interface for interacting with a resource ([Section 3.1](#section-3.1)) -- regardless of its type, nature, or implementation -- by sending messages that manipulate or transfer representations ([Section 3.2](#section-3.2)). Each message is either a request or a response. A client constructs request messages that communicate its intentions and routes those messages toward an identified origin server. A server listens for requests, parses each message received, interprets the message semantics in relation to the identified target resource, and responds to that request with one or more response messages. The client examines received responses to see if its intentions were carried out, determining what to do next based on the status codes and content received. HTTP semantics include the intentions defined by each request method ([Section 9](#section-9)), extensions to those semantics that might be described in request header fields, status codes that describe the response ([Section 15](#section-15)), and other control data and resource metadata that might be given in response fields. Semantics also include representation metadata that describe how content is intended to be interpreted by a recipient, request header fields that might influence content selection, and the various selection algorithms that are collectively referred to as "content negotiation" ([Section 12](#section-12)). ### 1.4. Specifications Obsoleted by This Document +============================================+===========+=====+ | Title | Reference | See | +============================================+===========+=====+ | HTTP Over TLS | [[RFC2818](https://datatracker.ietf.org/doc/html/rfc2818)] | B.1 | +--------------------------------------------+-----------+-----+ | HTTP/1.1 Message Syntax and Routing [\*] | [[RFC7230](https://datatracker.ietf.org/doc/html/rfc7230)] | B.2 | +--------------------------------------------+-----------+-----+ | HTTP/1.1 Semantics and Content | [[RFC7231](https://datatracker.ietf.org/doc/html/rfc7231)] | B.3 | +--------------------------------------------+-----------+-----+ | HTTP/1.1 Conditional Requests | [[RFC7232](https://datatracker.ietf.org/doc/html/rfc7232)] | B.4 | +--------------------------------------------+-----------+-----+ | HTTP/1.1 Range Requests | [[RFC7233](https://datatracker.ietf.org/doc/html/rfc7233)] | B.5 | +--------------------------------------------+-----------+-----+ | HTTP/1.1 Authentication | [[RFC7235](https://datatracker.ietf.org/doc/html/rfc7235)] | B.6 | +--------------------------------------------+-----------+-----+ | HTTP Status Code 308 (Permanent Redirect) | [[RFC7538](https://datatracker.ietf.org/doc/html/rfc7538)] | B.7 | +--------------------------------------------+-----------+-----+ | HTTP Authentication-Info and Proxy- | [[RFC7615](https://datatracker.ietf.org/doc/html/rfc7615)] | B.8 | | Authentication-Info Response Header Fields | | | +--------------------------------------------+-----------+-----+ | HTTP Client-Initiated Content-Encoding | [[RFC7694](https://datatracker.ietf.org/doc/html/rfc7694)] | B.9 | +--------------------------------------------+-----------+-----+ Table 1 [\*] This document only obsoletes the portions of [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230) that are independent of the HTTP/1.1 messaging syntax and connection management; the remaining bits of [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230) are obsoleted by "HTTP/1.1" [HTTP/1.1]. 2. Conformance -------------- ### 2.1. Syntax Notation This specification uses the Augmented Backus-Naur Form (ABNF) notation of [[RFC5234](https://datatracker.ietf.org/doc/html/rfc5234)], extended with the notation for case- sensitivity in strings defined in [[RFC7405](https://datatracker.ietf.org/doc/html/rfc7405)]. It also uses a list extension, defined in [Section 5.6.1](#section-5.6.1), that allows for compact definition of comma-separated lists using a "#" operator (similar to how the "\*" operator indicates repetition). [Appendix A](#appendix-A) shows the collected grammar with all list operators expanded to standard ABNF notation. As a convention, ABNF rule names prefixed with "obs-" denote obsolete grammar rules that appear for historical reasons. The following core rules are included by reference, as defined in [Appendix B.1 of [RFC5234]](https://datatracker.ietf.org/doc/html/rfc5234#appendix-B.1): ALPHA (letters), CR (carriage return), CRLF (CR LF), CTL (controls), DIGIT (decimal 0-9), DQUOTE (double quote), HEXDIG (hexadecimal 0-9/A-F/a-f), HTAB (horizontal tab), LF (line feed), OCTET (any 8-bit sequence of data), SP (space), and VCHAR (any visible US-ASCII character). [Section 5.6](#section-5.6) defines some generic syntactic components for field values. This specification uses the terms "character", "character encoding scheme", "charset", and "protocol element" as they are defined in [[RFC6365](https://datatracker.ietf.org/doc/html/rfc6365)]. ### 2.2. Requirements Notation The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://datatracker.ietf.org/doc/html/bcp14) [[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)] [[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when, and only when, they appear in all capitals, as shown here. This specification targets conformance criteria according to the role of a participant in HTTP communication. Hence, requirements are placed on senders, recipients, clients, servers, user agents, intermediaries, origin servers, proxies, gateways, or caches, depending on what behavior is being constrained by the requirement. Additional requirements are placed on implementations, resource owners, and protocol element registrations when they apply beyond the scope of a single communication. The verb "generate" is used instead of "send" where a requirement applies only to implementations that create the protocol element, rather than an implementation that forwards a received element downstream. An implementation is considered conformant if it complies with all of the requirements associated with the roles it partakes in HTTP. A sender MUST NOT generate protocol elements that do not match the grammar defined by the corresponding ABNF rules. Within a given message, a sender MUST NOT generate protocol elements or syntax alternatives that are only allowed to be generated by participants in other roles (i.e., a role that the sender does not have for that message). Conformance to HTTP includes both conformance to the particular messaging syntax of the protocol version in use and conformance to the semantics of protocol elements sent. For example, a client that claims conformance to HTTP/1.1 but fails to recognize the features required of HTTP/1.1 recipients will fail to interoperate with servers that adjust their responses in accordance with those claims. Features that reflect user choices, such as content negotiation and user-selected extensions, can impact application behavior beyond the protocol stream; sending protocol elements that inaccurately reflect a user's choices will confuse the user and inhibit choice. When an implementation fails semantic conformance, recipients of that implementation's messages will eventually develop workarounds to adjust their behavior accordingly. A recipient MAY employ such workarounds while remaining conformant to this protocol if the workarounds are limited to the implementations at fault. For example, servers often scan portions of the User-Agent field value, and user agents often scan the Server field value, to adjust their own behavior with respect to known bugs or poorly chosen defaults. ### 2.3. Length Requirements A recipient SHOULD parse a received protocol element defensively, with only marginal expectations that the element will conform to its ABNF grammar and fit within a reasonable buffer size. HTTP does not have specific length limitations for many of its protocol elements because the lengths that might be appropriate will vary widely, depending on the deployment context and purpose of the implementation. Hence, interoperability between senders and recipients depends on shared expectations regarding what is a reasonable length for each protocol element. Furthermore, what is commonly understood to be a reasonable length for some protocol elements has changed over the course of the past three decades of HTTP use and is expected to continue changing in the future. At a minimum, a recipient MUST be able to parse and process protocol element lengths that are at least as long as the values that it generates for those same protocol elements in other messages. For example, an origin server that publishes very long URI references to its own resources needs to be able to parse and process those same references when received as a target URI. Many received protocol elements are only parsed to the extent necessary to identify and forward that element downstream. For example, an intermediary might parse a received field into its field name and field value components, but then forward the field without further parsing inside the field value. ### 2.4. Error Handling A recipient MUST interpret a received protocol element according to the semantics defined for it by this specification, including extensions to this specification, unless the recipient has determined (through experience or configuration) that the sender incorrectly implements what is implied by those semantics. For example, an origin server might disregard the contents of a received Accept-Encoding header field if inspection of the User-Agent header field indicates a specific implementation version that is known to fail on receipt of certain content codings. Unless noted otherwise, a recipient MAY attempt to recover a usable protocol element from an invalid construct. HTTP does not define specific error handling mechanisms except when they have a direct impact on security, since different applications of the protocol require different error handling strategies. For example, a Web browser might wish to transparently recover from a response where the Location header field doesn't parse according to the ABNF, whereas a systems control client might consider any form of error recovery to be dangerous. Some requests can be automatically retried by a client in the event of an underlying connection failure, as described in [Section 9.2.2](#section-9.2.2). ### 2.5. Protocol Version HTTP's version number consists of two decimal digits separated by a "." (period or decimal point). The first digit (major version) indicates the messaging syntax, whereas the second digit (minor version) indicates the highest minor version within that major version to which the sender is conformant (able to understand for future communication). While HTTP's core semantics don't change between protocol versions, their expression "on the wire" can change, and so the HTTP version number changes when incompatible changes are made to the wire format. Additionally, HTTP allows incremental, backwards-compatible changes to be made to the protocol without changing its version through the use of defined extension points ([Section 16](#section-16)). The protocol version as a whole indicates the sender's conformance with the set of requirements laid out in that version's corresponding specification(s). For example, the version "HTTP/1.1" is defined by the combined specifications of this document, "HTTP Caching" [[CACHING](#ref-CACHING)], and "HTTP/1.1" [HTTP/1.1]. HTTP's major version number is incremented when an incompatible message syntax is introduced. The minor number is incremented when changes made to the protocol have the effect of adding to the message semantics or implying additional capabilities of the sender. The minor version advertises the sender's communication capabilities even when the sender is only using a backwards-compatible subset of the protocol, thereby letting the recipient know that more advanced features can be used in response (by servers) or in future requests (by clients). When a major version of HTTP does not define any minor versions, the minor version "0" is implied. The "0" is used when referring to that protocol within elements that require a minor version identifier. 3. Terminology and Core Concepts -------------------------------- HTTP was created for the World Wide Web (WWW) architecture and has evolved over time to support the scalability needs of a worldwide hypertext system. Much of that architecture is reflected in the terminology used to define HTTP. ### 3.1. Resources The target of an HTTP request is called a "resource". HTTP does not limit the nature of a resource; it merely defines an interface that might be used to interact with resources. Most resources are identified by a Uniform Resource Identifier (URI), as described in [Section 4](#section-4). One design goal of HTTP is to separate resource identification from request semantics, which is made possible by vesting the request semantics in the request method ([Section 9](#section-9)) and a few request- modifying header fields. A resource cannot treat a request in a manner inconsistent with the semantics of the method of the request. For example, though the URI of a resource might imply semantics that are not safe, a client can expect the resource to avoid actions that are unsafe when processing a request with a safe method (see [Section 9.2.1](#section-9.2.1)). HTTP relies upon the Uniform Resource Identifier (URI) standard [[URI](#ref-URI)] to indicate the target resource ([Section 7.1](#section-7.1)) and relationships between resources. ### 3.2. Representations A "representation" is information that is intended to reflect a past, current, or desired state of a given resource, in a format that can be readily communicated via the protocol. A representation consists of a set of representation metadata and a potentially unbounded stream of representation data ([Section 8](#section-8)). HTTP allows "information hiding" behind its uniform interface by defining communication with respect to a transferable representation of the resource state, rather than transferring the resource itself. This allows the resource identified by a URI to be anything, including temporal functions like "the current weather in Laguna Beach", while potentially providing information that represents that resource at the time a message is generated [[REST](#ref-REST)]. The uniform interface is similar to a window through which one can observe and act upon a thing only through the communication of messages to an independent actor on the other side. A shared abstraction is needed to represent ("take the place of") the current or desired state of that thing in our communications. When a representation is hypertext, it can provide both a representation of the resource state and processing instructions that help guide the recipient's future interactions. A target resource might be provided with, or be capable of generating, multiple representations that are each intended to reflect the resource's current state. An algorithm, usually based on content negotiation ([Section 12](#section-12)), would be used to select one of those representations as being most applicable to a given request. This "selected representation" provides the data and metadata for evaluating conditional requests ([Section 13](#section-13)) and constructing the content for 200 (OK), 206 (Partial Content), and 304 (Not Modified) responses to GET ([Section 9.3.1](#section-9.3.1)). ### 3.3. Connections, Clients, and Servers HTTP is a client/server protocol that operates over a reliable transport- or session-layer "connection". An HTTP "client" is a program that establishes a connection to a server for the purpose of sending one or more HTTP requests. An HTTP "server" is a program that accepts connections in order to service HTTP requests by sending HTTP responses. The terms client and server refer only to the roles that these programs perform for a particular connection. The same program might act as a client on some connections and a server on others. HTTP is defined as a stateless protocol, meaning that each request message's semantics can be understood in isolation, and that the relationship between connections and messages on them has no impact on the interpretation of those messages. For example, a CONNECT request ([Section 9.3.6](#section-9.3.6)) or a request with the Upgrade header field ([Section 7.8](#section-7.8)) can occur at any time, not just in the first message on a connection. Many implementations depend on HTTP's stateless design in order to reuse proxied connections or dynamically load balance requests across multiple servers. As a result, a server MUST NOT assume that two requests on the same connection are from the same user agent unless the connection is secured and specific to that agent. Some non-standard HTTP extensions (e.g., [[RFC4559](https://datatracker.ietf.org/doc/html/rfc4559)]) have been known to violate this requirement, resulting in security and interoperability problems. ### 3.4. Messages HTTP is a stateless request/response protocol for exchanging "messages" across a connection. The terms "sender" and "recipient" refer to any implementation that sends or receives a given message, respectively. A client sends requests to a server in the form of a "request" message with a method ([Section 9](#section-9)) and request target ([Section 7.1](#section-7.1)). The request might also contain header fields ([Section 6.3](#section-6.3)) for request modifiers, client information, and representation metadata, content ([Section 6.4](#section-6.4)) intended for processing in accordance with the method, and trailer fields ([Section 6.5](#section-6.5)) to communicate information collected while sending the content. A server responds to a client's request by sending one or more "response" messages, each including a status code ([Section 15](#section-15)). The response might also contain header fields for server information, resource metadata, and representation metadata, content to be interpreted in accordance with the status code, and trailer fields to communicate information collected while sending the content. ### 3.5. User Agents The term "user agent" refers to any of the various client programs that initiate a request. The most familiar form of user agent is the general-purpose Web browser, but that's only a small percentage of implementations. Other common user agents include spiders (web-traversing robots), command-line tools, billboard screens, household appliances, scales, light bulbs, firmware update scripts, mobile apps, and communication devices in a multitude of shapes and sizes. Being a user agent does not imply that there is a human user directly interacting with the software agent at the time of a request. In many cases, a user agent is installed or configured to run in the background and save its results for later inspection (or save only a subset of those results that might be interesting or erroneous). Spiders, for example, are typically given a start URI and configured to follow certain behavior while crawling the Web as a hypertext graph. Many user agents cannot, or choose not to, make interactive suggestions to their user or provide adequate warning for security or privacy concerns. In the few cases where this specification requires reporting of errors to the user, it is acceptable for such reporting to only be observable in an error console or log file. Likewise, requirements that an automated action be confirmed by the user before proceeding might be met via advance configuration choices, run-time options, or simple avoidance of the unsafe action; confirmation does not imply any specific user interface or interruption of normal processing if the user has already made that choice. ### 3.6. Origin Server The term "origin server" refers to a program that can originate authoritative responses for a given target resource. The most familiar form of origin server are large public websites. However, like user agents being equated with browsers, it is easy to be misled into thinking that all origin servers are alike. Common origin servers also include home automation units, configurable networking components, office machines, autonomous robots, news feeds, traffic cameras, real-time ad selectors, and video-on-demand platforms. Most HTTP communication consists of a retrieval request (GET) for a representation of some resource identified by a URI. In the simplest case, this might be accomplished via a single bidirectional connection (===) between the user agent (UA) and the origin server (O). request > UA ======================================= O < response Figure 1 ### 3.7. Intermediaries HTTP enables the use of intermediaries to satisfy requests through a chain of connections. There are three common forms of HTTP "intermediary": proxy, gateway, and tunnel. In some cases, a single intermediary might act as an origin server, proxy, gateway, or tunnel, switching behavior based on the nature of each request. > > > > UA =========== A =========== B =========== C =========== O < < < < Figure 2 The figure above shows three intermediaries (A, B, and C) between the user agent and origin server. A request or response message that travels the whole chain will pass through four separate connections. Some HTTP communication options might apply only to the connection with the nearest, non-tunnel neighbor, only to the endpoints of the chain, or to all connections along the chain. Although the diagram is linear, each participant might be engaged in multiple, simultaneous communications. For example, B might be receiving requests from many clients other than A, and/or forwarding requests to servers other than C, at the same time that it is handling A's request. Likewise, later requests might be sent through a different path of connections, often based on dynamic configuration for load balancing. The terms "upstream" and "downstream" are used to describe directional requirements in relation to the message flow: all messages flow from upstream to downstream. The terms "inbound" and "outbound" are used to describe directional requirements in relation to the request route: inbound means "toward the origin server", whereas outbound means "toward the user agent". A "proxy" is a message-forwarding agent that is chosen by the client, usually via local configuration rules, to receive requests for some type(s) of absolute URI and attempt to satisfy those requests via translation through the HTTP interface. Some translations are minimal, such as for proxy requests for "http" URIs, whereas other requests might require translation to and from entirely different application-level protocols. Proxies are often used to group an organization's HTTP requests through a common intermediary for the sake of security services, annotation services, or shared caching. Some proxies are designed to apply transformations to selected messages or content while they are being forwarded, as described in [Section 7.7](#section-7.7). A "gateway" (a.k.a. "reverse proxy") is an intermediary that acts as an origin server for the outbound connection but translates received requests and forwards them inbound to another server or servers. Gateways are often used to encapsulate legacy or untrusted information services, to improve server performance through "accelerator" caching, and to enable partitioning or load balancing of HTTP services across multiple machines. All HTTP requirements applicable to an origin server also apply to the outbound communication of a gateway. A gateway communicates with inbound servers using any protocol that it desires, including private extensions to HTTP that are outside the scope of this specification. However, an HTTP-to-HTTP gateway that wishes to interoperate with third-party HTTP servers needs to conform to user agent requirements on the gateway's inbound connection. A "tunnel" acts as a blind relay between two connections without changing the messages. Once active, a tunnel is not considered a party to the HTTP communication, though the tunnel might have been initiated by an HTTP request. A tunnel ceases to exist when both ends of the relayed connection are closed. Tunnels are used to extend a virtual connection through an intermediary, such as when Transport Layer Security (TLS, [[TLS13](#ref-TLS13)]) is used to establish confidential communication through a shared firewall proxy. The above categories for intermediary only consider those acting as participants in the HTTP communication. There are also intermediaries that can act on lower layers of the network protocol stack, filtering or redirecting HTTP traffic without the knowledge or permission of message senders. Network intermediaries are indistinguishable (at a protocol level) from an on-path attacker, often introducing security flaws or interoperability problems due to mistakenly violating HTTP semantics. For example, an "interception proxy" [[RFC3040](https://datatracker.ietf.org/doc/html/rfc3040)] (also commonly known as a "transparent proxy" [[RFC1919](https://datatracker.ietf.org/doc/html/rfc1919)]) differs from an HTTP proxy because it is not chosen by the client. Instead, an interception proxy filters or redirects outgoing TCP port 80 packets (and occasionally other common port traffic). Interception proxies are commonly found on public network access points, as a means of enforcing account subscription prior to allowing use of non-local Internet services, and within corporate firewalls to enforce network usage policies. ### 3.8. Caches A "cache" is a local store of previous response messages and the subsystem that controls its message storage, retrieval, and deletion. A cache stores cacheable responses in order to reduce the response time and network bandwidth consumption on future, equivalent requests. Any client or server MAY employ a cache, though a cache cannot be used while acting as a tunnel. The effect of a cache is that the request/response chain is shortened if one of the participants along the chain has a cached response applicable to that request. The following illustrates the resulting chain if B has a cached copy of an earlier response from O (via C) for a request that has not been cached by UA or A. > > UA =========== A =========== B - - - - - - C - - - - - - O < < Figure 3 A response is "cacheable" if a cache is allowed to store a copy of the response message for use in answering subsequent requests. Even when a response is cacheable, there might be additional constraints placed by the client or by the origin server on when that cached response can be used for a particular request. HTTP requirements for cache behavior and cacheable responses are defined in [[CACHING](#ref-CACHING)]. There is a wide variety of architectures and configurations of caches deployed across the World Wide Web and inside large organizations. These include national hierarchies of proxy caches to save bandwidth and reduce latency, content delivery networks that use gateway caching to optimize regional and global distribution of popular sites, collaborative systems that broadcast or multicast cache entries, archives of pre-fetched cache entries for use in off-line or high-latency environments, and so on. ### 3.9. Example Message Exchange The following example illustrates a typical HTTP/1.1 message exchange for a GET request ([Section 9.3.1](#section-9.3.1)) on the URI "http://www.example.com/ hello.txt": Client request: GET /hello.txt HTTP/1.1 User-Agent: curl/7.64.1 Host: www.example.com Accept-Language: en, mi Server response: HTTP/1.1 200 OK Date: Mon, 27 Jul 2009 12:28:53 GMT Server: Apache Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT ETag: "34aa387-d-1568eb00" Accept-Ranges: bytes Content-Length: 51 Vary: Accept-Encoding Content-Type: text/plain Hello World! My content includes a trailing CRLF. 4. Identifiers in HTTP ---------------------- Uniform Resource Identifiers (URIs) [[URI](#ref-URI)] are used throughout HTTP as the means for identifying resources ([Section 3.1](#section-3.1)). ### 4.1. URI References URI references are used to target requests, indicate redirects, and define relationships. The definitions of "URI-reference", "absolute-URI", "relative-part", "authority", "port", "host", "path-abempty", "segment", and "query" are adopted from the URI generic syntax. An "absolute-path" rule is defined for protocol elements that can contain a non-empty path component. (This rule differs slightly from the path-abempty rule of [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986), which allows for an empty path, and path-absolute rule, which does not allow paths that begin with "//".) A "partial-URI" rule is defined for protocol elements that can contain a relative URI but not a fragment component. URI-reference = <URI-reference, see [[URI](#ref-URI)], Section 4.1> absolute-URI = <absolute-URI, see [[URI](#ref-URI)], Section 4.3> relative-part = <relative-part, see [[URI](#ref-URI)], Section 4.2> authority = <authority, see [[URI](#ref-URI)], Section 3.2> uri-host = <host, see [[URI](#ref-URI)], Section 3.2.2> port = <port, see [[URI](#ref-URI)], Section 3.2.3> path-abempty = <path-abempty, see [[URI](#ref-URI)], Section 3.3> segment = <segment, see [[URI](#ref-URI)], Section 3.3> query = <query, see [[URI](#ref-URI)], Section 3.4> absolute-path = 1\*( "/" segment ) partial-URI = relative-part [ "?" query ] Each protocol element in HTTP that allows a URI reference will indicate in its ABNF production whether the element allows any form of reference (URI-reference), only a URI in absolute form (absolute- URI), only the path and optional query components (partial-URI), or some combination of the above. Unless otherwise indicated, URI references are parsed relative to the target URI ([Section 7.1](#section-7.1)). It is RECOMMENDED that all senders and recipients support, at a minimum, URIs with lengths of 8000 octets in protocol elements. Note that this implies some structures and on-wire representations (for example, the request line in HTTP/1.1) will necessarily be larger in some cases. ### 4.2. HTTP-Related URI Schemes IANA maintains the registry of URI Schemes [[BCP35](#ref-BCP35)] at <<https://www.iana.org/assignments/uri-schemes/>>. Although requests might target any URI scheme, the following schemes are inherent to HTTP servers: +============+====================================+=========+ | URI Scheme | Description | Section | +============+====================================+=========+ | http | Hypertext Transfer Protocol | 4.2.1 | +------------+------------------------------------+---------+ | https | Hypertext Transfer Protocol Secure | 4.2.2 | +------------+------------------------------------+---------+ Table 2 Note that the presence of an "http" or "https" URI does not imply that there is always an HTTP server at the identified origin listening for connections. Anyone can mint a URI, whether or not a server exists and whether or not that server currently maps that identifier to a resource. The delegated nature of registered names and IP addresses creates a federated namespace whether or not an HTTP server is present. #### 4.2.1. http URI Scheme The "http" URI scheme is hereby defined for minting identifiers within the hierarchical namespace governed by a potential HTTP origin server listening for TCP ([[TCP](#ref-TCP)]) connections on a given port. http-URI = "http" "://" authority path-abempty [ "?" query ] The origin server for an "http" URI is identified by the authority component, which includes a host identifier ([[URI](#ref-URI)], Section 3.2.2) and optional port number ([[URI](#ref-URI)], Section 3.2.3). If the port subcomponent is empty or not given, TCP port 80 (the reserved port for WWW services) is the default. The origin determines who has the right to respond authoritatively to requests that target the identified resource, as defined in [Section 4.3.2](#section-4.3.2). A sender MUST NOT generate an "http" URI with an empty host identifier. A recipient that processes such a URI reference MUST reject it as invalid. The hierarchical path component and optional query component identify the target resource within that origin server's namespace. #### 4.2.2. https URI Scheme The "https" URI scheme is hereby defined for minting identifiers within the hierarchical namespace governed by a potential origin server listening for TCP connections on a given port and capable of establishing a TLS ([[TLS13](#ref-TLS13)]) connection that has been secured for HTTP communication. In this context, "secured" specifically means that the server has been authenticated as acting on behalf of the identified authority and all HTTP communication with that server has confidentiality and integrity protection that is acceptable to both client and server. https-URI = "https" "://" authority path-abempty [ "?" query ] The origin server for an "https" URI is identified by the authority component, which includes a host identifier ([[URI](#ref-URI)], Section 3.2.2) and optional port number ([[URI](#ref-URI)], Section 3.2.3). If the port subcomponent is empty or not given, TCP port 443 (the reserved port for HTTP over TLS) is the default. The origin determines who has the right to respond authoritatively to requests that target the identified resource, as defined in [Section 4.3.3](#section-4.3.3). A sender MUST NOT generate an "https" URI with an empty host identifier. A recipient that processes such a URI reference MUST reject it as invalid. The hierarchical path component and optional query component identify the target resource within that origin server's namespace. A client MUST ensure that its HTTP requests for an "https" resource are secured, prior to being communicated, and that it only accepts secured responses to those requests. Note that the definition of what cryptographic mechanisms are acceptable to client and server are usually negotiated and can change over time. Resources made available via the "https" scheme have no shared identity with the "http" scheme. They are distinct origins with separate namespaces. However, extensions to HTTP that are defined as applying to all origins with the same host, such as the Cookie protocol [[COOKIE](#ref-COOKIE)], allow information set by one service to impact communication with other services within a matching group of host domains. Such extensions ought to be designed with great care to prevent information obtained from a secured connection being inadvertently exchanged within an unsecured context. #### 4.2.3. http(s) Normalization and Comparison URIs with an "http" or "https" scheme are normalized and compared according to the methods defined in Section 6 of [[URI](#ref-URI)], using the defaults described above for each scheme. HTTP does not require the use of a specific method for determining equivalence. For example, a cache key might be compared as a simple string, after syntax-based normalization, or after scheme-based normalization. Scheme-based normalization (Section 6.2.3 of [[URI](#ref-URI)]) of "http" and "https" URIs involves the following additional rules: \* If the port is equal to the default port for a scheme, the normal form is to omit the port subcomponent. \* When not being used as the target of an OPTIONS request, an empty path component is equivalent to an absolute path of "/", so the normal form is to provide a path of "/" instead. \* The scheme and host are case-insensitive and normally provided in lowercase; all other components are compared in a case-sensitive manner. \* Characters other than those in the "reserved" set are equivalent to their percent-encoded octets: the normal form is to not encode them (see Sections [2.1](#section-2.1) and [2.2](#section-2.2) of [[URI](#ref-URI)]). For example, the following three URIs are equivalent: <http://example.com:80/~smith/home.html> http://EXAMPLE.com/%7Esmith/home.html [http://EXAMPLE.com:/%7esmith/home.html](http://EXAMPLE.com/%7esmith/home.html) Two HTTP URIs that are equivalent after normalization (using any method) can be assumed to identify the same resource, and any HTTP component MAY perform normalization. As a result, distinct resources SHOULD NOT be identified by HTTP URIs that are equivalent after normalization (using any method defined in Section 6.2 of [[URI](#ref-URI)]). #### 4.2.4. Deprecation of userinfo in http(s) URIs The URI generic syntax for authority also includes a userinfo subcomponent ([[URI](#ref-URI)], Section 3.2.1) for including user authentication information in the URI. In that subcomponent, the use of the format "user:password" is deprecated. Some implementations make use of the userinfo component for internal configuration of authentication information, such as within command invocation options, configuration files, or bookmark lists, even though such usage might expose a user identifier or password. A sender MUST NOT generate the userinfo subcomponent (and its "@" delimiter) when an "http" or "https" URI reference is generated within a message as a target URI or field value. Before making use of an "http" or "https" URI reference received from an untrusted source, a recipient SHOULD parse for userinfo and treat its presence as an error; it is likely being used to obscure the authority for the sake of phishing attacks. #### 4.2.5. http(s) References with Fragment Identifiers Fragment identifiers allow for indirect identification of a secondary resource, independent of the URI scheme, as defined in Section 3.5 of [[URI](#ref-URI)]. Some protocol elements that refer to a URI allow inclusion of a fragment, while others do not. They are distinguished by use of the ABNF rule for elements where fragment is allowed; otherwise, a specific rule that excludes fragments is used. | \*Note:\* The fragment identifier component is not part of the | scheme definition for a URI scheme (see Section 4.3 of [[URI](#ref-URI)]), | thus does not appear in the ABNF definitions for the "http" and | "https" URI schemes above. ### 4.3. Authoritative Access Authoritative access refers to dereferencing a given identifier, for the sake of access to the identified resource, in a way that the client believes is authoritative (controlled by the resource owner). The process for determining whether access is granted is defined by the URI scheme and often uses data within the URI components, such as the authority component when the generic syntax is used. However, authoritative access is not limited to the identified mechanism. [Section 4.3.1](#section-4.3.1) defines the concept of an origin as an aid to such uses, and the subsequent subsections explain how to establish that a peer has the authority to represent an origin. See [Section 17.1](#section-17.1) for security considerations related to establishing authority. #### 4.3.1. URI Origin The "origin" for a given URI is the triple of scheme, host, and port after normalizing the scheme and host to lowercase and normalizing the port to remove any leading zeros. If port is elided from the URI, the default port for that scheme is used. For example, the URI https://Example.Com/happy.js would have the origin { "https", "example.com", "443" } which can also be described as the normalized URI prefix with port always present: <https://example.com:443> Each origin defines its own namespace and controls how identifiers within that namespace are mapped to resources. In turn, how the origin responds to valid requests, consistently over time, determines the semantics that users will associate with a URI, and the usefulness of those semantics is what ultimately transforms these mechanisms into a resource for users to reference and access in the future. Two origins are distinct if they differ in scheme, host, or port. Even when it can be verified that the same entity controls two distinct origins, the two namespaces under those origins are distinct unless explicitly aliased by a server authoritative for that origin. Origin is also used within HTML and related Web protocols, beyond the scope of this document, as described in [[RFC6454](https://datatracker.ietf.org/doc/html/rfc6454)]. #### 4.3.2. http Origins Although HTTP is independent of the transport protocol, the "http" scheme ([Section 4.2.1](#section-4.2.1)) is specific to associating authority with whomever controls the origin server listening for TCP connections on the indicated port of whatever host is identified within the authority component. This is a very weak sense of authority because it depends on both client-specific name resolution mechanisms and communication that might not be secured from an on-path attacker. Nevertheless, it is a sufficient minimum for binding "http" identifiers to an origin server for consistent resolution within a trusted environment. If the host identifier is provided as an IP address, the origin server is the listener (if any) on the indicated TCP port at that IP address. If host is a registered name, the registered name is an indirect identifier for use with a name resolution service, such as DNS, to find an address for an appropriate origin server. When an "http" URI is used within a context that calls for access to the indicated resource, a client MAY attempt access by resolving the host identifier to an IP address, establishing a TCP connection to that address on the indicated port, and sending over that connection an HTTP request message containing a request target that matches the client's target URI ([Section 7.1](#section-7.1)). If the server responds to such a request with a non-interim HTTP response message, as described in [Section 15](#section-15), then that response is considered an authoritative answer to the client's request. Note, however, that the above is not the only means for obtaining an authoritative response, nor does it imply that an authoritative response is always necessary (see [[CACHING](#ref-CACHING)]). For example, the Alt- Svc header field [[ALTSVC](#ref-ALTSVC)] allows an origin server to identify other services that are also authoritative for that origin. Access to "http" identified resources might also be provided by protocols outside the scope of this document. #### 4.3.3. https Origins The "https" scheme ([Section 4.2.2](#section-4.2.2)) associates authority based on the ability of a server to use the private key corresponding to a certificate that the client considers to be trustworthy for the identified origin server. The client usually relies upon a chain of trust, conveyed from some prearranged or configured trust anchor, to deem a certificate trustworthy ([Section 4.3.4](#section-4.3.4)). In HTTP/1.1 and earlier, a client will only attribute authority to a server when they are communicating over a successfully established and secured connection specifically to that URI origin's host. The connection establishment and certificate verification are used as proof of authority. In HTTP/2 and HTTP/3, a client will attribute authority to a server when they are communicating over a successfully established and secured connection if the URI origin's host matches any of the hosts present in the server's certificate and the client believes that it could open a connection to that host for that URI. In practice, a client will make a DNS query to check that the origin's host contains the same server IP address as the established connection. This restriction can be removed by the origin server sending an equivalent ORIGIN frame [[RFC8336](https://datatracker.ietf.org/doc/html/rfc8336)]. The request target's host and port value are passed within each HTTP request, identifying the origin and distinguishing it from other namespaces that might be controlled by the same server ([Section 7.2](#section-7.2)). It is the origin's responsibility to ensure that any services provided with control over its certificate's private key are equally responsible for managing the corresponding "https" namespaces or at least prepared to reject requests that appear to have been misdirected ([Section 7.4](#section-7.4)). An origin server might be unwilling to process requests for certain target URIs even when they have the authority to do so. For example, when a host operates distinct services on different ports (e.g., 443 and 8000), checking the target URI at the origin server is necessary (even after the connection has been secured) because a network attacker might cause connections for one port to be received at some other port. Failing to check the target URI might allow such an attacker to replace a response to one target URI (e.g., "https://example.com/foo") with a seemingly authoritative response from the other port (e.g., "https://example.com:8000/foo"). Note that the "https" scheme does not rely on TCP and the connected port number for associating authority, since both are outside the secured communication and thus cannot be trusted as definitive. Hence, the HTTP communication might take place over any channel that has been secured, as defined in [Section 4.2.2](#section-4.2.2), including protocols that don't use TCP. When an "https" URI is used within a context that calls for access to the indicated resource, a client MAY attempt access by resolving the host identifier to an IP address, establishing a TCP connection to that address on the indicated port, securing the connection end-to- end by successfully initiating TLS over TCP with confidentiality and integrity protection, and sending over that connection an HTTP request message containing a request target that matches the client's target URI ([Section 7.1](#section-7.1)). If the server responds to such a request with a non-interim HTTP response message, as described in [Section 15](#section-15), then that response is considered an authoritative answer to the client's request. Note, however, that the above is not the only means for obtaining an authoritative response, nor does it imply that an authoritative response is always necessary (see [[CACHING](#ref-CACHING)]). #### 4.3.4. https Certificate Verification To establish a secured connection to dereference a URI, a client MUST verify that the service's identity is an acceptable match for the URI's origin server. Certificate verification is used to prevent server impersonation by an on-path attacker or by an attacker that controls name resolution. This process requires that a client be configured with a set of trust anchors. In general, a client MUST verify the service identity using the verification process defined in [Section 6 of [RFC6125]](https://datatracker.ietf.org/doc/html/rfc6125#section-6). The client MUST construct a reference identity from the service's host: if the host is a literal IP address ([Section 4.3.5](#section-4.3.5)), the reference identity is an IP-ID, otherwise the host is a name and the reference identity is a DNS-ID. A reference identity of type CN-ID MUST NOT be used by clients. As noted in [Section 6.2.1 of [RFC6125]](https://datatracker.ietf.org/doc/html/rfc6125#section-6.2.1), a reference identity of type CN- ID might be used by older clients. A client might be specially configured to accept an alternative form of server identity verification. For example, a client might be connecting to a server whose address and hostname are dynamic, with an expectation that the service will present a specific certificate (or a certificate matching some externally defined reference identity) rather than one matching the target URI's origin. In special cases, it might be appropriate for a client to simply ignore the server's identity, but it must be understood that this leaves a connection open to active attack. If the certificate is not valid for the target URI's origin, a user agent MUST either obtain confirmation from the user before proceeding (see [Section 3.5](#section-3.5)) or terminate the connection with a bad certificate error. Automated clients MUST log the error to an appropriate audit log (if available) and SHOULD terminate the connection (with a bad certificate error). Automated clients MAY provide a configuration setting that disables this check, but MUST provide a setting which enables it. #### 4.3.5. IP-ID Reference Identity A server that is identified using an IP address literal in the "host" field of an "https" URI has a reference identity of type IP-ID. An IP version 4 address uses the "IPv4address" ABNF rule, and an IP version 6 address uses the "IP-literal" production with the "IPv6address" option; see Section 3.2.2 of [[URI](#ref-URI)]. A reference identity of IP-ID contains the decoded bytes of the IP address. An IP version 4 address is 4 octets, and an IP version 6 address is 16 octets. Use of IP-ID is not defined for any other IP version. The iPAddress choice in the certificate subjectAltName extension does not explicitly include the IP version and so relies on the length of the address to distinguish versions; see [Section 4.2.1.6 of [RFC5280]](https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.6). A reference identity of type IP-ID matches if the address is identical to an iPAddress value of the subjectAltName extension of the certificate. 5. Fields --------- HTTP uses "fields" to provide data in the form of extensible name/ value pairs with a registered key namespace. Fields are sent and received within the header and trailer sections of messages ([Section 6](#section-6)). ### 5.1. Field Names A field name labels the corresponding field value as having the semantics defined by that name. For example, the Date header field is defined in [Section 6.6.1](#section-6.6.1) as containing the origination timestamp for the message in which it appears. field-name = token Field names are case-insensitive and ought to be registered within the "Hypertext Transfer Protocol (HTTP) Field Name Registry"; see [Section 16.3.1](#section-16.3.1). The interpretation of a field does not change between minor versions of the same major HTTP version, though the default behavior of a recipient in the absence of such a field can change. Unless specified otherwise, fields are defined for all versions of HTTP. In particular, the Host and Connection fields ought to be recognized by all HTTP implementations whether or not they advertise conformance with HTTP/1.1. New fields can be introduced without changing the protocol version if their defined semantics allow them to be safely ignored by recipients that do not recognize them; see [Section 16.3](#section-16.3). A proxy MUST forward unrecognized header fields unless the field name is listed in the Connection header field ([Section 7.6.1](#section-7.6.1)) or the proxy is specifically configured to block, or otherwise transform, such fields. Other recipients SHOULD ignore unrecognized header and trailer fields. Adhering to these requirements allows HTTP's functionality to be extended without updating or removing deployed intermediaries. ### 5.2. Field Lines and Combined Field Value Field sections are composed of any number of "field lines", each with a "field name" (see [Section 5.1](#section-5.1)) identifying the field, and a "field line value" that conveys data for that instance of the field. When a field name is only present once in a section, the combined "field value" for that field consists of the corresponding field line value. When a field name is repeated within a section, its combined field value consists of the list of corresponding field line values within that section, concatenated in order, with each field line value separated by a comma. For example, this section: Example-Field: Foo, Bar Example-Field: Baz contains two field lines, both with the field name "Example-Field". The first field line has a field line value of "Foo, Bar", while the second field line value is "Baz". The field value for "Example- Field" is the list "Foo, Bar, Baz". ### 5.3. Field Order A recipient MAY combine multiple field lines within a field section that have the same field name into one field line, without changing the semantics of the message, by appending each subsequent field line value to the initial field line value in order, separated by a comma (",") and optional whitespace (OWS, defined in [Section 5.6.3](#section-5.6.3)). For consistency, use comma SP. The order in which field lines with the same name are received is therefore significant to the interpretation of the field value; a proxy MUST NOT change the order of these field line values when forwarding a message. This means that, aside from the well-known exception noted below, a sender MUST NOT generate multiple field lines with the same name in a message (whether in the headers or trailers) or append a field line when a field line of the same name already exists in the message, unless that field's definition allows multiple field line values to be recombined as a comma-separated list (i.e., at least one alternative of the field's definition allows a comma-separated list, such as an ABNF rule of #(values) defined in [Section 5.6.1](#section-5.6.1)). | \*Note:\* In practice, the "Set-Cookie" header field ([[COOKIE](#ref-COOKIE)]) | often appears in a response message across multiple field lines | and does not use the list syntax, violating the above | requirements on multiple field lines with the same field name. | Since it cannot be combined into a single field value, | recipients ought to handle "Set-Cookie" as a special case while | processing fields. (See [Appendix A.2.3](#appendix-A.2.3) of [[Kri2001](#ref-Kri2001)] for | details.) The order in which field lines with differing field names are received in a section is not significant. However, it is good practice to send header fields that contain additional control data first, such as Host on requests and Date on responses, so that implementations can decide when not to handle a message as early as possible. A server MUST NOT apply a request to the target resource until it receives the entire request header section, since later header field lines might include conditionals, authentication credentials, or deliberately misleading duplicate header fields that could impact request processing. ### 5.4. Field Limits HTTP does not place a predefined limit on the length of each field line, field value, or on the length of a header or trailer section as a whole, as described in [Section 2](#section-2). Various ad hoc limitations on individual lengths are found in practice, often depending on the specific field's semantics. A server that receives a request header field line, field value, or set of fields larger than it wishes to process MUST respond with an appropriate 4xx (Client Error) status code. Ignoring such header fields would increase the server's vulnerability to request smuggling attacks ([Section 11.2](#section-11.2) of [HTTP/1.1]). A client MAY discard or truncate received field lines that are larger than the client wishes to process if the field semantics are such that the dropped value(s) can be safely ignored without changing the message framing or response semantics. ### 5.5. Field Values HTTP field values consist of a sequence of characters in a format defined by the field's grammar. Each field's grammar is usually defined using ABNF ([[RFC5234](https://datatracker.ietf.org/doc/html/rfc5234)]). field-value = \*field-content field-content = field-vchar [ 1\*( SP / HTAB / field-vchar ) field-vchar ] field-vchar = VCHAR / obs-text obs-text = %x80-FF A field value does not include leading or trailing whitespace. When a specific version of HTTP allows such whitespace to appear in a message, a field parsing implementation MUST exclude such whitespace prior to evaluating the field value. Field values are usually constrained to the range of US-ASCII characters [[USASCII](#ref-USASCII)]. Fields needing a greater range of characters can use an encoding, such as the one defined in [[RFC8187](https://datatracker.ietf.org/doc/html/rfc8187)]. Historically, HTTP allowed field content with text in the ISO-8859-1 charset [[ISO-8859-1](#ref-ISO-8859-1)], supporting other charsets only through use of [[RFC2047](https://datatracker.ietf.org/doc/html/rfc2047)] encoding. Specifications for newly defined fields SHOULD limit their values to visible US-ASCII octets (VCHAR), SP, and HTAB. A recipient SHOULD treat other allowed octets in field content (i.e., obs-text) as opaque data. Field values containing CR, LF, or NUL characters are invalid and dangerous, due to the varying ways that implementations might parse and interpret those characters; a recipient of CR, LF, or NUL within a field value MUST either reject the message or replace each of those characters with SP before further processing or forwarding of that message. Field values containing other CTL characters are also invalid; however, recipients MAY retain such characters for the sake of robustness when they appear within a safe context (e.g., an application-specific quoted string that will not be processed by any downstream HTTP parser). Fields that only anticipate a single member as the field value are referred to as "singleton fields". Fields that allow multiple members as the field value are referred to as "list-based fields". The list operator extension of [Section 5.6.1](#section-5.6.1) is used as a common notation for defining field values that can contain multiple members. Because commas (",") are used as the delimiter between members, they need to be treated with care if they are allowed as data within a member. This is true for both list-based and singleton fields, since a singleton field might be erroneously sent with multiple members and detecting such errors improves interoperability. Fields that expect to contain a comma within a member, such as within an HTTP-date or URI-reference element, ought to be defined with delimiters around that element to distinguish any comma within that data from potential list separators. For example, a textual date and a URI (either of which might contain a comma) could be safely carried in list-based field values like these: Example-URIs: "http://example.com/a.html,foo", "http://without-a-comma.example.com/" Example-Dates: "Sat, 04 May 1996", "Wed, 14 Sep 2005" Note that double-quote delimiters are almost always used with the quoted-string production ([Section 5.6.4](#section-5.6.4)); using a different syntax inside double-quotes will likely cause unnecessary confusion. Many fields (such as Content-Type, defined in [Section 8.3](#section-8.3)) use a common syntax for parameters that allows both unquoted (token) and quoted (quoted-string) syntax for a parameter value ([Section 5.6.6](#section-5.6.6)). Use of common syntax allows recipients to reuse existing parser components. When allowing both forms, the meaning of a parameter value ought to be the same whether it was received as a token or a quoted string. | \*Note:\* For defining field value syntax, this specification | uses an ABNF rule named after the field name to define the | allowed grammar for that field's value (after said value has | been extracted from the underlying messaging syntax and | multiple instances combined into a list). ### 5.6. Common Rules for Defining Field Values #### 5.6.1. Lists (#rule ABNF Extension) A #rule extension to the ABNF rules of [[RFC5234](https://datatracker.ietf.org/doc/html/rfc5234)] is used to improve readability in the definitions of some list-based field values. A construct "#" is defined, similar to "\*", for defining comma- delimited lists of elements. The full form is "<n>#<m>element" indicating at least <n> and at most <m> elements, each separated by a single comma (",") and optional whitespace (OWS, defined in [Section 5.6.3](#section-5.6.3)). ##### 5.6.1.1. Sender Requirements In any production that uses the list construct, a sender MUST NOT generate empty list elements. In other words, a sender has to generate lists that satisfy the following syntax: 1#element => element \*( OWS "," OWS element ) and: #element => [ 1#element ] and for n >= 1 and m > 1: <n>#<m>element => element <n-1>\*<m-1>( OWS "," OWS element ) [Appendix A](#appendix-A) shows the collected ABNF for senders after the list constructs have been expanded. ##### 5.6.1.2. Recipient Requirements Empty elements do not contribute to the count of elements present. A recipient MUST parse and ignore a reasonable number of empty list elements: enough to handle common mistakes by senders that merge values, but not so much that they could be used as a denial-of- service mechanism. In other words, a recipient MUST accept lists that satisfy the following syntax: #element => [ element ] \*( OWS "," OWS [ element ] ) Note that because of the potential presence of empty list elements, the [RFC 5234](https://datatracker.ietf.org/doc/html/rfc5234) ABNF cannot enforce the cardinality of list elements, and consequently all cases are mapped as if there was no cardinality specified. For example, given these ABNF productions: example-list = 1#example-list-elmt example-list-elmt = token ; see [Section 5.6.2](#section-5.6.2) Then the following are valid values for example-list (not including the double quotes, which are present for delimitation only): "foo,bar" "foo ,bar," "foo , ,bar,charlie" In contrast, the following values would be invalid, since at least one non-empty element is required by the example-list production: "" "," ", ," #### 5.6.2. Tokens Tokens are short textual identifiers that do not include whitespace or delimiters. token = 1\*tchar tchar = "!" / "#" / "$" / "%" / "&" / "'" / "\*" / "+" / "-" / "." / "^" / "\_" / "`" / "|" / "~" / DIGIT / ALPHA ; any VCHAR, except delimiters Many HTTP field values are defined using common syntax components, separated by whitespace or specific delimiting characters. Delimiters are chosen from the set of US-ASCII visual characters not allowed in a token (DQUOTE and "(),/:;<=>?@[\]{}"). #### 5.6.3. Whitespace This specification uses three rules to denote the use of linear whitespace: OWS (optional whitespace), RWS (required whitespace), and BWS ("bad" whitespace). The OWS rule is used where zero or more linear whitespace octets might appear. For protocol elements where optional whitespace is preferred to improve readability, a sender SHOULD generate the optional whitespace as a single SP; otherwise, a sender SHOULD NOT generate optional whitespace except as needed to overwrite invalid or unwanted protocol elements during in-place message filtering. The RWS rule is used when at least one linear whitespace octet is required to separate field tokens. A sender SHOULD generate RWS as a single SP. OWS and RWS have the same semantics as a single SP. Any content known to be defined as OWS or RWS MAY be replaced with a single SP before interpreting it or forwarding the message downstream. The BWS rule is used where the grammar allows optional whitespace only for historical reasons. A sender MUST NOT generate BWS in messages. A recipient MUST parse for such bad whitespace and remove it before interpreting the protocol element. BWS has no semantics. Any content known to be defined as BWS MAY be removed before interpreting it or forwarding the message downstream. OWS = \*( SP / HTAB ) ; optional whitespace RWS = 1\*( SP / HTAB ) ; required whitespace BWS = OWS ; "bad" whitespace #### 5.6.4. Quoted Strings A string of text is parsed as a single value if it is quoted using double-quote marks. quoted-string = DQUOTE \*( qdtext / quoted-pair ) DQUOTE qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text The backslash octet ("\") can be used as a single-octet quoting mechanism within quoted-string and comment constructs. Recipients that process the value of a quoted-string MUST handle a quoted-pair as if it were replaced by the octet following the backslash. quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) A sender SHOULD NOT generate a quoted-pair in a quoted-string except where necessary to quote DQUOTE and backslash octets occurring within that string. A sender SHOULD NOT generate a quoted-pair in a comment except where necessary to quote parentheses ["(" and ")"] and backslash octets occurring within that comment. #### 5.6.5. Comments Comments can be included in some HTTP fields by surrounding the comment text with parentheses. Comments are only allowed in fields containing "comment" as part of their field value definition. comment = "(" \*( ctext / quoted-pair / comment ) ")" ctext = HTAB / SP / %x21-27 / %x2A-5B / %x5D-7E / obs-text #### 5.6.6. Parameters Parameters are instances of name/value pairs; they are often used in field values as a common syntax for appending auxiliary information to an item. Each parameter is usually delimited by an immediately preceding semicolon. parameters = \*( OWS ";" OWS [ parameter ] ) parameter = parameter-name "=" parameter-value parameter-name = token parameter-value = ( token / quoted-string ) Parameter names are case-insensitive. Parameter values might or might not be case-sensitive, depending on the semantics of the parameter name. Examples of parameters and some equivalent forms can be seen in media types ([Section 8.3.1](#section-8.3.1)) and the Accept header field ([Section 12.5.1](#section-12.5.1)). A parameter value that matches the token production can be transmitted either as a token or within a quoted-string. The quoted and unquoted values are equivalent. | \*Note:\* Parameters do not allow whitespace (not even "bad" | whitespace) around the "=" character. #### 5.6.7. Date/Time Formats Prior to 1995, there were three different formats commonly used by servers to communicate timestamps. For compatibility with old implementations, all three are defined here. The preferred format is a fixed-length and single-zone subset of the date and time specification used by the Internet Message Format [[RFC5322](https://datatracker.ietf.org/doc/html/rfc5322)]. HTTP-date = IMF-fixdate / obs-date An example of the preferred format is Sun, 06 Nov 1994 08:49:37 GMT ; IMF-fixdate Examples of the two obsolete formats are Sunday, 06-Nov-94 08:49:37 GMT ; obsolete [RFC 850](https://datatracker.ietf.org/doc/html/rfc850) format Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format A recipient that parses a timestamp value in an HTTP field MUST accept all three HTTP-date formats. When a sender generates a field that contains one or more timestamps defined as HTTP-date, the sender MUST generate those timestamps in the IMF-fixdate format. An HTTP-date value represents time as an instance of Coordinated Universal Time (UTC). The first two formats indicate UTC by the three-letter abbreviation for Greenwich Mean Time, "GMT", a predecessor of the UTC name; values in the asctime format are assumed to be in UTC. A "clock" is an implementation capable of providing a reasonable approximation of the current instant in UTC. A clock implementation ought to use NTP ([[RFC5905](https://datatracker.ietf.org/doc/html/rfc5905)]), or some similar protocol, to synchronize with UTC. Preferred format: IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT ; fixed length/zone/capitalization subset of the format ; see [Section 3.3 of [RFC5322]](https://datatracker.ietf.org/doc/html/rfc5322#section-3.3) day-name = %s"Mon" / %s"Tue" / %s"Wed" / %s"Thu" / %s"Fri" / %s"Sat" / %s"Sun" date1 = day SP month SP year ; e.g., 02 Jun 1982 day = 2DIGIT month = %s"Jan" / %s"Feb" / %s"Mar" / %s"Apr" / %s"May" / %s"Jun" / %s"Jul" / %s"Aug" / %s"Sep" / %s"Oct" / %s"Nov" / %s"Dec" year = 4DIGIT GMT = %s"GMT" time-of-day = hour ":" minute ":" second ; 00:00:00 - 23:59:60 (leap second) hour = 2DIGIT minute = 2DIGIT second = 2DIGIT Obsolete formats: obs-date = [rfc850](https://datatracker.ietf.org/doc/html/rfc850)-date / asctime-date [rfc850](https://datatracker.ietf.org/doc/html/rfc850)-date = day-name-l "," SP date2 SP time-of-day SP GMT date2 = day "-" month "-" 2DIGIT ; e.g., 02-Jun-82 day-name-l = %s"Monday" / %s"Tuesday" / %s"Wednesday" / %s"Thursday" / %s"Friday" / %s"Saturday" / %s"Sunday" asctime-date = day-name SP date3 SP time-of-day SP year date3 = month SP ( 2DIGIT / ( SP 1DIGIT )) ; e.g., Jun 2 HTTP-date is case sensitive. Note that Section 4.2 of [[CACHING](#ref-CACHING)] relaxes this for cache recipients. A sender MUST NOT generate additional whitespace in an HTTP-date beyond that specifically included as SP in the grammar. The semantics of day-name, day, month, year, and time-of-day are the same as those defined for the Internet Message Format constructs with the corresponding name ([[RFC5322], Section 3.3](https://datatracker.ietf.org/doc/html/rfc5322#section-3.3)). Recipients of a timestamp value in [rfc850](https://datatracker.ietf.org/doc/html/rfc850)-date format, which uses a two-digit year, MUST interpret a timestamp that appears to be more than 50 years in the future as representing the most recent year in the past that had the same last two digits. Recipients of timestamp values are encouraged to be robust in parsing timestamps unless otherwise restricted by the field definition. For example, messages are occasionally forwarded over HTTP from a non- HTTP source that might generate any of the date and time specifications defined by the Internet Message Format. | \*Note:\* HTTP requirements for timestamp formats apply only to | their usage within the protocol stream. Implementations are | not required to use these formats for user presentation, | request logging, etc. 6. Message Abstraction ---------------------- Each major version of HTTP defines its own syntax for communicating messages. This section defines an abstract data type for HTTP messages based on a generalization of those message characteristics, common structure, and capacity for conveying semantics. This abstraction is used to define requirements on senders and recipients that are independent of the HTTP version, such that a message in one version can be relayed through other versions without changing its meaning. A "message" consists of the following: \* control data to describe and route the message, \* a headers lookup table of name/value pairs for extending that control data and conveying additional information about the sender, message, content, or context, \* a potentially unbounded stream of content, and \* a trailers lookup table of name/value pairs for communicating information obtained while sending the content. Framing and control data is sent first, followed by a header section containing fields for the headers table. When a message includes content, the content is sent after the header section, potentially followed by a trailer section that might contain fields for the trailers table. Messages are expected to be processed as a stream, wherein the purpose of that stream and its continued processing is revealed while being read. Hence, control data describes what the recipient needs to know immediately, header fields describe what needs to be known before receiving content, the content (when present) presumably contains what the recipient wants or needs to fulfill the message semantics, and trailer fields provide optional metadata that was unknown prior to sending the content. Messages are intended to be "self-descriptive": everything a recipient needs to know about the message can be determined by looking at the message itself, after decoding or reconstituting parts that have been compressed or elided in transit, without requiring an understanding of the sender's current application state (established via prior messages). However, a client MUST retain knowledge of the request when parsing, interpreting, or caching a corresponding response. For example, responses to the HEAD method look just like the beginning of a response to GET but cannot be parsed in the same manner. Note that this message abstraction is a generalization across many versions of HTTP, including features that might not be found in some versions. For example, trailers were introduced within the HTTP/1.1 chunked transfer coding as a trailer section after the content. An equivalent feature is present in HTTP/2 and HTTP/3 within the header block that terminates each stream. ### 6.1. Framing and Completeness Message framing indicates how each message begins and ends, such that each message can be distinguished from other messages or noise on the same connection. Each major version of HTTP defines its own framing mechanism. HTTP/0.9 and early deployments of HTTP/1.0 used closure of the underlying connection to end a response. For backwards compatibility, this implicit framing is also allowed in HTTP/1.1. However, implicit framing can fail to distinguish an incomplete response if the connection closes early. For that reason, almost all modern implementations use explicit framing in the form of length- delimited sequences of message data. A message is considered "complete" when all of the octets indicated by its framing are available. Note that, when no explicit framing is used, a response message that is ended by the underlying connection's close is considered complete even though it might be indistinguishable from an incomplete response, unless a transport- level error indicates that it is not complete. ### 6.2. Control Data Messages start with control data that describe its primary purpose. Request message control data includes a request method ([Section 9](#section-9)), request target ([Section 7.1](#section-7.1)), and protocol version ([Section 2.5](#section-2.5)). Response message control data includes a status code ([Section 15](#section-15)), optional reason phrase, and protocol version. In HTTP/1.1 ([HTTP/1.1]) and earlier, control data is sent as the first line of a message. In HTTP/2 ([HTTP/2]) and HTTP/3 ([HTTP/3]), control data is sent as pseudo-header fields with a reserved name prefix (e.g., ":authority"). Every HTTP message has a protocol version. Depending on the version in use, it might be identified within the message explicitly or inferred by the connection over which the message is received. Recipients use that version information to determine limitations or potential for later communication with that sender. When a message is forwarded by an intermediary, the protocol version is updated to reflect the version used by that intermediary. The Via header field ([Section 7.6.3](#section-7.6.3)) is used to communicate upstream protocol information within a forwarded message. A client SHOULD send a request version equal to the highest version to which the client is conformant and whose major version is no higher than the highest version supported by the server, if this is known. A client MUST NOT send a version to which it is not conformant. A client MAY send a lower request version if it is known that the server incorrectly implements the HTTP specification, but only after the client has attempted at least one normal request and determined from the response status code or header fields (e.g., Server) that the server improperly handles higher request versions. A server SHOULD send a response version equal to the highest version to which the server is conformant that has a major version less than or equal to the one received in the request. A server MUST NOT send a version to which it is not conformant. A server can send a 505 (HTTP Version Not Supported) response if it wishes, for any reason, to refuse service of the client's major protocol version. A recipient that receives a message with a major version number that it implements and a minor version number higher than what it implements SHOULD process the message as if it were in the highest minor version within that major version to which the recipient is conformant. A recipient can assume that a message with a higher minor version, when sent to a recipient that has not yet indicated support for that higher version, is sufficiently backwards-compatible to be safely processed by any implementation of the same major version. ### 6.3. Header Fields Fields ([Section 5](#section-5)) that are sent or received before the content are referred to as "header fields" (or just "headers", colloquially). The "header section" of a message consists of a sequence of header field lines. Each header field might modify or extend message semantics, describe the sender, define the content, or provide additional context. | \*Note:\* We refer to named fields specifically as a "header | field" when they are only allowed to be sent in the header | section. ### 6.4. Content HTTP messages often transfer a complete or partial representation as the message "content": a stream of octets sent after the header section, as delineated by the message framing. This abstract definition of content reflects the data after it has been extracted from the message framing. For example, an HTTP/1.1 message body ([Section 6](#section-6) of [HTTP/1.1]) might consist of a stream of data encoded with the chunked transfer coding -- a sequence of data chunks, one zero-length chunk, and a trailer section -- whereas the content of that same message includes only the data stream after the transfer coding has been decoded; it does not include the chunk lengths, chunked framing syntax, nor the trailer fields ([Section 6.5](#section-6.5)). | \*Note:\* Some field names have a "Content-" prefix. This is an | informal convention; while some of these fields refer to the | content of the message, as defined above, others are scoped to | the selected representation ([Section 3.2](#section-3.2)). See the individual | field's definition to disambiguate. #### 6.4.1. Content Semantics The purpose of content in a request is defined by the method semantics ([Section 9](#section-9)). For example, a representation in the content of a PUT request ([Section 9.3.4](#section-9.3.4)) represents the desired state of the target resource after the request is successfully applied, whereas a representation in the content of a POST request ([Section 9.3.3](#section-9.3.3)) represents information to be processed by the target resource. In a response, the content's purpose is defined by the request method, response status code ([Section 15](#section-15)), and response fields describing that content. For example, the content of a 200 (OK) response to GET ([Section 9.3.1](#section-9.3.1)) represents the current state of the target resource, as observed at the time of the message origination date ([Section 6.6.1](#section-6.6.1)), whereas the content of the same status code in a response to POST might represent either the processing result or the new state of the target resource after applying the processing. The content of a 206 (Partial Content) response to GET contains either a single part of the selected representation or a multipart message body containing multiple parts of that representation, as described in [Section 15.3.7](#section-15.3.7). Response messages with an error status code usually contain content that represents the error condition, such that the content describes the error state and what steps are suggested for resolving it. Responses to the HEAD request method ([Section 9.3.2](#section-9.3.2)) never include content; the associated response header fields indicate only what their values would have been if the request method had been GET ([Section 9.3.1](#section-9.3.1)). 2xx (Successful) responses to a CONNECT request method ([Section 9.3.6](#section-9.3.6)) switch the connection to tunnel mode instead of having content. All 1xx (Informational), 204 (No Content), and 304 (Not Modified) responses do not include content. All other responses do include content, although that content might be of zero length. #### 6.4.2. Identifying Content When a complete or partial representation is transferred as message content, it is often desirable for the sender to supply, or the recipient to determine, an identifier for a resource corresponding to that specific representation. For example, a client making a GET request on a resource for "the current weather report" might want an identifier specific to the content returned (e.g., "weather report for Laguna Beach at 20210720T1711"). This can be useful for sharing or bookmarking content from resources that are expected to have changing representations over time. For a request message: \* If the request has a Content-Location header field, then the sender asserts that the content is a representation of the resource identified by the Content-Location field value. However, such an assertion cannot be trusted unless it can be verified by other means (not defined by this specification). The information might still be useful for revision history links. \* Otherwise, the content is unidentified by HTTP, but a more specific identifier might be supplied within the content itself. For a response message, the following rules are applied in order until a match is found: 1. If the request method is HEAD or the response status code is 204 (No Content) or 304 (Not Modified), there is no content in the response. 2. If the request method is GET and the response status code is 200 (OK), the content is a representation of the target resource ([Section 7.1](#section-7.1)). 3. If the request method is GET and the response status code is 203 (Non-Authoritative Information), the content is a potentially modified or enhanced representation of the target resource as provided by an intermediary. 4. If the request method is GET and the response status code is 206 (Partial Content), the content is one or more parts of a representation of the target resource. 5. If the response has a Content-Location header field and its field value is a reference to the same URI as the target URI, the content is a representation of the target resource. 6. If the response has a Content-Location header field and its field value is a reference to a URI different from the target URI, then the sender asserts that the content is a representation of the resource identified by the Content-Location field value. However, such an assertion cannot be trusted unless it can be verified by other means (not defined by this specification). 7. Otherwise, the content is unidentified by HTTP, but a more specific identifier might be supplied within the content itself. ### 6.5. Trailer Fields Fields ([Section 5](#section-5)) that are located within a "trailer section" are referred to as "trailer fields" (or just "trailers", colloquially). Trailer fields can be useful for supplying message integrity checks, digital signatures, delivery metrics, or post-processing status information. Trailer fields ought to be processed and stored separately from the fields in the header section to avoid contradicting message semantics known at the time the header section was complete. The presence or absence of certain header fields might impact choices made for the routing or processing of the message as a whole before the trailers are received; those choices cannot be unmade by the later discovery of trailer fields. #### 6.5.1. Limitations on Use of Trailers A trailer section is only possible when supported by the version of HTTP in use and enabled by an explicit framing mechanism. For example, the chunked transfer coding in HTTP/1.1 allows a trailer section to be sent after the content ([Section 7.1.2](#section-7.1.2) of [HTTP/1.1]). Many fields cannot be processed outside the header section because their evaluation is necessary prior to receiving the content, such as those that describe message framing, routing, authentication, request modifiers, response controls, or content format. A sender MUST NOT generate a trailer field unless the sender knows the corresponding header field name's definition permits the field to be sent in trailers. Trailer fields can be difficult to process by intermediaries that forward messages from one protocol version to another. If the entire message can be buffered in transit, some intermediaries could merge trailer fields into the header section (as appropriate) before it is forwarded. However, in most cases, the trailers are simply discarded. A recipient MUST NOT merge a trailer field into a header section unless the recipient understands the corresponding header field definition and that definition explicitly permits and defines how trailer field values can be safely merged. The presence of the keyword "trailers" in the TE header field ([Section 10.1.4](#section-10.1.4)) of a request indicates that the client is willing to accept trailer fields, on behalf of itself and any downstream clients. For requests from an intermediary, this implies that all downstream clients are willing to accept trailer fields in the forwarded response. Note that the presence of "trailers" does not mean that the client(s) will process any particular trailer field in the response; only that the trailer section(s) will not be dropped by any of the clients. Because of the potential for trailer fields to be discarded in transit, a server SHOULD NOT generate trailer fields that it believes are necessary for the user agent to receive. #### 6.5.2. Processing Trailer Fields The "Trailer" header field ([Section 6.6.2](#section-6.6.2)) can be sent to indicate fields likely to be sent in the trailer section, which allows recipients to prepare for their receipt before processing the content. For example, this could be useful if a field name indicates that a dynamic checksum should be calculated as the content is received and then immediately checked upon receipt of the trailer field value. Like header fields, trailer fields with the same name are processed in the order received; multiple trailer field lines with the same name have the equivalent semantics as appending the multiple values as a list of members. Trailer fields that might be generated more than once during a message MUST be defined as a list-based field even if each member value is only processed once per field line received. At the end of a message, a recipient MAY treat the set of received trailer fields as a data structure of name/value pairs, similar to (but separate from) the header fields. Additional processing expectations, if any, can be defined within the field specification for a field intended for use in trailers. ### 6.6. Message Metadata Fields that describe the message itself, such as when and how the message has been generated, can appear in both requests and responses. #### 6.6.1. Date The "Date" header field represents the date and time at which the message was originated, having the same semantics as the Origination Date Field (orig-date) defined in [Section 3.6.1 of [RFC5322]](https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.1). The field value is an HTTP-date, as defined in [Section 5.6.7](#section-5.6.7). Date = HTTP-date An example is Date: Tue, 15 Nov 1994 08:12:31 GMT A sender that generates a Date header field SHOULD generate its field value as the best available approximation of the date and time of message generation. In theory, the date ought to represent the moment just before generating the message content. In practice, a sender can generate the date value at any time during message origination. An origin server with a clock (as defined in [Section 5.6.7](#section-5.6.7)) MUST generate a Date header field in all 2xx (Successful), 3xx (Redirection), and 4xx (Client Error) responses, and MAY generate a Date header field in 1xx (Informational) and 5xx (Server Error) responses. An origin server without a clock MUST NOT generate a Date header field. A recipient with a clock that receives a response message without a Date header field MUST record the time it was received and append a corresponding Date header field to the message's header section if it is cached or forwarded downstream. A recipient with a clock that receives a response with an invalid Date header field value MAY replace that value with the time that response was received. A user agent MAY send a Date header field in a request, though generally will not do so unless it is believed to convey useful information to the server. For example, custom applications of HTTP might convey a Date if the server is expected to adjust its interpretation of the user's request based on differences between the user agent and server clocks. #### 6.6.2. Trailer The "Trailer" header field provides a list of field names that the sender anticipates sending as trailer fields within that message. This allows a recipient to prepare for receipt of the indicated metadata before it starts processing the content. Trailer = #field-name For example, a sender might indicate that a signature will be computed as the content is being streamed and provide the final signature as a trailer field. This allows a recipient to perform the same check on the fly as it receives the content. A sender that intends to generate one or more trailer fields in a message SHOULD generate a Trailer header field in the header section of that message to indicate which fields might be present in the trailers. If an intermediary discards the trailer section in transit, the Trailer field could provide a hint of what metadata was lost, though there is no guarantee that a sender of Trailer will always follow through by sending the named fields. 7. Routing HTTP Messages ------------------------ HTTP request message routing is determined by each client based on the target resource, the client's proxy configuration, and establishment or reuse of an inbound connection. The corresponding response routing follows the same connection chain back to the client. ### 7.1. Determining the Target Resource Although HTTP is used in a wide variety of applications, most clients rely on the same resource identification mechanism and configuration techniques as general-purpose Web browsers. Even when communication options are hard-coded in a client's configuration, we can think of their combined effect as a URI reference ([Section 4.1](#section-4.1)). A URI reference is resolved to its absolute form in order to obtain the "target URI". The target URI excludes the reference's fragment component, if any, since fragment identifiers are reserved for client-side processing ([[URI](#ref-URI)], Section 3.5). To perform an action on a "target resource", the client sends a request message containing enough components of its parsed target URI to enable recipients to identify that same resource. For historical reasons, the parsed target URI components, collectively referred to as the "request target", are sent within the message control data and the Host header field ([Section 7.2](#section-7.2)). There are two unusual cases for which the request target components are in a method-specific form: \* For CONNECT ([Section 9.3.6](#section-9.3.6)), the request target is the host name and port number of the tunnel destination, separated by a colon. \* For OPTIONS ([Section 9.3.7](#section-9.3.7)), the request target can be a single asterisk ("\*"). See the respective method definitions for details. These forms MUST NOT be used with other methods. Upon receipt of a client's request, a server reconstructs the target URI from the received components in accordance with their local configuration and incoming connection context. This reconstruction is specific to each major protocol version. For example, [Section 3.3](#section-3.3) of [HTTP/1.1] defines how a server determines the target URI of an HTTP/1.1 request. | \*Note:\* Previous specifications defined the recomposed target | URI as a distinct concept, the "effective request URI". ### 7.2. Host and :authority The "Host" header field in a request provides the host and port information from the target URI, enabling the origin server to distinguish among resources while servicing requests for multiple host names. In HTTP/2 [HTTP/2] and HTTP/3 [HTTP/3], the Host header field is, in some cases, supplanted by the ":authority" pseudo-header field of a request's control data. Host = uri-host [ ":" port ] ; [Section 4](#section-4) The target URI's authority information is critical for handling a request. A user agent MUST generate a Host header field in a request unless it sends that information as an ":authority" pseudo-header field. A user agent that sends Host SHOULD send it as the first field in the header section of a request. For example, a GET request to the origin server for <http://www.example.org/pub/WWW/> would begin with: GET /pub/WWW/ HTTP/1.1 Host: www.example.org Since the host and port information acts as an application-level routing mechanism, it is a frequent target for malware seeking to poison a shared cache or redirect a request to an unintended server. An interception proxy is particularly vulnerable if it relies on the host and port information for redirecting requests to internal servers, or for use as a cache key in a shared cache, without first verifying that the intercepted connection is targeting a valid IP address for that host. ### 7.3. Routing Inbound Requests Once the target URI and its origin are determined, a client decides whether a network request is necessary to accomplish the desired semantics and, if so, where that request is to be directed. #### 7.3.1. To a Cache If the client has a cache [[CACHING](#ref-CACHING)] and the request can be satisfied by it, then the request is usually directed there first. #### 7.3.2. To a Proxy If the request is not satisfied by a cache, then a typical client will check its configuration to determine whether a proxy is to be used to satisfy the request. Proxy configuration is implementation- dependent, but is often based on URI prefix matching, selective authority matching, or both, and the proxy itself is usually identified by an "http" or "https" URI. If an "http" or "https" proxy is applicable, the client connects inbound by establishing (or reusing) a connection to that proxy and then sending it an HTTP request message containing a request target that matches the client's target URI. #### 7.3.3. To the Origin If no proxy is applicable, a typical client will invoke a handler routine (specific to the target URI's scheme) to obtain access to the identified resource. How that is accomplished is dependent on the target URI scheme and defined by its associated specification. [Section 4.3.2](#section-4.3.2) defines how to obtain access to an "http" resource by establishing (or reusing) an inbound connection to the identified origin server and then sending it an HTTP request message containing a request target that matches the client's target URI. [Section 4.3.3](#section-4.3.3) defines how to obtain access to an "https" resource by establishing (or reusing) an inbound secured connection to an origin server that is authoritative for the identified origin and then sending it an HTTP request message containing a request target that matches the client's target URI. ### 7.4. Rejecting Misdirected Requests Once a request is received by a server and parsed sufficiently to determine its target URI, the server decides whether to process the request itself, forward the request to another server, redirect the client to a different resource, respond with an error, or drop the connection. This decision can be influenced by anything about the request or connection context, but is specifically directed at whether the server has been configured to process requests for that target URI and whether the connection context is appropriate for that request. For example, a request might have been misdirected, deliberately or accidentally, such that the information within a received Host header field differs from the connection's host or port. If the connection is from a trusted gateway, such inconsistency might be expected; otherwise, it might indicate an attempt to bypass security filters, trick the server into delivering non-public content, or poison a cache. See [Section 17](#section-17) for security considerations regarding message routing. Unless the connection is from a trusted gateway, an origin server MUST reject a request if any scheme-specific requirements for the target URI are not met. In particular, a request for an "https" resource MUST be rejected unless it has been received over a connection that has been secured via a certificate valid for that target URI's origin, as defined by [Section 4.2.2](#section-4.2.2). The 421 (Misdirected Request) status code in a response indicates that the origin server has rejected the request because it appears to have been misdirected ([Section 15.5.20](#section-15.5.20)). ### 7.5. Response Correlation A connection might be used for multiple request/response exchanges. The mechanism used to correlate between request and response messages is version dependent; some versions of HTTP use implicit ordering of messages, while others use an explicit identifier. All responses, regardless of the status code (including interim responses) can be sent at any time after a request is received, even if the request is not yet complete. A response can complete before its corresponding request is complete ([Section 6.1](#section-6.1)). Likewise, clients are not expected to wait any specific amount of time for a response. Clients (including intermediaries) might abandon a request if the response is not received within a reasonable period of time. A client that receives a response while it is still sending the associated request SHOULD continue sending that request unless it receives an explicit indication to the contrary (see, e.g., [Section 9.5](#section-9.5) of [HTTP/1.1] and [Section 6.4](#section-6.4) of [HTTP/2]). ### 7.6. Message Forwarding As described in [Section 3.7](#section-3.7), intermediaries can serve a variety of roles in the processing of HTTP requests and responses. Some intermediaries are used to improve performance or availability. Others are used for access control or to filter content. Since an HTTP stream has characteristics similar to a pipe-and-filter architecture, there are no inherent limits to the extent an intermediary can enhance (or interfere) with either direction of the stream. Intermediaries are expected to forward messages even when protocol elements are not recognized (e.g., new methods, status codes, or field names) since that preserves extensibility for downstream recipients. An intermediary not acting as a tunnel MUST implement the Connection header field, as specified in [Section 7.6.1](#section-7.6.1), and exclude fields from being forwarded that are only intended for the incoming connection. An intermediary MUST NOT forward a message to itself unless it is protected from an infinite request loop. In general, an intermediary ought to recognize its own server names, including any aliases, local variations, or literal IP addresses, and respond to such requests directly. An HTTP message can be parsed as a stream for incremental processing or forwarding downstream. However, senders and recipients cannot rely on incremental delivery of partial messages, since some implementations will buffer or delay message forwarding for the sake of network efficiency, security checks, or content transformations. #### 7.6.1. Connection The "Connection" header field allows the sender to list desired control options for the current connection. Connection = #connection-option connection-option = token Connection options are case-insensitive. When a field aside from Connection is used to supply control information for or about the current connection, the sender MUST list the corresponding field name within the Connection header field. Note that some versions of HTTP prohibit the use of fields for such information, and therefore do not allow the Connection field. Intermediaries MUST parse a received Connection header field before a message is forwarded and, for each connection-option in this field, remove any header or trailer field(s) from the message with the same name as the connection-option, and then remove the Connection header field itself (or replace it with the intermediary's own control options for the forwarded message). Hence, the Connection header field provides a declarative way of distinguishing fields that are only intended for the immediate recipient ("hop-by-hop") from those fields that are intended for all recipients on the chain ("end-to-end"), enabling the message to be self-descriptive and allowing future connection-specific extensions to be deployed without fear that they will be blindly forwarded by older intermediaries. Furthermore, intermediaries SHOULD remove or replace fields that are known to require removal before forwarding, whether or not they appear as a connection-option, after applying those fields' semantics. This includes but is not limited to: \* Proxy-Connection (Appendix C.2.2 of [HTTP/1.1]) \* Keep-Alive ([Section 19.7.1 of [RFC2068]](https://datatracker.ietf.org/doc/html/rfc2068#section-19.7.1)) \* TE ([Section 10.1.4](#section-10.1.4)) \* Transfer-Encoding ([Section 6.1](#section-6.1) of [HTTP/1.1]) \* Upgrade ([Section 7.8](#section-7.8)) A sender MUST NOT send a connection option corresponding to a field that is intended for all recipients of the content. For example, Cache-Control is never appropriate as a connection option (Section 5.2 of [[CACHING](#ref-CACHING)]). Connection options do not always correspond to a field present in the message, since a connection-specific field might not be needed if there are no parameters associated with a connection option. In contrast, a connection-specific field received without a corresponding connection option usually indicates that the field has been improperly forwarded by an intermediary and ought to be ignored by the recipient. When defining a new connection option that does not correspond to a field, specification authors ought to reserve the corresponding field name anyway in order to avoid later collisions. Such reserved field names are registered in the "Hypertext Transfer Protocol (HTTP) Field Name Registry" ([Section 16.3.1](#section-16.3.1)). #### 7.6.2. Max-Forwards The "Max-Forwards" header field provides a mechanism with the TRACE ([Section 9.3.8](#section-9.3.8)) and OPTIONS ([Section 9.3.7](#section-9.3.7)) request methods to limit the number of times that the request is forwarded by proxies. This can be useful when the client is attempting to trace a request that appears to be failing or looping mid-chain. Max-Forwards = 1\*DIGIT The Max-Forwards value is a decimal integer indicating the remaining number of times this request message can be forwarded. Each intermediary that receives a TRACE or OPTIONS request containing a Max-Forwards header field MUST check and update its value prior to forwarding the request. If the received value is zero (0), the intermediary MUST NOT forward the request; instead, the intermediary MUST respond as the final recipient. If the received Max-Forwards value is greater than zero, the intermediary MUST generate an updated Max-Forwards field in the forwarded message with a field value that is the lesser of a) the received value decremented by one (1) or b) the recipient's maximum supported value for Max-Forwards. A recipient MAY ignore a Max-Forwards header field received with any other request methods. #### 7.6.3. Via The "Via" header field indicates the presence of intermediate protocols and recipients between the user agent and the server (on requests) or between the origin server and the client (on responses), similar to the "Received" header field in email ([Section 3.6.7 of [RFC5322]](https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.7)). Via can be used for tracking message forwards, avoiding request loops, and identifying the protocol capabilities of senders along the request/response chain. Via = #( received-protocol RWS received-by [ RWS comment ] ) received-protocol = [ protocol-name "/" ] protocol-version ; see [Section 7.8](#section-7.8) received-by = pseudonym [ ":" port ] pseudonym = token Each member of the Via field value represents a proxy or gateway that has forwarded the message. Each intermediary appends its own information about how the message was received, such that the end result is ordered according to the sequence of forwarding recipients. A proxy MUST send an appropriate Via header field, as described below, in each message that it forwards. An HTTP-to-HTTP gateway MUST send an appropriate Via header field in each inbound request message and MAY send a Via header field in forwarded response messages. For each intermediary, the received-protocol indicates the protocol and protocol version used by the upstream sender of the message. Hence, the Via field value records the advertised protocol capabilities of the request/response chain such that they remain visible to downstream recipients; this can be useful for determining what backwards-incompatible features might be safe to use in response, or within a later request, as described in [Section 2.5](#section-2.5). For brevity, the protocol-name is omitted when the received protocol is HTTP. The received-by portion is normally the host and optional port number of a recipient server or client that subsequently forwarded the message. However, if the real host is considered to be sensitive information, a sender MAY replace it with a pseudonym. If a port is not provided, a recipient MAY interpret that as meaning it was received on the default port, if any, for the received-protocol. A sender MAY generate comments to identify the software of each recipient, analogous to the User-Agent and Server header fields. However, comments in Via are optional, and a recipient MAY remove them prior to forwarding the message. For example, a request message could be sent from an HTTP/1.0 user agent to an internal proxy code-named "fred", which uses HTTP/1.1 to forward the request to a public proxy at p.example.net, which completes the request by forwarding it to the origin server at www.example.com. The request received by www.example.com would then have the following Via header field: Via: 1.0 fred, 1.1 p.example.net An intermediary used as a portal through a network firewall SHOULD NOT forward the names and ports of hosts within the firewall region unless it is explicitly enabled to do so. If not enabled, such an intermediary SHOULD replace each received-by host of any host behind the firewall by an appropriate pseudonym for that host. An intermediary MAY combine an ordered subsequence of Via header field list members into a single member if the entries have identical received-protocol values. For example, Via: 1.0 ricky, 1.1 ethel, 1.1 fred, 1.0 lucy could be collapsed to Via: 1.0 ricky, 1.1 mertz, 1.0 lucy A sender SHOULD NOT combine multiple list members unless they are all under the same organizational control and the hosts have already been replaced by pseudonyms. A sender MUST NOT combine members that have different received-protocol values. ### 7.7. Message Transformations Some intermediaries include features for transforming messages and their content. A proxy might, for example, convert between image formats in order to save cache space or to reduce the amount of traffic on a slow link. However, operational problems might occur when these transformations are applied to content intended for critical applications, such as medical imaging or scientific data analysis, particularly when integrity checks or digital signatures are used to ensure that the content received is identical to the original. An HTTP-to-HTTP proxy is called a "transforming proxy" if it is designed or configured to modify messages in a semantically meaningful way (i.e., modifications, beyond those required by normal HTTP processing, that change the message in a way that would be significant to the original sender or potentially significant to downstream recipients). For example, a transforming proxy might be acting as a shared annotation server (modifying responses to include references to a local annotation database), a malware filter, a format transcoder, or a privacy filter. Such transformations are presumed to be desired by whichever client (or client organization) chose the proxy. If a proxy receives a target URI with a host name that is not a fully qualified domain name, it MAY add its own domain to the host name it received when forwarding the request. A proxy MUST NOT change the host name if the target URI contains a fully qualified domain name. A proxy MUST NOT modify the "absolute-path" and "query" parts of the received target URI when forwarding it to the next inbound server except as required by that forwarding protocol. For example, a proxy forwarding a request to an origin server via HTTP/1.1 will replace an empty path with "/" ([Section 3.2.1](#section-3.2.1) of [HTTP/1.1]) or "\*" ([Section 3.2.4](#section-3.2.4) of [HTTP/1.1]), depending on the request method. A proxy MUST NOT transform the content ([Section 6.4](#section-6.4)) of a response message that contains a no-transform cache directive (Section 5.2.2.6 of [[CACHING](#ref-CACHING)]). Note that this does not apply to message transformations that do not change the content, such as the addition or removal of transfer codings ([Section 7](#section-7) of [HTTP/1.1]). A proxy MAY transform the content of a message that does not contain a no-transform cache directive. A proxy that transforms the content of a 200 (OK) response can inform downstream recipients that a transformation has been applied by changing the response status code to 203 (Non-Authoritative Information) ([Section 15.3.4](#section-15.3.4)). A proxy SHOULD NOT modify header fields that provide information about the endpoints of the communication chain, the resource state, or the selected representation (other than the content) unless the field's definition specifically allows such modification or the modification is deemed necessary for privacy or security. ### 7.8. Upgrade The "Upgrade" header field is intended to provide a simple mechanism for transitioning from HTTP/1.1 to some other protocol on the same connection. A client MAY send a list of protocol names in the Upgrade header field of a request to invite the server to switch to one or more of the named protocols, in order of descending preference, before sending the final response. A server MAY ignore a received Upgrade header field if it wishes to continue using the current protocol on that connection. Upgrade cannot be used to insist on a protocol change. Upgrade = #protocol protocol = protocol-name ["/" protocol-version] protocol-name = token protocol-version = token Although protocol names are registered with a preferred case, recipients SHOULD use case-insensitive comparison when matching each protocol-name to supported protocols. A server that sends a 101 (Switching Protocols) response MUST send an Upgrade header field to indicate the new protocol(s) to which the connection is being switched; if multiple protocol layers are being switched, the sender MUST list the protocols in layer-ascending order. A server MUST NOT switch to a protocol that was not indicated by the client in the corresponding request's Upgrade header field. A server MAY choose to ignore the order of preference indicated by the client and select the new protocol(s) based on other factors, such as the nature of the request or the current load on the server. A server that sends a 426 (Upgrade Required) response MUST send an Upgrade header field to indicate the acceptable protocols, in order of descending preference. A server MAY send an Upgrade header field in any other response to advertise that it implements support for upgrading to the listed protocols, in order of descending preference, when appropriate for a future request. The following is a hypothetical example sent by a client: GET /hello HTTP/1.1 Host: www.example.com Connection: upgrade Upgrade: websocket, IRC/6.9, RTA/x11 The capabilities and nature of the application-level communication after the protocol change is entirely dependent upon the new protocol(s) chosen. However, immediately after sending the 101 (Switching Protocols) response, the server is expected to continue responding to the original request as if it had received its equivalent within the new protocol (i.e., the server still has an outstanding request to satisfy after the protocol has been changed, and is expected to do so without requiring the request to be repeated). For example, if the Upgrade header field is received in a GET request and the server decides to switch protocols, it first responds with a 101 (Switching Protocols) message in HTTP/1.1 and then immediately follows that with the new protocol's equivalent of a response to a GET on the target resource. This allows a connection to be upgraded to protocols with the same semantics as HTTP without the latency cost of an additional round trip. A server MUST NOT switch protocols unless the received message semantics can be honored by the new protocol; an OPTIONS request can be honored by any protocol. The following is an example response to the above hypothetical request: HTTP/1.1 101 Switching Protocols Connection: upgrade Upgrade: websocket [... data stream switches to websocket with an appropriate response (as defined by new protocol) to the "GET /hello" request ...] A sender of Upgrade MUST also send an "Upgrade" connection option in the Connection header field ([Section 7.6.1](#section-7.6.1)) to inform intermediaries not to forward this field. A server that receives an Upgrade header field in an HTTP/1.0 request MUST ignore that Upgrade field. A client cannot begin using an upgraded protocol on the connection until it has completely sent the request message (i.e., the client can't change the protocol it is sending in the middle of a message). If a server receives both an Upgrade and an Expect header field with the "100-continue" expectation ([Section 10.1.1](#section-10.1.1)), the server MUST send a 100 (Continue) response before sending a 101 (Switching Protocols) response. The Upgrade header field only applies to switching protocols on top of the existing connection; it cannot be used to switch the underlying connection (transport) protocol, nor to switch the existing communication to a different connection. For those purposes, it is more appropriate to use a 3xx (Redirection) response ([Section 15.4](#section-15.4)). This specification only defines the protocol name "HTTP" for use by the family of Hypertext Transfer Protocols, as defined by the HTTP version rules of [Section 2.5](#section-2.5) and future updates to this specification. Additional protocol names ought to be registered using the registration procedure defined in [Section 16.7](#section-16.7). 8. Representation Data and Metadata ----------------------------------- ### 8.1. Representation Data The representation data associated with an HTTP message is either provided as the content of the message or referred to by the message semantics and the target URI. The representation data is in a format and encoding defined by the representation metadata header fields. The data type of the representation data is determined via the header fields Content-Type and Content-Encoding. These define a two-layer, ordered encoding model: representation-data := Content-Encoding( Content-Type( data ) ) ### 8.2. Representation Metadata Representation header fields provide metadata about the representation. When a message includes content, the representation header fields describe how to interpret that data. In a response to a HEAD request, the representation header fields describe the representation data that would have been enclosed in the content if the same request had been a GET. ### 8.3. Content-Type The "Content-Type" header field indicates the media type of the associated representation: either the representation enclosed in the message content or the selected representation, as determined by the message semantics. The indicated media type defines both the data format and how that data is intended to be processed by a recipient, within the scope of the received message semantics, after any content codings indicated by Content-Encoding are decoded. Content-Type = media-type Media types are defined in [Section 8.3.1](#section-8.3.1). An example of the field is Content-Type: text/html; charset=ISO-8859-4 A sender that generates a message containing content SHOULD generate a Content-Type header field in that message unless the intended media type of the enclosed representation is unknown to the sender. If a Content-Type header field is not present, the recipient MAY either assume a media type of "application/octet-stream" ([[RFC2046], Section 4.5.1](https://datatracker.ietf.org/doc/html/rfc2046#section-4.5.1)) or examine the data to determine its type. In practice, resource owners do not always properly configure their origin server to provide the correct Content-Type for a given representation. Some user agents examine the content and, in certain cases, override the received type (for example, see [[Sniffing](#ref-Sniffing)]). This "MIME sniffing" risks drawing incorrect conclusions about the data, which might expose the user to additional security risks (e.g., "privilege escalation"). Furthermore, distinct media types often share a common data format, differing only in how the data is intended to be processed, which is impossible to distinguish by inspecting the data alone. When sniffing is implemented, implementers are encouraged to provide a means for the user to disable it. Although Content-Type is defined as a singleton field, it is sometimes incorrectly generated multiple times, resulting in a combined field value that appears to be a list. Recipients often attempt to handle this error by using the last syntactically valid member of the list, leading to potential interoperability and security issues if different implementations have different error handling behaviors. #### 8.3.1. Media Type HTTP uses media types [[RFC2046](https://datatracker.ietf.org/doc/html/rfc2046)] in the Content-Type ([Section 8.3](#section-8.3)) and Accept ([Section 12.5.1](#section-12.5.1)) header fields in order to provide open and extensible data typing and type negotiation. Media types define both a data format and various processing models: how to process that data in accordance with the message context. media-type = type "/" subtype parameters type = token subtype = token The type and subtype tokens are case-insensitive. The type/subtype MAY be followed by semicolon-delimited parameters ([Section 5.6.6](#section-5.6.6)) in the form of name/value pairs. The presence or absence of a parameter might be significant to the processing of a media type, depending on its definition within the media type registry. Parameter values might or might not be case-sensitive, depending on the semantics of the parameter name. For example, the following media types are equivalent in describing HTML text data encoded in the UTF-8 character encoding scheme, but the first is preferred for consistency (the "charset" parameter value is defined as being case-insensitive in [[RFC2046], Section 4.1.2](https://datatracker.ietf.org/doc/html/rfc2046#section-4.1.2)): text/html;charset=utf-8 Text/HTML;Charset="utf-8" text/html; charset="utf-8" text/html;charset=UTF-8 Media types ought to be registered with IANA according to the procedures defined in [[BCP13](#ref-BCP13)]. #### 8.3.2. Charset HTTP uses "charset" names to indicate or negotiate the character encoding scheme ([[RFC6365], Section 2](https://datatracker.ietf.org/doc/html/rfc6365#section-2)) of a textual representation. In the fields defined by this document, charset names appear either in parameters (Content-Type), or, for Accept-Encoding, in the form of a plain token. In both cases, charset names are matched case- insensitively. Charset names ought to be registered in the IANA "Character Sets" registry (<<https://www.iana.org/assignments/character-sets>>) according to the procedures defined in [Section 2 of [RFC2978]](https://datatracker.ietf.org/doc/html/rfc2978#section-2). | \*Note:\* In theory, charset names are defined by the "mime- | charset" ABNF rule defined in [Section 2.3 of [RFC2978]](https://datatracker.ietf.org/doc/html/rfc2978#section-2.3) (as | corrected in [[Err1912](#ref-Err1912)]). That rule allows two characters that | are not included in "token" ("{" and "}"), but no charset name | registered at the time of this writing includes braces (see | [[Err5433](#ref-Err5433)]). #### 8.3.3. Multipart Types MIME provides for a number of "multipart" types -- encapsulations of one or more representations within a single message body. All multipart types share a common syntax, as defined in [Section 5.1.1 of [RFC2046]](https://datatracker.ietf.org/doc/html/rfc2046#section-5.1.1), and include a boundary parameter as part of the media type value. The message body is itself a protocol element; a sender MUST generate only CRLF to represent line breaks between body parts. HTTP message framing does not use the multipart boundary as an indicator of message body length, though it might be used by implementations that generate or process the content. For example, the "multipart/form-data" type is often used for carrying form data in a request, as described in [[RFC7578](https://datatracker.ietf.org/doc/html/rfc7578)], and the "multipart/ byteranges" type is defined by this specification for use in some 206 (Partial Content) responses (see [Section 15.3.7](#section-15.3.7)). ### 8.4. Content-Encoding The "Content-Encoding" header field indicates what content codings have been applied to the representation, beyond those inherent in the media type, and thus what decoding mechanisms have to be applied in order to obtain data in the media type referenced by the Content-Type header field. Content-Encoding is primarily used to allow a representation's data to be compressed without losing the identity of its underlying media type. Content-Encoding = #content-coding An example of its use is Content-Encoding: gzip If one or more encodings have been applied to a representation, the sender that applied the encodings MUST generate a Content-Encoding header field that lists the content codings in the order in which they were applied. Note that the coding named "identity" is reserved for its special role in Accept-Encoding and thus SHOULD NOT be included. Additional information about the encoding parameters can be provided by other header fields not defined by this specification. Unlike Transfer-Encoding ([Section 6.1](#section-6.1) of [HTTP/1.1]), the codings listed in Content-Encoding are a characteristic of the representation; the representation is defined in terms of the coded form, and all other metadata about the representation is about the coded form unless otherwise noted in the metadata definition. Typically, the representation is only decoded just prior to rendering or analogous usage. If the media type includes an inherent encoding, such as a data format that is always compressed, then that encoding would not be restated in Content-Encoding even if it happens to be the same algorithm as one of the content codings. Such a content coding would only be listed if, for some bizarre reason, it is applied a second time to form the representation. Likewise, an origin server might choose to publish the same data as multiple representations that differ only in whether the coding is defined as part of Content-Type or Content-Encoding, since some user agents will behave differently in their handling of each response (e.g., open a "Save as ..." dialog instead of automatic decompression and rendering of content). An origin server MAY respond with a status code of 415 (Unsupported Media Type) if a representation in the request message has a content coding that is not acceptable. #### 8.4.1. Content Codings Content coding values indicate an encoding transformation that has been or can be applied to a representation. Content codings are primarily used to allow a representation to be compressed or otherwise usefully transformed without losing the identity of its underlying media type and without loss of information. Frequently, the representation is stored in coded form, transmitted directly, and only decoded by the final recipient. content-coding = token All content codings are case-insensitive and ought to be registered within the "HTTP Content Coding Registry", as described in [Section 16.6](#section-16.6) Content-coding values are used in the Accept-Encoding ([Section 12.5.3](#section-12.5.3)) and Content-Encoding ([Section 8.4](#section-8.4)) header fields. ##### 8.4.1.1. Compress Coding The "compress" coding is an adaptive Lempel-Ziv-Welch (LZW) coding [[Welch](#ref-Welch)] that is commonly produced by the UNIX file compression program "compress". A recipient SHOULD consider "x-compress" to be equivalent to "compress". ##### 8.4.1.2. Deflate Coding The "deflate" coding is a "zlib" data format [[RFC1950](https://datatracker.ietf.org/doc/html/rfc1950)] containing a "deflate" compressed data stream [[RFC1951](https://datatracker.ietf.org/doc/html/rfc1951)] that uses a combination of the Lempel-Ziv (LZ77) compression algorithm and Huffman coding. | \*Note:\* Some non-conformant implementations send the "deflate" | compressed data without the zlib wrapper. ##### 8.4.1.3. Gzip Coding The "gzip" coding is an LZ77 coding with a 32-bit Cyclic Redundancy Check (CRC) that is commonly produced by the gzip file compression program [[RFC1952](https://datatracker.ietf.org/doc/html/rfc1952)]. A recipient SHOULD consider "x-gzip" to be equivalent to "gzip". ### 8.5. Content-Language The "Content-Language" header field describes the natural language(s) of the intended audience for the representation. Note that this might not be equivalent to all the languages used within the representation. Content-Language = #language-tag Language tags are defined in [Section 8.5.1](#section-8.5.1). The primary purpose of Content-Language is to allow a user to identify and differentiate representations according to the users' own preferred language. Thus, if the content is intended only for a Danish-literate audience, the appropriate field is Content-Language: da If no Content-Language is specified, the default is that the content is intended for all language audiences. This might mean that the sender does not consider it to be specific to any natural language, or that the sender does not know for which language it is intended. Multiple languages MAY be listed for content that is intended for multiple audiences. For example, a rendition of the "Treaty of Waitangi", presented simultaneously in the original Maori and English versions, would call for Content-Language: mi, en However, just because multiple languages are present within a representation does not mean that it is intended for multiple linguistic audiences. An example would be a beginner's language primer, such as "A First Lesson in Latin", which is clearly intended to be used by an English-literate audience. In this case, the Content-Language would properly only include "en". Content-Language MAY be applied to any media type -- it is not limited to textual documents. #### 8.5.1. Language Tags A language tag, as defined in [[RFC5646](https://datatracker.ietf.org/doc/html/rfc5646)], identifies a natural language spoken, written, or otherwise conveyed by human beings for communication of information to other human beings. Computer languages are explicitly excluded. HTTP uses language tags within the Accept-Language and Content-Language header fields. Accept-Language uses the broader language-range production defined in [Section 12.5.4](#section-12.5.4), whereas Content-Language uses the language-tag production defined below. language-tag = <Language-Tag, see [[RFC5646], Section 2.1](https://datatracker.ietf.org/doc/html/rfc5646#section-2.1)> A language tag is a sequence of one or more case-insensitive subtags, each separated by a hyphen character ("-", %x2D). In most cases, a language tag consists of a primary language subtag that identifies a broad family of related languages (e.g., "en" = English), which is optionally followed by a series of subtags that refine or narrow that language's range (e.g., "en-CA" = the variety of English as communicated in Canada). Whitespace is not allowed within a language tag. Example tags include: fr, en-US, es-419, az-Arab, x-pig-latin, man-Nkoo-GN See [[RFC5646](https://datatracker.ietf.org/doc/html/rfc5646)] for further information. ### 8.6. Content-Length The "Content-Length" header field indicates the associated representation's data length as a decimal non-negative integer number of octets. When transferring a representation as content, Content- Length refers specifically to the amount of data enclosed so that it can be used to delimit framing (e.g., [Section 6.2](#section-6.2) of [HTTP/1.1]). In other cases, Content-Length indicates the selected representation's current length, which can be used by recipients to estimate transfer time or to compare with previously stored representations. Content-Length = 1\*DIGIT An example is Content-Length: 3495 A user agent SHOULD send Content-Length in a request when the method defines a meaning for enclosed content and it is not sending Transfer-Encoding. For example, a user agent normally sends Content- Length in a POST request even when the value is 0 (indicating empty content). A user agent SHOULD NOT send a Content-Length header field when the request message does not contain content and the method semantics do not anticipate such data. A server MAY send a Content-Length header field in a response to a HEAD request ([Section 9.3.2](#section-9.3.2)); a server MUST NOT send Content-Length in such a response unless its field value equals the decimal number of octets that would have been sent in the content of a response if the same request had used the GET method. A server MAY send a Content-Length header field in a 304 (Not Modified) response to a conditional GET request ([Section 15.4.5](#section-15.4.5)); a server MUST NOT send Content-Length in such a response unless its field value equals the decimal number of octets that would have been sent in the content of a 200 (OK) response to the same request. A server MUST NOT send a Content-Length header field in any response with a status code of 1xx (Informational) or 204 (No Content). A server MUST NOT send a Content-Length header field in any 2xx (Successful) response to a CONNECT request ([Section 9.3.6](#section-9.3.6)). Aside from the cases defined above, in the absence of Transfer- Encoding, an origin server SHOULD send a Content-Length header field when the content size is known prior to sending the complete header section. This will allow downstream recipients to measure transfer progress, know when a received message is complete, and potentially reuse the connection for additional requests. Any Content-Length field value greater than or equal to zero is valid. Since there is no predefined limit to the length of content, a recipient MUST anticipate potentially large decimal numerals and prevent parsing errors due to integer conversion overflows or precision loss due to integer conversion ([Section 17.5](#section-17.5)). Because Content-Length is used for message delimitation in HTTP/1.1, its field value can impact how the message is parsed by downstream recipients even when the immediate connection is not using HTTP/1.1. If the message is forwarded by a downstream intermediary, a Content- Length field value that is inconsistent with the received message framing might cause a security failure due to request smuggling or response splitting. As a result, a sender MUST NOT forward a message with a Content- Length header field value that is known to be incorrect. Likewise, a sender MUST NOT forward a message with a Content-Length header field value that does not match the ABNF above, with one exception: a recipient of a Content-Length header field value consisting of the same decimal value repeated as a comma-separated list (e.g, "Content-Length: 42, 42") MAY either reject the message as invalid or replace that invalid field value with a single instance of the decimal value, since this likely indicates that a duplicate was generated or combined by an upstream message processor. ### 8.7. Content-Location The "Content-Location" header field references a URI that can be used as an identifier for a specific resource corresponding to the representation in this message's content. In other words, if one were to perform a GET request on this URI at the time of this message's generation, then a 200 (OK) response would contain the same representation that is enclosed as content in this message. Content-Location = absolute-URI / partial-URI The field value is either an absolute-URI or a partial-URI. In the latter case ([Section 4](#section-4)), the referenced URI is relative to the target URI ([[URI](#ref-URI)], Section 5). The Content-Location value is not a replacement for the target URI ([Section 7.1](#section-7.1)). It is representation metadata. It has the same syntax and semantics as the header field of the same name defined for MIME body parts in [Section 4 of [RFC2557]](https://datatracker.ietf.org/doc/html/rfc2557#section-4). However, its appearance in an HTTP message has some special implications for HTTP recipients. If Content-Location is included in a 2xx (Successful) response message and its value refers (after conversion to absolute form) to a URI that is the same as the target URI, then the recipient MAY consider the content to be a current representation of that resource at the time indicated by the message origination date. For a GET ([Section 9.3.1](#section-9.3.1)) or HEAD ([Section 9.3.2](#section-9.3.2)) request, this is the same as the default semantics when no Content-Location is provided by the server. For a state-changing request like PUT ([Section 9.3.4](#section-9.3.4)) or POST ([Section 9.3.3](#section-9.3.3)), it implies that the server's response contains the new representation of that resource, thereby distinguishing it from representations that might only report about the action (e.g., "It worked!"). This allows authoring applications to update their local copies without the need for a subsequent GET request. If Content-Location is included in a 2xx (Successful) response message and its field value refers to a URI that differs from the target URI, then the origin server claims that the URI is an identifier for a different resource corresponding to the enclosed representation. Such a claim can only be trusted if both identifiers share the same resource owner, which cannot be programmatically determined via HTTP. \* For a response to a GET or HEAD request, this is an indication that the target URI refers to a resource that is subject to content negotiation and the Content-Location field value is a more specific identifier for the selected representation. \* For a 201 (Created) response to a state-changing method, a Content-Location field value that is identical to the Location field value indicates that this content is a current representation of the newly created resource. \* Otherwise, such a Content-Location indicates that this content is a representation reporting on the requested action's status and that the same report is available (for future access with GET) at the given URI. For example, a purchase transaction made via a POST request might include a receipt document as the content of the 200 (OK) response; the Content-Location field value provides an identifier for retrieving a copy of that same receipt in the future. A user agent that sends Content-Location in a request message is stating that its value refers to where the user agent originally obtained the content of the enclosed representation (prior to any modifications made by that user agent). In other words, the user agent is providing a back link to the source of the original representation. An origin server that receives a Content-Location field in a request message MUST treat the information as transitory request context rather than as metadata to be saved verbatim as part of the representation. An origin server MAY use that context to guide in processing the request or to save it for other uses, such as within source links or versioning metadata. However, an origin server MUST NOT use such context information to alter the request semantics. For example, if a client makes a PUT request on a negotiated resource and the origin server accepts that PUT (without redirection), then the new state of that resource is expected to be consistent with the one representation supplied in that PUT; the Content-Location cannot be used as a form of reverse content selection identifier to update only one of the negotiated representations. If the user agent had wanted the latter semantics, it would have applied the PUT directly to the Content-Location URI. ### 8.8. Validator Fields Resource metadata is referred to as a "validator" if it can be used within a precondition ([Section 13.1](#section-13.1)) to make a conditional request ([Section 13](#section-13)). Validator fields convey a current validator for the selected representation ([Section 3.2](#section-3.2)). In responses to safe requests, validator fields describe the selected representation chosen by the origin server while handling the response. Note that, depending on the method and status code semantics, the selected representation for a given response is not necessarily the same as the representation enclosed as response content. In a successful response to a state-changing request, validator fields describe the new representation that has replaced the prior selected representation as a result of processing the request. For example, an ETag field in a 201 (Created) response communicates the entity tag of the newly created resource's representation, so that the entity tag can be used as a validator in later conditional requests to prevent the "lost update" problem. This specification defines two forms of metadata that are commonly used to observe resource state and test for preconditions: modification dates ([Section 8.8.2](#section-8.8.2)) and opaque entity tags ([Section 8.8.3](#section-8.8.3)). Additional metadata that reflects resource state has been defined by various extensions of HTTP, such as Web Distributed Authoring and Versioning [[WEBDAV](#ref-WEBDAV)], that are beyond the scope of this specification. #### 8.8.1. Weak versus Strong Validators come in two flavors: strong or weak. Weak validators are easy to generate but are far less useful for comparisons. Strong validators are ideal for comparisons but can be very difficult (and occasionally impossible) to generate efficiently. Rather than impose that all forms of resource adhere to the same strength of validator, HTTP exposes the type of validator in use and imposes restrictions on when weak validators can be used as preconditions. A "strong validator" is representation metadata that changes value whenever a change occurs to the representation data that would be observable in the content of a 200 (OK) response to GET. A strong validator might change for reasons other than a change to the representation data, such as when a semantically significant part of the representation metadata is changed (e.g., Content-Type), but it is in the best interests of the origin server to only change the value when it is necessary to invalidate the stored responses held by remote caches and authoring tools. Cache entries might persist for arbitrarily long periods, regardless of expiration times. Thus, a cache might attempt to validate an entry using a validator that it obtained in the distant past. A strong validator is unique across all versions of all representations associated with a particular resource over time. However, there is no implication of uniqueness across representations of different resources (i.e., the same strong validator might be in use for representations of multiple resources at the same time and does not imply that those representations are equivalent). There are a variety of strong validators used in practice. The best are based on strict revision control, wherein each change to a representation always results in a unique node name and revision identifier being assigned before the representation is made accessible to GET. A collision-resistant hash function applied to the representation data is also sufficient if the data is available prior to the response header fields being sent and the digest does not need to be recalculated every time a validation request is received. However, if a resource has distinct representations that differ only in their metadata, such as might occur with content negotiation over media types that happen to share the same data format, then the origin server needs to incorporate additional information in the validator to distinguish those representations. In contrast, a "weak validator" is representation metadata that might not change for every change to the representation data. This weakness might be due to limitations in how the value is calculated (e.g., clock resolution), an inability to ensure uniqueness for all possible representations of the resource, or a desire of the resource owner to group representations by some self-determined set of equivalency rather than unique sequences of data. An origin server SHOULD change a weak entity tag whenever it considers prior representations to be unacceptable as a substitute for the current representation. In other words, a weak entity tag ought to change whenever the origin server wants caches to invalidate old responses. For example, the representation of a weather report that changes in content every second, based on dynamic measurements, might be grouped into sets of equivalent representations (from the origin server's perspective) with the same weak validator in order to allow cached representations to be valid for a reasonable period of time (perhaps adjusted dynamically based on server load or weather quality). Likewise, a representation's modification time, if defined with only one-second resolution, might be a weak validator if it is possible for the representation to be modified twice during a single second and retrieved between those modifications. Likewise, a validator is weak if it is shared by two or more representations of a given resource at the same time, unless those representations have identical representation data. For example, if the origin server sends the same validator for a representation with a gzip content coding applied as it does for a representation with no content coding, then that validator is weak. However, two simultaneous representations might share the same strong validator if they differ only in the representation metadata, such as when two different media types are available for the same representation data. Strong validators are usable for all conditional requests, including cache validation, partial content ranges, and "lost update" avoidance. Weak validators are only usable when the client does not require exact equality with previously obtained representation data, such as when validating a cache entry or limiting a web traversal to recent changes. #### 8.8.2. Last-Modified The "Last-Modified" header field in a response provides a timestamp indicating the date and time at which the origin server believes the selected representation was last modified, as determined at the conclusion of handling the request. Last-Modified = HTTP-date An example of its use is Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT ##### 8.8.2.1. Generation An origin server SHOULD send Last-Modified for any selected representation for which a last modification date can be reasonably and consistently determined, since its use in conditional requests and evaluating cache freshness ([[CACHING](#ref-CACHING)]) can substantially reduce unnecessary transfers and significantly improve service availability and scalability. A representation is typically the sum of many parts behind the resource interface. The last-modified time would usually be the most recent time that any of those parts were changed. How that value is determined for any given resource is an implementation detail beyond the scope of this specification. An origin server SHOULD obtain the Last-Modified value of the representation as close as possible to the time that it generates the Date field value for its response. This allows a recipient to make an accurate assessment of the representation's modification time, especially if the representation changes near the time that the response is generated. An origin server with a clock (as defined in [Section 5.6.7](#section-5.6.7)) MUST NOT generate a Last-Modified date that is later than the server's time of message origination (Date, [Section 6.6.1](#section-6.6.1)). If the last modification time is derived from implementation-specific metadata that evaluates to some time in the future, according to the origin server's clock, then the origin server MUST replace that value with the message origination date. This prevents a future modification date from having an adverse impact on cache validation. An origin server without a clock MUST NOT generate a Last-Modified date for a response unless that date value was assigned to the resource by some other system (presumably one with a clock). ##### 8.8.2.2. Comparison A Last-Modified time, when used as a validator in a request, is implicitly weak unless it is possible to deduce that it is strong, using the following rules: \* The validator is being compared by an origin server to the actual current validator for the representation and, \* That origin server reliably knows that the associated representation did not change twice during the second covered by the presented validator; or \* The validator is about to be used by a client in an If-Modified-Since, If-Unmodified-Since, or If-Range header field, because the client has a cache entry for the associated representation, and \* That cache entry includes a Date value which is at least one second after the Last-Modified value and the client has reason to believe that they were generated by the same clock or that there is enough difference between the Last-Modified and Date values to make clock synchronization issues unlikely; or \* The validator is being compared by an intermediate cache to the validator stored in its cache entry for the representation, and \* That cache entry includes a Date value which is at least one second after the Last-Modified value and the cache has reason to believe that they were generated by the same clock or that there is enough difference between the Last-Modified and Date values to make clock synchronization issues unlikely. This method relies on the fact that if two different responses were sent by the origin server during the same second, but both had the same Last-Modified time, then at least one of those responses would have a Date value equal to its Last-Modified time. #### 8.8.3. ETag The "ETag" field in a response provides the current entity tag for the selected representation, as determined at the conclusion of handling the request. An entity tag is an opaque validator for differentiating between multiple representations of the same resource, regardless of whether those multiple representations are due to resource state changes over time, content negotiation resulting in multiple representations being valid at the same time, or both. An entity tag consists of an opaque quoted string, possibly prefixed by a weakness indicator. ETag = entity-tag entity-tag = [ weak ] opaque-tag weak = %s"W/" opaque-tag = DQUOTE \*etagc DQUOTE etagc = %x21 / %x23-7E / obs-text ; VCHAR except double quotes, plus obs-text | \*Note:\* Previously, opaque-tag was defined to be a quoted- | string ([[RFC2616], Section 3.11](https://datatracker.ietf.org/doc/html/rfc2616#section-3.11)); thus, some recipients might | perform backslash unescaping. Servers therefore ought to avoid | backslash characters in entity tags. An entity tag can be more reliable for validation than a modification date in situations where it is inconvenient to store modification dates, where the one-second resolution of HTTP-date values is not sufficient, or where modification dates are not consistently maintained. Examples: ETag: "xyzzy" ETag: W/"xyzzy" ETag: "" An entity tag can be either a weak or strong validator, with strong being the default. If an origin server provides an entity tag for a representation and the generation of that entity tag does not satisfy all of the characteristics of a strong validator ([Section 8.8.1](#section-8.8.1)), then the origin server MUST mark the entity tag as weak by prefixing its opaque value with "W/" (case-sensitive). A sender MAY send the ETag field in a trailer section (see [Section 6.5](#section-6.5)). However, since trailers are often ignored, it is preferable to send ETag as a header field unless the entity tag is generated while sending the content. ##### 8.8.3.1. Generation The principle behind entity tags is that only the service author knows the implementation of a resource well enough to select the most accurate and efficient validation mechanism for that resource, and that any such mechanism can be mapped to a simple sequence of octets for easy comparison. Since the value is opaque, there is no need for the client to be aware of how each entity tag is constructed. For example, a resource that has implementation-specific versioning applied to all changes might use an internal revision number, perhaps combined with a variance identifier for content negotiation, to accurately differentiate between representations. Other implementations might use a collision-resistant hash of representation content, a combination of various file attributes, or a modification timestamp that has sub-second resolution. An origin server SHOULD send an ETag for any selected representation for which detection of changes can be reasonably and consistently determined, since the entity tag's use in conditional requests and evaluating cache freshness ([[CACHING](#ref-CACHING)]) can substantially reduce unnecessary transfers and significantly improve service availability, scalability, and reliability. ##### 8.8.3.2. Comparison There are two entity tag comparison functions, depending on whether or not the comparison context allows the use of weak validators: "Strong comparison": two entity tags are equivalent if both are not weak and their opaque-tags match character-by-character. "Weak comparison": two entity tags are equivalent if their opaque- tags match character-by-character, regardless of either or both being tagged as "weak". The example below shows the results for a set of entity tag pairs and both the weak and strong comparison function results: +========+========+===================+=================+ | ETag 1 | ETag 2 | Strong Comparison | Weak Comparison | +========+========+===================+=================+ | W/"1" | W/"1" | no match | match | +--------+--------+-------------------+-----------------+ | W/"1" | W/"2" | no match | no match | +--------+--------+-------------------+-----------------+ | W/"1" | "1" | no match | match | +--------+--------+-------------------+-----------------+ | "1" | "1" | match | match | +--------+--------+-------------------+-----------------+ Table 3 ##### 8.8.3.3. Example: Entity Tags Varying on Content-Negotiated Resources Consider a resource that is subject to content negotiation ([Section 12](#section-12)), and where the representations sent in response to a GET request vary based on the Accept-Encoding request header field ([Section 12.5.3](#section-12.5.3)): >> Request: GET /index HTTP/1.1 Host: www.example.com Accept-Encoding: gzip In this case, the response might or might not use the gzip content coding. If it does not, the response might look like: >> Response: HTTP/1.1 200 OK Date: Fri, 26 Mar 2010 00:05:00 GMT ETag: "123-a" Content-Length: 70 Vary: Accept-Encoding Content-Type: text/plain Hello World! Hello World! Hello World! Hello World! Hello World! An alternative representation that does use gzip content coding would be: >> Response: HTTP/1.1 200 OK Date: Fri, 26 Mar 2010 00:05:00 GMT ETag: "123-b" Content-Length: 43 Vary: Accept-Encoding Content-Type: text/plain Content-Encoding: gzip ...binary data | \*Note:\* Content codings are a property of the representation | data, so a strong entity tag for a content-encoded | representation has to be distinct from the entity tag of an | unencoded representation to prevent potential conflicts during | cache updates and range requests. In contrast, transfer | codings ([Section 7](#section-7) of [HTTP/1.1]) apply only during message | transfer and do not result in distinct entity tags. 9. Methods ---------- ### 9.1. Overview The request method token is the primary source of request semantics; it indicates the purpose for which the client has made this request and what is expected by the client as a successful result. The request method's semantics might be further specialized by the semantics of some header fields when present in a request if those additional semantics do not conflict with the method. For example, a client can send conditional request header fields ([Section 13.1](#section-13.1)) to make the requested action conditional on the current state of the target resource. HTTP is designed to be usable as an interface to distributed object systems. The request method invokes an action to be applied to a target resource in much the same way that a remote method invocation can be sent to an identified object. method = token The method token is case-sensitive because it might be used as a gateway to object-based systems with case-sensitive method names. By convention, standardized methods are defined in all-uppercase US- ASCII letters. Unlike distributed objects, the standardized request methods in HTTP are not resource-specific, since uniform interfaces provide for better visibility and reuse in network-based systems [[REST](#ref-REST)]. Once defined, a standardized method ought to have the same semantics when applied to any resource, though each resource determines for itself whether those semantics are implemented or allowed. This specification defines a number of standardized methods that are commonly used in HTTP, as outlined by the following table. +=========+============================================+=========+ | Method | Description | Section | | Name | | | +=========+============================================+=========+ | GET | Transfer a current representation of the | 9.3.1 | | | target resource. | | +---------+--------------------------------------------+---------+ | HEAD | Same as GET, but do not transfer the | 9.3.2 | | | response content. | | +---------+--------------------------------------------+---------+ | POST | Perform resource-specific processing on | 9.3.3 | | | the request content. | | +---------+--------------------------------------------+---------+ | PUT | Replace all current representations of the | 9.3.4 | | | target resource with the request content. | | +---------+--------------------------------------------+---------+ | DELETE | Remove all current representations of the | 9.3.5 | | | target resource. | | +---------+--------------------------------------------+---------+ | CONNECT | Establish a tunnel to the server | 9.3.6 | | | identified by the target resource. | | +---------+--------------------------------------------+---------+ | OPTIONS | Describe the communication options for the | 9.3.7 | | | target resource. | | +---------+--------------------------------------------+---------+ | TRACE | Perform a message loop-back test along the | 9.3.8 | | | path to the target resource. | | +---------+--------------------------------------------+---------+ Table 4 All general-purpose servers MUST support the methods GET and HEAD. All other methods are OPTIONAL. The set of methods allowed by a target resource can be listed in an Allow header field ([Section 10.2.1](#section-10.2.1)). However, the set of allowed methods can change dynamically. An origin server that receives a request method that is unrecognized or not implemented SHOULD respond with the 501 (Not Implemented) status code. An origin server that receives a request method that is recognized and implemented, but not allowed for the target resource, SHOULD respond with the 405 (Method Not Allowed) status code. Additional methods, outside the scope of this specification, have been specified for use in HTTP. All such methods ought to be registered within the "Hypertext Transfer Protocol (HTTP) Method Registry", as described in [Section 16.1](#section-16.1). ### 9.2. Common Method Properties #### 9.2.1. Safe Methods Request methods are considered "safe" if their defined semantics are essentially read-only; i.e., the client does not request, and does not expect, any state change on the origin server as a result of applying a safe method to a target resource. Likewise, reasonable use of a safe method is not expected to cause any harm, loss of property, or unusual burden on the origin server. This definition of safe methods does not prevent an implementation from including behavior that is potentially harmful, that is not entirely read-only, or that causes side effects while invoking a safe method. What is important, however, is that the client did not request that additional behavior and cannot be held accountable for it. For example, most servers append request information to access log files at the completion of every response, regardless of the method, and that is considered safe even though the log storage might become full and cause the server to fail. Likewise, a safe request initiated by selecting an advertisement on the Web will often have the side effect of charging an advertising account. Of the request methods defined by this specification, the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe. The purpose of distinguishing between safe and unsafe methods is to allow automated retrieval processes (spiders) and cache performance optimization (pre-fetching) to work without fear of causing harm. In addition, it allows a user agent to apply appropriate constraints on the automated use of unsafe methods when processing potentially untrusted content. A user agent SHOULD distinguish between safe and unsafe methods when presenting potential actions to a user, such that the user can be made aware of an unsafe action before it is requested. When a resource is constructed such that parameters within the target URI have the effect of selecting an action, it is the resource owner's responsibility to ensure that the action is consistent with the request method semantics. For example, it is common for Web- based content editing software to use actions within query parameters, such as "page?do=delete". If the purpose of such a resource is to perform an unsafe action, then the resource owner MUST disable or disallow that action when it is accessed using a safe request method. Failure to do so will result in unfortunate side effects when automated processes perform a GET on every URI reference for the sake of link maintenance, pre-fetching, building a search index, etc. #### 9.2.2. Idempotent Methods A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent. Like the definition of safe, the idempotent property only applies to what has been requested by the user; a server is free to log each request separately, retain a revision control history, or implement other non-idempotent side effects for each idempotent request. Idempotent methods are distinguished because the request can be repeated automatically if a communication failure occurs before the client is able to read the server's response. For example, if a client sends a PUT request and the underlying connection is closed before any response is received, then the client can establish a new connection and retry the idempotent request. It knows that repeating the request will have the same intended effect, even if the original request succeeded, though the response might differ. A client SHOULD NOT automatically retry a request with a non- idempotent method unless it has some means to know that the request semantics are actually idempotent, regardless of the method, or some means to detect that the original request was never applied. For example, a user agent can repeat a POST request automatically if it knows (through design or configuration) that the request is safe for that resource. Likewise, a user agent designed specifically to operate on a version control repository might be able to recover from partial failure conditions by checking the target resource revision(s) after a failed connection, reverting or fixing any changes that were partially applied, and then automatically retrying the requests that failed. Some clients take a riskier approach and attempt to guess when an automatic retry is possible. For example, a client might automatically retry a POST request if the underlying transport connection closed before any part of a response is received, particularly if an idle persistent connection was used. A proxy MUST NOT automatically retry non-idempotent requests. A client SHOULD NOT automatically retry a failed automatic retry. #### 9.2.3. Methods and Caching For a cache to store and use a response, the associated method needs to explicitly allow caching and to detail under what conditions a response can be used to satisfy subsequent requests; a method definition that does not do so cannot be cached. For additional requirements see [[CACHING](#ref-CACHING)]. This specification defines caching semantics for GET, HEAD, and POST, although the overwhelming majority of cache implementations only support GET and HEAD. ### 9.3. Method Definitions #### 9.3.1. GET The GET method requests transfer of a current selected representation for the target resource. A successful response reflects the quality of "sameness" identified by the target URI (Section 1.2.2 of [[URI](#ref-URI)]). Hence, retrieving identifiable information via HTTP is usually performed by making a GET request on an identifier associated with the potential for providing that information in a 200 (OK) response. GET is the primary mechanism of information retrieval and the focus of almost all performance optimizations. Applications that produce a URI for each important resource can benefit from those optimizations while enabling their reuse by other applications, creating a network effect that promotes further expansion of the Web. It is tempting to think of resource identifiers as remote file system pathnames and of representations as being a copy of the contents of such files. In fact, that is how many resources are implemented (see [Section 17.3](#section-17.3) for related security considerations). However, there are no such limitations in practice. The HTTP interface for a resource is just as likely to be implemented as a tree of content objects, a programmatic view on various database records, or a gateway to other information systems. Even when the URI mapping mechanism is tied to a file system, an origin server might be configured to execute the files with the request as input and send the output as the representation rather than transfer the files directly. Regardless, only the origin server needs to know how each resource identifier corresponds to an implementation and how that implementation manages to select and send a current representation of the target resource. A client can alter the semantics of GET to be a "range request", requesting transfer of only some part(s) of the selected representation, by sending a Range header field in the request ([Section 14.2](#section-14.2)). Although request message framing is independent of the method used, content received in a GET request has no generally defined semantics, cannot alter the meaning or target of the request, and might lead some implementations to reject the request and close the connection because of its potential as a request smuggling attack ([Section 11.2](#section-11.2) of [HTTP/1.1]). A client SHOULD NOT generate content in a GET request unless it is made directly to an origin server that has previously indicated, in or out of band, that such a request has a purpose and will be adequately supported. An origin server SHOULD NOT rely on private agreements to receive content, since participants in HTTP communication are often unaware of intermediaries along the request chain. The response to a GET request is cacheable; a cache MAY use it to satisfy subsequent GET and HEAD requests unless otherwise indicated by the Cache-Control header field (Section 5.2 of [[CACHING](#ref-CACHING)]). When information retrieval is performed with a mechanism that constructs a target URI from user-provided information, such as the query fields of a form using GET, potentially sensitive data might be provided that would not be appropriate for disclosure within a URI (see [Section 17.9](#section-17.9)). In some cases, the data can be filtered or transformed such that it would not reveal such information. In others, particularly when there is no benefit from caching a response, using the POST method ([Section 9.3.3](#section-9.3.3)) instead of GET can transmit such information in the request content rather than within the target URI. #### 9.3.2. HEAD The HEAD method is identical to GET except that the server MUST NOT send content in the response. HEAD is used to obtain metadata about the selected representation without transferring its representation data, often for the sake of testing hypertext links or finding recent modifications. The server SHOULD send the same header fields in response to a HEAD request as it would have sent if the request method had been GET. However, a server MAY omit header fields for which a value is determined only while generating the content. For example, some servers buffer a dynamic response to GET until a minimum amount of data is generated so that they can more efficiently delimit small responses or make late decisions with regard to content selection. Such a response to GET might contain Content-Length and Vary fields, for example, that are not generated within a HEAD response. These minor inconsistencies are considered preferable to generating and discarding the content for a HEAD request, since HEAD is usually requested for the sake of efficiency. Although request message framing is independent of the method used, content received in a HEAD request has no generally defined semantics, cannot alter the meaning or target of the request, and might lead some implementations to reject the request and close the connection because of its potential as a request smuggling attack ([Section 11.2](#section-11.2) of [HTTP/1.1]). A client SHOULD NOT generate content in a HEAD request unless it is made directly to an origin server that has previously indicated, in or out of band, that such a request has a purpose and will be adequately supported. An origin server SHOULD NOT rely on private agreements to receive content, since participants in HTTP communication are often unaware of intermediaries along the request chain. The response to a HEAD request is cacheable; a cache MAY use it to satisfy subsequent HEAD requests unless otherwise indicated by the Cache-Control header field (Section 5.2 of [[CACHING](#ref-CACHING)]). A HEAD response might also affect previously cached responses to GET; see Section 4.3.5 of [[CACHING](#ref-CACHING)]. #### 9.3.3. POST The POST method requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics. For example, POST is used for the following functions (among others): \* Providing a block of data, such as the fields entered into an HTML form, to a data-handling process; \* Posting a message to a bulletin board, newsgroup, mailing list, blog, or similar group of articles; \* Creating a new resource that has yet to be identified by the origin server; and \* Appending data to a resource's existing representation(s). An origin server indicates response semantics by choosing an appropriate status code depending on the result of processing the POST request; almost all of the status codes defined by this specification could be received in a response to POST (the exceptions being 206 (Partial Content), 304 (Not Modified), and 416 (Range Not Satisfiable)). If one or more resources has been created on the origin server as a result of successfully processing a POST request, the origin server SHOULD send a 201 (Created) response containing a Location header field that provides an identifier for the primary resource created ([Section 10.2.2](#section-10.2.2)) and a representation that describes the status of the request while referring to the new resource(s). Responses to POST requests are only cacheable when they include explicit freshness information (see Section 4.2.1 of [[CACHING](#ref-CACHING)]) and a Content-Location header field that has the same value as the POST's target URI ([Section 8.7](#section-8.7)). A cached POST response can be reused to satisfy a later GET or HEAD request. In contrast, a POST request cannot be satisfied by a cached POST response because POST is potentially unsafe; see Section 4 of [[CACHING](#ref-CACHING)]. If the result of processing a POST would be equivalent to a representation of an existing resource, an origin server MAY redirect the user agent to that resource by sending a 303 (See Other) response with the existing resource's identifier in the Location field. This has the benefits of providing the user agent a resource identifier and transferring the representation via a method more amenable to shared caching, though at the cost of an extra request if the user agent does not already have the representation cached. #### 9.3.4. PUT The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message content. A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation being sent in a 200 (OK) response. However, there is no guarantee that such a state change will be observable, since the target resource might be acted upon by other user agents in parallel, or might be subject to dynamic processing by the origin server, before any subsequent GET is received. A successful response only implies that the user agent's intent was achieved at the time of its processing by the origin server. If the target resource does not have a current representation and the PUT successfully creates one, then the origin server MUST inform the user agent by sending a 201 (Created) response. If the target resource does have a current representation and that representation is successfully modified in accordance with the state of the enclosed representation, then the origin server MUST send either a 200 (OK) or a 204 (No Content) response to indicate successful completion of the request. An origin server SHOULD verify that the PUT representation is consistent with its configured constraints for the target resource. For example, if an origin server determines a resource's representation metadata based on the URI, then the origin server needs to ensure that the content received in a successful PUT request is consistent with that metadata. When a PUT representation is inconsistent with the target resource, the origin server SHOULD either make them consistent, by transforming the representation or changing the resource configuration, or respond with an appropriate error message containing sufficient information to explain why the representation is unsuitable. The 409 (Conflict) or 415 (Unsupported Media Type) status codes are suggested, with the latter being specific to constraints on Content-Type values. For example, if the target resource is configured to always have a Content-Type of "text/html" and the representation being PUT has a Content-Type of "image/jpeg", the origin server ought to do one of: a. reconfigure the target resource to reflect the new media type; b. transform the PUT representation to a format consistent with that of the resource before saving it as the new resource state; or, c. reject the request with a 415 (Unsupported Media Type) response indicating that the target resource is limited to "text/html", perhaps including a link to a different resource that would be a suitable target for the new representation. HTTP does not define exactly how a PUT method affects the state of an origin server beyond what can be expressed by the intent of the user agent request and the semantics of the origin server response. It does not define what a resource might be, in any sense of that word, beyond the interface provided via HTTP. It does not define how resource state is "stored", nor how such storage might change as a result of a change in resource state, nor how the origin server translates resource state into representations. Generally speaking, all implementation details behind the resource interface are intentionally hidden by the server. This extends to how header and trailer fields are stored; while common header fields like Content-Type will typically be stored and returned upon subsequent GET requests, header and trailer field handling is specific to the resource that received the request. As a result, an origin server SHOULD ignore unrecognized header and trailer fields received in a PUT request (i.e., not save them as part of the resource state). An origin server MUST NOT send a validator field ([Section 8.8](#section-8.8)), such as an ETag or Last-Modified field, in a successful response to PUT unless the request's representation data was saved without any transformation applied to the content (i.e., the resource's new representation data is identical to the content received in the PUT request) and the validator field value reflects the new representation. This requirement allows a user agent to know when the representation it sent (and retains in memory) is the result of the PUT, and thus it doesn't need to be retrieved again from the origin server. The new validator(s) received in the response can be used for future conditional requests in order to prevent accidental overwrites ([Section 13.1](#section-13.1)). The fundamental difference between the POST and PUT methods is highlighted by the different intent for the enclosed representation. The target resource in a POST request is intended to handle the enclosed representation according to the resource's own semantics, whereas the enclosed representation in a PUT request is defined as replacing the state of the target resource. Hence, the intent of PUT is idempotent and visible to intermediaries, even though the exact effect is only known by the origin server. Proper interpretation of a PUT request presumes that the user agent knows which target resource is desired. A service that selects a proper URI on behalf of the client, after receiving a state-changing request, SHOULD be implemented using the POST method rather than PUT. If the origin server will not make the requested PUT state change to the target resource and instead wishes to have it applied to a different resource, such as when the resource has been moved to a different URI, then the origin server MUST send an appropriate 3xx (Redirection) response; the user agent MAY then make its own decision regarding whether or not to redirect the request. A PUT request applied to the target resource can have side effects on other resources. For example, an article might have a URI for identifying "the current version" (a resource) that is separate from the URIs identifying each particular version (different resources that at one point shared the same state as the current version resource). A successful PUT request on "the current version" URI might therefore create a new version resource in addition to changing the state of the target resource, and might also cause links to be added between the related resources. Some origin servers support use of the Content-Range header field ([Section 14.4](#section-14.4)) as a request modifier to perform a partial PUT, as described in [Section 14.5](#section-14.5). Responses to the PUT method are not cacheable. If a successful PUT request passes through a cache that has one or more stored responses for the target URI, those stored responses will be invalidated (see Section 4.4 of [[CACHING](#ref-CACHING)]). #### 9.3.5. DELETE The DELETE method requests that the origin server remove the association between the target resource and its current functionality. In effect, this method is similar to the "rm" command in UNIX: it expresses a deletion operation on the URI mapping of the origin server rather than an expectation that the previously associated information be deleted. If the target resource has one or more current representations, they might or might not be destroyed by the origin server, and the associated storage might or might not be reclaimed, depending entirely on the nature of the resource and its implementation by the origin server (which are beyond the scope of this specification). Likewise, other implementation aspects of a resource might need to be deactivated or archived as a result of a DELETE, such as database or gateway connections. In general, it is assumed that the origin server will only allow DELETE on resources for which it has a prescribed mechanism for accomplishing the deletion. Relatively few resources allow the DELETE method -- its primary use is for remote authoring environments, where the user has some direction regarding its effect. For example, a resource that was previously created using a PUT request, or identified via the Location header field after a 201 (Created) response to a POST request, might allow a corresponding DELETE request to undo those actions. Similarly, custom user agent implementations that implement an authoring function, such as revision control clients using HTTP for remote operations, might use DELETE based on an assumption that the server's URI space has been crafted to correspond to a version repository. If a DELETE method is successfully applied, the origin server SHOULD send \* a 202 (Accepted) status code if the action will likely succeed but has not yet been enacted, \* a 204 (No Content) status code if the action has been enacted and no further information is to be supplied, or \* a 200 (OK) status code if the action has been enacted and the response message includes a representation describing the status. Although request message framing is independent of the method used, content received in a DELETE request has no generally defined semantics, cannot alter the meaning or target of the request, and might lead some implementations to reject the request and close the connection because of its potential as a request smuggling attack ([Section 11.2](#section-11.2) of [HTTP/1.1]). A client SHOULD NOT generate content in a DELETE request unless it is made directly to an origin server that has previously indicated, in or out of band, that such a request has a purpose and will be adequately supported. An origin server SHOULD NOT rely on private agreements to receive content, since participants in HTTP communication are often unaware of intermediaries along the request chain. Responses to the DELETE method are not cacheable. If a successful DELETE request passes through a cache that has one or more stored responses for the target URI, those stored responses will be invalidated (see Section 4.4 of [[CACHING](#ref-CACHING)]). #### 9.3.6. CONNECT The CONNECT method requests that the recipient establish a tunnel to the destination origin server identified by the request target and, if successful, thereafter restrict its behavior to blind forwarding of data, in both directions, until the tunnel is closed. Tunnels are commonly used to create an end-to-end virtual connection, through one or more proxies, which can then be secured using TLS (Transport Layer Security, [[TLS13](#ref-TLS13)]). CONNECT uses a special form of request target, unique to this method, consisting of only the host and port number of the tunnel destination, separated by a colon. There is no default port; a client MUST send the port number even if the CONNECT request is based on a URI reference that contains an authority component with an elided port ([Section 4.1](#section-4.1)). For example, CONNECT server.example.com:80 HTTP/1.1 Host: server.example.com A server MUST reject a CONNECT request that targets an empty or invalid port number, typically by responding with a 400 (Bad Request) status code. Because CONNECT changes the request/response nature of an HTTP connection, specific HTTP versions might have different ways of mapping its semantics into the protocol's wire format. CONNECT is intended for use in requests to a proxy. The recipient can establish a tunnel either by directly connecting to the server identified by the request target or, if configured to use another proxy, by forwarding the CONNECT request to the next inbound proxy. An origin server MAY accept a CONNECT request, but most origin servers do not implement CONNECT. Any 2xx (Successful) response indicates that the sender (and all inbound proxies) will switch to tunnel mode immediately after the response header section; data received after that header section is from the server identified by the request target. Any response other than a successful response indicates that the tunnel has not yet been formed. A tunnel is closed when a tunnel intermediary detects that either side has closed its connection: the intermediary MUST attempt to send any outstanding data that came from the closed side to the other side, close both connections, and then discard any remaining data left undelivered. Proxy authentication might be used to establish the authority to create a tunnel. For example, CONNECT server.example.com:443 HTTP/1.1 Host: server.example.com:443 Proxy-Authorization: basic aGVsbG86d29ybGQ= There are significant risks in establishing a tunnel to arbitrary servers, particularly when the destination is a well-known or reserved TCP port that is not intended for Web traffic. For example, a CONNECT to "example.com:25" would suggest that the proxy connect to the reserved port for SMTP traffic; if allowed, that could trick the proxy into relaying spam email. Proxies that support CONNECT SHOULD restrict its use to a limited set of known ports or a configurable list of safe request targets. A server MUST NOT send any Transfer-Encoding or Content-Length header fields in a 2xx (Successful) response to CONNECT. A client MUST ignore any Content-Length or Transfer-Encoding header fields received in a successful response to CONNECT. A CONNECT request message does not have content. The interpretation of data sent after the header section of the CONNECT request message is specific to the version of HTTP in use. Responses to the CONNECT method are not cacheable. #### 9.3.7. OPTIONS The OPTIONS method requests information about the communication options available for the target resource, at either the origin server or an intervening intermediary. This method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action. An OPTIONS request with an asterisk ("\*") as the request target ([Section 7.1](#section-7.1)) applies to the server in general rather than to a specific resource. Since a server's communication options typically depend on the resource, the "\*" request is only useful as a "ping" or "no-op" type of method; it does nothing beyond allowing the client to test the capabilities of the server. For example, this can be used to test a proxy for HTTP/1.1 conformance (or lack thereof). If the request target is not an asterisk, the OPTIONS request applies to the options that are available when communicating with the target resource. A server generating a successful response to OPTIONS SHOULD send any header that might indicate optional features implemented by the server and applicable to the target resource (e.g., Allow), including potential extensions not defined by this specification. The response content, if any, might also describe the communication options in a machine or human-readable representation. A standard format for such a representation is not defined by this specification, but might be defined by future extensions to HTTP. A client MAY send a Max-Forwards header field in an OPTIONS request to target a specific recipient in the request chain (see [Section 7.6.2](#section-7.6.2)). A proxy MUST NOT generate a Max-Forwards header field while forwarding a request unless that request was received with a Max-Forwards field. A client that generates an OPTIONS request containing content MUST send a valid Content-Type header field describing the representation media type. Note that this specification does not define any use for such content. Responses to the OPTIONS method are not cacheable. #### 9.3.8. TRACE The TRACE method requests a remote, application-level loop-back of the request message. The final recipient of the request SHOULD reflect the message received, excluding some fields described below, back to the client as the content of a 200 (OK) response. The "message/http" format ([Section 10.1](#section-10.1) of [HTTP/1.1]) is one way to do so. The final recipient is either the origin server or the first server to receive a Max-Forwards value of zero (0) in the request ([Section 7.6.2](#section-7.6.2)). A client MUST NOT generate fields in a TRACE request containing sensitive data that might be disclosed by the response. For example, it would be foolish for a user agent to send stored user credentials ([Section 11](#section-11)) or cookies [[COOKIE](#ref-COOKIE)] in a TRACE request. The final recipient of the request SHOULD exclude any request fields that are likely to contain sensitive data when that recipient generates the response content. TRACE allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information. The value of the Via header field ([Section 7.6.3](#section-7.6.3)) is of particular interest, since it acts as a trace of the request chain. Use of the Max-Forwards header field allows the client to limit the length of the request chain, which is useful for testing a chain of proxies forwarding messages in an infinite loop. A client MUST NOT send content in a TRACE request. Responses to the TRACE method are not cacheable. 10. Message Context ------------------- ### 10.1. Request Context Fields The request header fields below provide additional information about the request context, including information about the user, user agent, and resource behind the request. #### 10.1.1. Expect The "Expect" header field in a request indicates a certain set of behaviors (expectations) that need to be supported by the server in order to properly handle this request. Expect = #expectation expectation = token [ "=" ( token / quoted-string ) parameters ] The Expect field value is case-insensitive. The only expectation defined by this specification is "100-continue" (with no defined parameters). A server that receives an Expect field value containing a member other than 100-continue MAY respond with a 417 (Expectation Failed) status code to indicate that the unexpected expectation cannot be met. A "100-continue" expectation informs recipients that the client is about to send (presumably large) content in this request and wishes to receive a 100 (Continue) interim response if the method, target URI, and header fields are not sufficient to cause an immediate success, redirect, or error response. This allows the client to wait for an indication that it is worthwhile to send the content before actually doing so, which can improve efficiency when the data is huge or when the client anticipates that an error is likely (e.g., when sending a state-changing method, for the first time, without previously verified authentication credentials). For example, a request that begins with PUT /somewhere/fun HTTP/1.1 Host: origin.example.com Content-Type: video/h264 Content-Length: 1234567890987 Expect: 100-continue allows the origin server to immediately respond with an error message, such as 401 (Unauthorized) or 405 (Method Not Allowed), before the client starts filling the pipes with an unnecessary data transfer. Requirements for clients: \* A client MUST NOT generate a 100-continue expectation in a request that does not include content. \* A client that will wait for a 100 (Continue) response before sending the request content MUST send an Expect header field containing a 100-continue expectation. \* A client that sends a 100-continue expectation is not required to wait for any specific length of time; such a client MAY proceed to send the content even if it has not yet received a response. Furthermore, since 100 (Continue) responses cannot be sent through an HTTP/1.0 intermediary, such a client SHOULD NOT wait for an indefinite period before sending the content. \* A client that receives a 417 (Expectation Failed) status code in response to a request containing a 100-continue expectation SHOULD repeat that request without a 100-continue expectation, since the 417 response merely indicates that the response chain does not support expectations (e.g., it passes through an HTTP/1.0 server). Requirements for servers: \* A server that receives a 100-continue expectation in an HTTP/1.0 request MUST ignore that expectation. \* A server MAY omit sending a 100 (Continue) response if it has already received some or all of the content for the corresponding request, or if the framing indicates that there is no content. \* A server that sends a 100 (Continue) response MUST ultimately send a final status code, once it receives and processes the request content, unless the connection is closed prematurely. \* A server that responds with a final status code before reading the entire request content SHOULD indicate whether it intends to close the connection (e.g., see [Section 9.6](#section-9.6) of [HTTP/1.1]) or continue reading the request content. Upon receiving an HTTP/1.1 (or later) request that has a method, target URI, and complete header section that contains a 100-continue expectation and an indication that request content will follow, an origin server MUST send either: \* an immediate response with a final status code, if that status can be determined by examining just the method, target URI, and header fields, or \* an immediate 100 (Continue) response to encourage the client to send the request content. The origin server MUST NOT wait for the content before sending the 100 (Continue) response. Upon receiving an HTTP/1.1 (or later) request that has a method, target URI, and complete header section that contains a 100-continue expectation and indicates a request content will follow, a proxy MUST either: \* send an immediate response with a final status code, if that status can be determined by examining just the method, target URI, and header fields, or \* forward the request toward the origin server by sending a corresponding request-line and header section to the next inbound server. If the proxy believes (from configuration or past interaction) that the next inbound server only supports HTTP/1.0, the proxy MAY generate an immediate 100 (Continue) response to encourage the client to begin sending the content. #### 10.1.2. From The "From" header field contains an Internet email address for a human user who controls the requesting user agent. The address ought to be machine-usable, as defined by "mailbox" in [Section 3.4 of [RFC5322]](https://datatracker.ietf.org/doc/html/rfc5322#section-3.4): From = mailbox mailbox = <mailbox, see [[RFC5322], Section 3.4](https://datatracker.ietf.org/doc/html/rfc5322#section-3.4)> An example is: From: [email protected] The From header field is rarely sent by non-robotic user agents. A user agent SHOULD NOT send a From header field without explicit configuration by the user, since that might conflict with the user's privacy interests or their site's security policy. A robotic user agent SHOULD send a valid From header field so that the person responsible for running the robot can be contacted if problems occur on servers, such as if the robot is sending excessive, unwanted, or invalid requests. A server SHOULD NOT use the From header field for access control or authentication, since its value is expected to be visible to anyone receiving or observing the request and is often recorded within logfiles and error reports without any expectation of privacy. #### 10.1.3. Referer The "Referer" [sic] header field allows the user agent to specify a URI reference for the resource from which the target URI was obtained (i.e., the "referrer", though the field name is misspelled). A user agent MUST NOT include the fragment and userinfo components of the URI reference [[URI](#ref-URI)], if any, when generating the Referer field value. Referer = absolute-URI / partial-URI The field value is either an absolute-URI or a partial-URI. In the latter case ([Section 4](#section-4)), the referenced URI is relative to the target URI ([[URI](#ref-URI)], Section 5). The Referer header field allows servers to generate back-links to other resources for simple analytics, logging, optimized caching, etc. It also allows obsolete or mistyped links to be found for maintenance. Some servers use the Referer header field as a means of denying links from other sites (so-called "deep linking") or restricting cross-site request forgery (CSRF), but not all requests contain it. Example: Referer: http://www.example.org/hypertext/Overview.html If the target URI was obtained from a source that does not have its own URI (e.g., input from the user keyboard, or an entry within the user's bookmarks/favorites), the user agent MUST either exclude the Referer header field or send it with a value of "about:blank". The Referer header field value need not convey the full URI of the referring resource; a user agent MAY truncate parts other than the referring origin. The Referer header field has the potential to reveal information about the request context or browsing history of the user, which is a privacy concern if the referring resource's identifier reveals personal information (such as an account name) or a resource that is supposed to be confidential (such as behind a firewall or internal to a secured service). Most general-purpose user agents do not send the Referer header field when the referring resource is a local "file" or "data" URI. A user agent SHOULD NOT send a Referer header field if the referring resource was accessed with a secure protocol and the request target has an origin differing from that of the referring resource, unless the referring resource explicitly allows Referer to be sent. A user agent MUST NOT send a Referer header field in an unsecured HTTP request if the referring resource was accessed with a secure protocol. See [Section 17.9](#section-17.9) for additional security considerations. Some intermediaries have been known to indiscriminately remove Referer header fields from outgoing requests. This has the unfortunate side effect of interfering with protection against CSRF attacks, which can be far more harmful to their users. Intermediaries and user agent extensions that wish to limit information disclosure in Referer ought to restrict their changes to specific edits, such as replacing internal domain names with pseudonyms or truncating the query and/or path components. An intermediary SHOULD NOT modify or delete the Referer header field when the field value shares the same scheme and host as the target URI. #### 10.1.4. TE The "TE" header field describes capabilities of the client with regard to transfer codings and trailer sections. As described in [Section 6.5](#section-6.5), a TE field with a "trailers" member sent in a request indicates that the client will not discard trailer fields. TE is also used within HTTP/1.1 to advise servers about which transfer codings the client is able to accept in a response. As of publication, only HTTP/1.1 uses transfer codings (see [Section 7](#section-7) of [HTTP/1.1]). The TE field value is a list of members, with each member (aside from "trailers") consisting of a transfer coding name token with an optional weight indicating the client's relative preference for that transfer coding ([Section 12.4.2](#section-12.4.2)) and optional parameters for that transfer coding. TE = #t-codings t-codings = "trailers" / ( transfer-coding [ weight ] ) transfer-coding = token \*( OWS ";" OWS transfer-parameter ) transfer-parameter = token BWS "=" BWS ( token / quoted-string ) A sender of TE MUST also send a "TE" connection option within the Connection header field ([Section 7.6.1](#section-7.6.1)) to inform intermediaries not to forward this field. #### 10.1.5. User-Agent The "User-Agent" header field contains information about the user agent originating the request, which is often used by servers to help identify the scope of reported interoperability problems, to work around or tailor responses to avoid particular user agent limitations, and for analytics regarding browser or operating system use. A user agent SHOULD send a User-Agent header field in each request unless specifically configured not to do so. User-Agent = product \*( RWS ( product / comment ) ) The User-Agent field value consists of one or more product identifiers, each followed by zero or more comments ([Section 5.6.5](#section-5.6.5)), which together identify the user agent software and its significant subproducts. By convention, the product identifiers are listed in decreasing order of their significance for identifying the user agent software. Each product identifier consists of a name and optional version. product = token ["/" product-version] product-version = token A sender SHOULD limit generated product identifiers to what is necessary to identify the product; a sender MUST NOT generate advertising or other nonessential information within the product identifier. A sender SHOULD NOT generate information in product-version that is not a version identifier (i.e., successive versions of the same product name ought to differ only in the product-version portion of the product identifier). Example: User-Agent: CERN-LineMode/2.15 libwww/2.17b3 A user agent SHOULD NOT generate a User-Agent header field containing needlessly fine-grained detail and SHOULD limit the addition of subproducts by third parties. Overly long and detailed User-Agent field values increase request latency and the risk of a user being identified against their wishes ("fingerprinting"). Likewise, implementations are encouraged not to use the product tokens of other implementations in order to declare compatibility with them, as this circumvents the purpose of the field. If a user agent masquerades as a different user agent, recipients can assume that the user intentionally desires to see responses tailored for that identified user agent, even if they might not work as well for the actual user agent being used. ### 10.2. Response Context Fields The response header fields below provide additional information about the response, beyond what is implied by the status code, including information about the server, about the target resource, or about related resources. #### 10.2.1. Allow The "Allow" header field lists the set of methods advertised as supported by the target resource. The purpose of this field is strictly to inform the recipient of valid request methods associated with the resource. Allow = #method Example of use: Allow: GET, HEAD, PUT The actual set of allowed methods is defined by the origin server at the time of each request. An origin server MUST generate an Allow header field in a 405 (Method Not Allowed) response and MAY do so in any other response. An empty Allow field value indicates that the resource allows no methods, which might occur in a 405 response if the resource has been temporarily disabled by configuration. A proxy MUST NOT modify the Allow header field -- it does not need to understand all of the indicated methods in order to handle them according to the generic message handling rules. #### 10.2.2. Location The "Location" header field is used in some responses to refer to a specific resource in relation to the response. The type of relationship is defined by the combination of request method and status code semantics. Location = URI-reference The field value consists of a single URI-reference. When it has the form of a relative reference ([[URI](#ref-URI)], Section 4.2), the final value is computed by resolving it against the target URI ([[URI](#ref-URI)], Section 5). For 201 (Created) responses, the Location value refers to the primary resource created by the request. For 3xx (Redirection) responses, the Location value refers to the preferred target resource for automatically redirecting the request. If the Location value provided in a 3xx (Redirection) response does not have a fragment component, a user agent MUST process the redirection as if the value inherits the fragment component of the URI reference used to generate the target URI (i.e., the redirection inherits the original reference's fragment, if any). For example, a GET request generated for the URI reference "http://www.example.org/~tim" might result in a 303 (See Other) response containing the header field: Location: /People.html#tim which suggests that the user agent redirect to "http://www.example.org/People.html#tim" Likewise, a GET request generated for the URI reference "http://www.example.org/index.html#larry" might result in a 301 (Moved Permanently) response containing the header field: Location: http://www.example.net/index.html which suggests that the user agent redirect to "http://www.example.net/index.html#larry", preserving the original fragment identifier. There are circumstances in which a fragment identifier in a Location value would not be appropriate. For example, the Location header field in a 201 (Created) response is supposed to provide a URI that is specific to the created resource. | \*Note:\* Some recipients attempt to recover from Location header | fields that are not valid URI references. This specification | does not mandate or define such processing, but does allow it | for the sake of robustness. A Location field value cannot | allow a list of members because the comma list separator is a | valid data character within a URI-reference. If an invalid | message is sent with multiple Location field lines, a recipient | along the path might combine those field lines into one value. | Recovery of a valid Location field value from that situation is | difficult and not interoperable across implementations. | \*Note:\* The Content-Location header field ([Section 8.7](#section-8.7)) differs | from Location in that the Content-Location refers to the most | specific resource corresponding to the enclosed representation. | It is therefore possible for a response to contain both the | Location and Content-Location header fields. #### 10.2.3. Retry-After Servers send the "Retry-After" header field to indicate how long the user agent ought to wait before making a follow-up request. When sent with a 503 (Service Unavailable) response, Retry-After indicates how long the service is expected to be unavailable to the client. When sent with any 3xx (Redirection) response, Retry-After indicates the minimum time that the user agent is asked to wait before issuing the redirected request. The Retry-After field value can be either an HTTP-date or a number of seconds to delay after receiving the response. Retry-After = HTTP-date / delay-seconds A delay-seconds value is a non-negative decimal integer, representing time in seconds. delay-seconds = 1\*DIGIT Two examples of its use are Retry-After: Fri, 31 Dec 1999 23:59:59 GMT Retry-After: 120 In the latter example, the delay is 2 minutes. #### 10.2.4. Server The "Server" header field contains information about the software used by the origin server to handle the request, which is often used by clients to help identify the scope of reported interoperability problems, to work around or tailor requests to avoid particular server limitations, and for analytics regarding server or operating system use. An origin server MAY generate a Server header field in its responses. Server = product \*( RWS ( product / comment ) ) The Server header field value consists of one or more product identifiers, each followed by zero or more comments ([Section 5.6.5](#section-5.6.5)), which together identify the origin server software and its significant subproducts. By convention, the product identifiers are listed in decreasing order of their significance for identifying the origin server software. Each product identifier consists of a name and optional version, as defined in [Section 10.1.5](#section-10.1.5). Example: Server: CERN/3.0 libwww/2.17 An origin server SHOULD NOT generate a Server header field containing needlessly fine-grained detail and SHOULD limit the addition of subproducts by third parties. Overly long and detailed Server field values increase response latency and potentially reveal internal implementation details that might make it (slightly) easier for attackers to find and exploit known security holes. 11. HTTP Authentication ----------------------- ### 11.1. Authentication Scheme HTTP provides a general framework for access control and authentication, via an extensible set of challenge-response authentication schemes, which can be used by a server to challenge a client request and by a client to provide authentication information. It uses a case-insensitive token to identify the authentication scheme: auth-scheme = token Aside from the general framework, this document does not specify any authentication schemes. New and existing authentication schemes are specified independently and ought to be registered within the "Hypertext Transfer Protocol (HTTP) Authentication Scheme Registry". For example, the "basic" and "digest" authentication schemes are defined by [[RFC7617](https://datatracker.ietf.org/doc/html/rfc7617)] and [[RFC7616](https://datatracker.ietf.org/doc/html/rfc7616)], respectively. ### 11.2. Authentication Parameters The authentication scheme is followed by additional information necessary for achieving authentication via that scheme as either a comma-separated list of parameters or a single sequence of characters capable of holding base64-encoded information. token68 = 1\*( ALPHA / DIGIT / "-" / "." / "\_" / "~" / "+" / "/" ) \*"=" The token68 syntax allows the 66 unreserved URI characters ([[URI](#ref-URI)]), plus a few others, so that it can hold a base64, base64url (URL and filename safe alphabet), base32, or base16 (hex) encoding, with or without padding, but excluding whitespace ([[RFC4648](https://datatracker.ietf.org/doc/html/rfc4648)]). Authentication parameters are name/value pairs, where the name token is matched case-insensitively and each parameter name MUST only occur once per challenge. auth-param = token BWS "=" BWS ( token / quoted-string ) Parameter values can be expressed either as "token" or as "quoted- string" ([Section 5.6](#section-5.6)). Authentication scheme definitions need to accept both notations, both for senders and recipients, to allow recipients to use generic parsing components regardless of the authentication scheme. For backwards compatibility, authentication scheme definitions can restrict the format for senders to one of the two variants. This can be important when it is known that deployed implementations will fail when encountering one of the two formats. ### 11.3. Challenge and Response A 401 (Unauthorized) response message is used by an origin server to challenge the authorization of a user agent, including a WWW-Authenticate header field containing at least one challenge applicable to the requested resource. A 407 (Proxy Authentication Required) response message is used by a proxy to challenge the authorization of a client, including a Proxy-Authenticate header field containing at least one challenge applicable to the proxy for the requested resource. challenge = auth-scheme [ 1\*SP ( token68 / #auth-param ) ] | \*Note:\* Many clients fail to parse a challenge that contains an | unknown scheme. A workaround for this problem is to list well- | supported schemes (such as "basic") first. A user agent that wishes to authenticate itself with an origin server -- usually, but not necessarily, after receiving a 401 (Unauthorized) -- can do so by including an Authorization header field with the request. A client that wishes to authenticate itself with a proxy -- usually, but not necessarily, after receiving a 407 (Proxy Authentication Required) -- can do so by including a Proxy-Authorization header field with the request. ### 11.4. Credentials Both the Authorization field value and the Proxy-Authorization field value contain the client's credentials for the realm of the resource being requested, based upon a challenge received in a response (possibly at some point in the past). When creating their values, the user agent ought to do so by selecting the challenge with what it considers to be the most secure auth-scheme that it understands, obtaining credentials from the user as appropriate. Transmission of credentials within header field values implies significant security considerations regarding the confidentiality of the underlying connection, as described in [Section 17.16.1](#section-17.16.1). credentials = auth-scheme [ 1\*SP ( token68 / #auth-param ) ] Upon receipt of a request for a protected resource that omits credentials, contains invalid credentials (e.g., a bad password) or partial credentials (e.g., when the authentication scheme requires more than one round trip), an origin server SHOULD send a 401 (Unauthorized) response that contains a WWW-Authenticate header field with at least one (possibly new) challenge applicable to the requested resource. Likewise, upon receipt of a request that omits proxy credentials or contains invalid or partial proxy credentials, a proxy that requires authentication SHOULD generate a 407 (Proxy Authentication Required) response that contains a Proxy-Authenticate header field with at least one (possibly new) challenge applicable to the proxy. A server that receives valid credentials that are not adequate to gain access ought to respond with the 403 (Forbidden) status code ([Section 15.5.4](#section-15.5.4)). HTTP does not restrict applications to this simple challenge-response framework for access authentication. Additional mechanisms can be used, such as authentication at the transport level or via message encapsulation, and with additional header fields specifying authentication information. However, such additional mechanisms are not defined by this specification. Note that various custom mechanisms for user authentication use the Set-Cookie and Cookie header fields, defined in [[COOKIE](#ref-COOKIE)], for passing tokens related to authentication. ### 11.5. Establishing a Protection Space (Realm) The "realm" authentication parameter is reserved for use by authentication schemes that wish to indicate a scope of protection. A "protection space" is defined by the origin (see [Section 4.3.1](#section-4.3.1)) of the server being accessed, in combination with the realm value if present. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, that can have additional semantics specific to the authentication scheme. Note that a response can have multiple challenges with the same auth- scheme but with different realms. The protection space determines the domain over which credentials can be automatically applied. If a prior request has been authorized, the user agent MAY reuse the same credentials for all other requests within that protection space for a period of time determined by the authentication scheme, parameters, and/or user preferences (such as a configurable inactivity timeout). The extent of a protection space, and therefore the requests to which credentials might be automatically applied, is not necessarily known to clients without additional information. An authentication scheme might define parameters that describe the extent of a protection space. Unless specifically allowed by the authentication scheme, a single protection space cannot extend outside the scope of its server. For historical reasons, a sender MUST only generate the quoted-string syntax. Recipients might have to support both token and quoted- string syntax for maximum interoperability with existing clients that have been accepting both notations for a long time. ### 11.6. Authenticating Users to Origin Servers #### 11.6.1. WWW-Authenticate The "WWW-Authenticate" response header field indicates the authentication scheme(s) and parameters applicable to the target resource. WWW-Authenticate = #challenge A server generating a 401 (Unauthorized) response MUST send a WWW- Authenticate header field containing at least one challenge. A server MAY generate a WWW-Authenticate header field in other response messages to indicate that supplying credentials (or different credentials) might affect the response. A proxy forwarding a response MUST NOT modify any WWW-Authenticate header fields in that response. User agents are advised to take special care in parsing the field value, as it might contain more than one challenge, and each challenge can contain a comma-separated list of authentication parameters. Furthermore, the header field itself can occur multiple times. For instance: WWW-Authenticate: Basic realm="simple", Newauth realm="apps", type=1, title="Login to \"apps\"" This header field contains two challenges, one for the "Basic" scheme with a realm value of "simple" and another for the "Newauth" scheme with a realm value of "apps". It also contains two additional parameters, "type" and "title". Some user agents do not recognize this form, however. As a result, sending a WWW-Authenticate field value with more than one member on the same field line might not be interoperable. | \*Note:\* The challenge grammar production uses the list syntax | as well. Therefore, a sequence of comma, whitespace, and comma | can be considered either as applying to the preceding | challenge, or to be an empty entry in the list of challenges. | In practice, this ambiguity does not affect the semantics of | the header field value and thus is harmless. #### 11.6.2. Authorization The "Authorization" header field allows a user agent to authenticate itself with an origin server -- usually, but not necessarily, after receiving a 401 (Unauthorized) response. Its value consists of credentials containing the authentication information of the user agent for the realm of the resource being requested. Authorization = credentials If a request is authenticated and a realm specified, the same credentials are presumed to be valid for all other requests within this realm (assuming that the authentication scheme itself does not require otherwise, such as credentials that vary according to a challenge value or using synchronized clocks). A proxy forwarding a request MUST NOT modify any Authorization header fields in that request. See Section 3.5 of [[CACHING](#ref-CACHING)] for details of and requirements pertaining to handling of the Authorization header field by HTTP caches. #### 11.6.3. Authentication-Info HTTP authentication schemes can use the "Authentication-Info" response field to communicate information after the client's authentication credentials have been accepted. This information can include a finalization message from the server (e.g., it can contain the server authentication). The field value is a list of parameters (name/value pairs), using the "auth-param" syntax defined in [Section 11.3](#section-11.3). This specification only describes the generic format; authentication schemes using Authentication-Info will define the individual parameters. The "Digest" Authentication Scheme, for instance, defines multiple parameters in [Section 3.5 of [RFC7616]](https://datatracker.ietf.org/doc/html/rfc7616#section-3.5). Authentication-Info = #auth-param The Authentication-Info field can be used in any HTTP response, independently of request method and status code. Its semantics are defined by the authentication scheme indicated by the Authorization header field ([Section 11.6.2](#section-11.6.2)) of the corresponding request. A proxy forwarding a response is not allowed to modify the field value in any way. Authentication-Info can be sent as a trailer field ([Section 6.5](#section-6.5)) when the authentication scheme explicitly allows this. ### 11.7. Authenticating Clients to Proxies #### 11.7.1. Proxy-Authenticate The "Proxy-Authenticate" header field consists of at least one challenge that indicates the authentication scheme(s) and parameters applicable to the proxy for this request. A proxy MUST send at least one Proxy-Authenticate header field in each 407 (Proxy Authentication Required) response that it generates. Proxy-Authenticate = #challenge Unlike WWW-Authenticate, the Proxy-Authenticate header field applies only to the next outbound client on the response chain. This is because only the client that chose a given proxy is likely to have the credentials necessary for authentication. However, when multiple proxies are used within the same administrative domain, such as office and regional caching proxies within a large corporate network, it is common for credentials to be generated by the user agent and passed through the hierarchy until consumed. Hence, in such a configuration, it will appear as if Proxy-Authenticate is being forwarded because each proxy will send the same challenge set. Note that the parsing considerations for WWW-Authenticate apply to this header field as well; see [Section 11.6.1](#section-11.6.1) for details. #### 11.7.2. Proxy-Authorization The "Proxy-Authorization" header field allows the client to identify itself (or its user) to a proxy that requires authentication. Its value consists of credentials containing the authentication information of the client for the proxy and/or realm of the resource being requested. Proxy-Authorization = credentials Unlike Authorization, the Proxy-Authorization header field applies only to the next inbound proxy that demanded authentication using the Proxy-Authenticate header field. When multiple proxies are used in a chain, the Proxy-Authorization header field is consumed by the first inbound proxy that was expecting to receive credentials. A proxy MAY relay the credentials from the client request to the next proxy if that is the mechanism by which the proxies cooperatively authenticate a given request. #### 11.7.3. Proxy-Authentication-Info The "Proxy-Authentication-Info" response header field is equivalent to Authentication-Info, except that it applies to proxy authentication ([Section 11.3](#section-11.3)) and its semantics are defined by the authentication scheme indicated by the Proxy-Authorization header field ([Section 11.7.2](#section-11.7.2)) of the corresponding request: Proxy-Authentication-Info = #auth-param However, unlike Authentication-Info, the Proxy-Authentication-Info header field applies only to the next outbound client on the response chain. This is because only the client that chose a given proxy is likely to have the credentials necessary for authentication. However, when multiple proxies are used within the same administrative domain, such as office and regional caching proxies within a large corporate network, it is common for credentials to be generated by the user agent and passed through the hierarchy until consumed. Hence, in such a configuration, it will appear as if Proxy-Authentication-Info is being forwarded because each proxy will send the same field value. Proxy-Authentication-Info can be sent as a trailer field ([Section 6.5](#section-6.5)) when the authentication scheme explicitly allows this. 12. Content Negotiation ----------------------- When responses convey content, whether indicating a success or an error, the origin server often has different ways of representing that information; for example, in different formats, languages, or encodings. Likewise, different users or user agents might have differing capabilities, characteristics, or preferences that could influence which representation, among those available, would be best to deliver. For this reason, HTTP provides mechanisms for content negotiation. This specification defines three patterns of content negotiation that can be made visible within the protocol: "proactive" negotiation, where the server selects the representation based upon the user agent's stated preferences; "reactive" negotiation, where the server provides a list of representations for the user agent to choose from; and "request content" negotiation, where the user agent selects the representation for a future request based upon the server's stated preferences in past responses. Other patterns of content negotiation include "conditional content", where the representation consists of multiple parts that are selectively rendered based on user agent parameters, "active content", where the representation contains a script that makes additional (more specific) requests based on the user agent characteristics, and "Transparent Content Negotiation" ([[RFC2295](https://datatracker.ietf.org/doc/html/rfc2295)]), where content selection is performed by an intermediary. These patterns are not mutually exclusive, and each has trade-offs in applicability and practicality. Note that, in all cases, HTTP is not aware of the resource semantics. The consistency with which an origin server responds to requests, over time and over the varying dimensions of content negotiation, and thus the "sameness" of a resource's observed representations over time, is determined entirely by whatever entity or algorithm selects or generates those responses. ### 12.1. Proactive Negotiation When content negotiation preferences are sent by the user agent in a request to encourage an algorithm located at the server to select the preferred representation, it is called "proactive negotiation" (a.k.a., "server-driven negotiation"). Selection is based on the available representations for a response (the dimensions over which it might vary, such as language, content coding, etc.) compared to various information supplied in the request, including both the explicit negotiation header fields below and implicit characteristics, such as the client's network address or parts of the User-Agent field. Proactive negotiation is advantageous when the algorithm for selecting from among the available representations is difficult to describe to a user agent, or when the server desires to send its "best guess" to the user agent along with the first response (when that "best guess" is good enough for the user, this avoids the round- trip delay of a subsequent request). In order to improve the server's guess, a user agent MAY send request header fields that describe its preferences. Proactive negotiation has serious disadvantages: \* It is impossible for the server to accurately determine what might be "best" for any given user, since that would require complete knowledge of both the capabilities of the user agent and the intended use for the response (e.g., does the user want to view it on screen or print it on paper?); \* Having the user agent describe its capabilities in every request can be both very inefficient (given that only a small percentage of responses have multiple representations) and a potential risk to the user's privacy; \* It complicates the implementation of an origin server and the algorithms for generating responses to a request; and, \* It limits the reusability of responses for shared caching. A user agent cannot rely on proactive negotiation preferences being consistently honored, since the origin server might not implement proactive negotiation for the requested resource or might decide that sending a response that doesn't conform to the user agent's preferences is better than sending a 406 (Not Acceptable) response. A Vary header field ([Section 12.5.5](#section-12.5.5)) is often sent in a response subject to proactive negotiation to indicate what parts of the request information were used in the selection algorithm. The request header fields Accept, Accept-Charset, Accept-Encoding, and Accept-Language are defined below for a user agent to engage in proactive negotiation of the response content. The preferences sent in these fields apply to any content in the response, including representations of the target resource, representations of error or processing status, and potentially even the miscellaneous text strings that might appear within the protocol. ### 12.2. Reactive Negotiation With "reactive negotiation" (a.k.a., "agent-driven negotiation"), selection of content (regardless of the status code) is performed by the user agent after receiving an initial response. The mechanism for reactive negotiation might be as simple as a list of references to alternative representations. If the user agent is not satisfied by the initial response content, it can perform a GET request on one or more of the alternative resources to obtain a different representation. Selection of such alternatives might be performed automatically (by the user agent) or manually (e.g., by the user selecting from a hypertext menu). A server might choose not to send an initial representation, other than the list of alternatives, and thereby indicate that reactive negotiation by the user agent is preferred. For example, the alternatives listed in responses with the 300 (Multiple Choices) and 406 (Not Acceptable) status codes include information about available representations so that the user or user agent can react by making a selection. Reactive negotiation is advantageous when the response would vary over commonly used dimensions (such as type, language, or encoding), when the origin server is unable to determine a user agent's capabilities from examining the request, and generally when public caches are used to distribute server load and reduce network usage. Reactive negotiation suffers from the disadvantages of transmitting a list of alternatives to the user agent, which degrades user-perceived latency if transmitted in the header section, and needing a second request to obtain an alternate representation. Furthermore, this specification does not define a mechanism for supporting automatic selection, though it does not prevent such a mechanism from being developed. ### 12.3. Request Content Negotiation When content negotiation preferences are sent in a server's response, the listed preferences are called "request content negotiation" because they intend to influence selection of an appropriate content for subsequent requests to that resource. For example, the Accept ([Section 12.5.1](#section-12.5.1)) and Accept-Encoding ([Section 12.5.3](#section-12.5.3)) header fields can be sent in a response to indicate preferred media types and content codings for subsequent requests to that resource. Similarly, [Section 3.1 of [RFC5789]](https://datatracker.ietf.org/doc/html/rfc5789#section-3.1) defines the "Accept-Patch" response header field, which allows discovery of which content types are accepted in PATCH requests. ### 12.4. Content Negotiation Field Features #### 12.4.1. Absence For each of the content negotiation fields, a request that does not contain the field implies that the sender has no preference on that dimension of negotiation. If a content negotiation header field is present in a request and none of the available representations for the response can be considered acceptable according to it, the origin server can either honor the header field by sending a 406 (Not Acceptable) response or disregard the header field by treating the response as if it is not subject to content negotiation for that request header field. This does not imply, however, that the client will be able to use the representation. | \*Note:\* A user agent sending these header fields makes it | easier for a server to identify an individual by virtue of the | user agent's request characteristics ([Section 17.13](#section-17.13)). #### 12.4.2. Quality Values The content negotiation fields defined by this specification use a common parameter, named "q" (case-insensitive), to assign a relative "weight" to the preference for that associated kind of content. This weight is referred to as a "quality value" (or "qvalue") because the same parameter name is often used within server configurations to assign a weight to the relative quality of the various representations that can be selected for a resource. The weight is normalized to a real number in the range 0 through 1, where 0.001 is the least preferred and 1 is the most preferred; a value of 0 means "not acceptable". If no "q" parameter is present, the default weight is 1. weight = OWS ";" OWS "q=" qvalue qvalue = ( "0" [ "." 0\*3DIGIT ] ) / ( "1" [ "." 0\*3("0") ] ) A sender of qvalue MUST NOT generate more than three digits after the decimal point. User configuration of these values ought to be limited in the same fashion. #### 12.4.3. Wildcard Values Most of these header fields, where indicated, define a wildcard value ("\*") to select unspecified values. If no wildcard is present, values that are not explicitly mentioned in the field are considered unacceptable. Within Vary, the wildcard value means that the variance is unlimited. | \*Note:\* In practice, using wildcards in content negotiation has | limited practical value because it is seldom useful to say, for | example, "I prefer image/\* more or less than (some other | specific value)". By sending Accept: \*/\*;q=0, clients can | explicitly request a 406 (Not Acceptable) response if a more | preferred format is not available, but they still need to be | able to handle a different response since the server is allowed | to ignore their preference. ### 12.5. Content Negotiation Fields #### 12.5.1. Accept The "Accept" header field can be used by user agents to specify their preferences regarding response media types. For example, Accept header fields can be used to indicate that the request is specifically limited to a small set of desired types, as in the case of a request for an in-line image. When sent by a server in a response, Accept provides information about which content types are preferred in the content of a subsequent request to the same resource. Accept = #( media-range [ weight ] ) media-range = ( "\*/\*" / ( type "/" "\*" ) / ( type "/" subtype ) ) parameters The asterisk "\*" character is used to group media types into ranges, with "\*/\*" indicating all media types and "type/\*" indicating all subtypes of that type. The media-range can include media type parameters that are applicable to that range. Each media-range might be followed by optional applicable media type parameters (e.g., charset), followed by an optional "q" parameter for indicating a relative weight ([Section 12.4.2](#section-12.4.2)). Previous specifications allowed additional extension parameters to appear after the weight parameter. The accept extension grammar (accept-params, accept-ext) has been removed because it had a complicated definition, was not being used in practice, and is more easily deployed through new header fields. Senders using weights SHOULD send "q" last (after all media-range parameters). Recipients SHOULD process any parameter named "q" as weight, regardless of parameter ordering. | \*Note:\* Use of the "q" parameter name to control content | negotiation would interfere with any media type parameter | having the same name. Hence, the media type registry disallows | parameters named "q". The example Accept: audio/\*; q=0.2, audio/basic is interpreted as "I prefer audio/basic, but send me any audio type if it is the best available after an 80% markdown in quality". A more elaborate example is Accept: text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c Verbally, this would be interpreted as "text/html and text/x-c are the equally preferred media types, but if they do not exist, then send the text/x-dvi representation, and if that does not exist, send the text/plain representation". Media ranges can be overridden by more specific media ranges or specific media types. If more than one media range applies to a given type, the most specific reference has precedence. For example, Accept: text/\*, text/plain, text/plain;format=flowed, \*/\* have the following precedence: 1. text/plain;format=flowed 2. text/plain 3. text/\* 4. \*/\* The media type quality factor associated with a given type is determined by finding the media range with the highest precedence that matches the type. For example, Accept: text/\*;q=0.3, text/plain;q=0.7, text/plain;format=flowed, text/plain;format=fixed;q=0.4, \*/\*;q=0.5 would cause the following values to be associated: +==========================+===============+ | Media Type | Quality Value | +==========================+===============+ | text/plain;format=flowed | 1 | +--------------------------+---------------+ | text/plain | 0.7 | +--------------------------+---------------+ | text/html | 0.3 | +--------------------------+---------------+ | image/jpeg | 0.5 | +--------------------------+---------------+ | text/plain;format=fixed | 0.4 | +--------------------------+---------------+ | text/html;level=3 | 0.7 | +--------------------------+---------------+ Table 5 | \*Note:\* A user agent might be provided with a default set of | quality values for certain media ranges. However, unless the | user agent is a closed system that cannot interact with other | rendering agents, this default set ought to be configurable by | the user. #### 12.5.2. Accept-Charset The "Accept-Charset" header field can be sent by a user agent to indicate its preferences for charsets in textual response content. For example, this field allows user agents capable of understanding more comprehensive or special-purpose charsets to signal that capability to an origin server that is capable of representing information in those charsets. Accept-Charset = #( ( token / "\*" ) [ weight ] ) Charset names are defined in [Section 8.3.2](#section-8.3.2). A user agent MAY associate a quality value with each charset to indicate the user's relative preference for that charset, as defined in [Section 12.4.2](#section-12.4.2). An example is Accept-Charset: iso-8859-5, unicode-1-1;q=0.8 The special value "\*", if present in the Accept-Charset header field, matches every charset that is not mentioned elsewhere in the field. | \*Note:\* Accept-Charset is deprecated because UTF-8 has become | nearly ubiquitous and sending a detailed list of user-preferred | charsets wastes bandwidth, increases latency, and makes passive | fingerprinting far too easy ([Section 17.13](#section-17.13)). Most general- | purpose user agents do not send Accept-Charset unless | specifically configured to do so. #### 12.5.3. Accept-Encoding The "Accept-Encoding" header field can be used to indicate preferences regarding the use of content codings ([Section 8.4.1](#section-8.4.1)). When sent by a user agent in a request, Accept-Encoding indicates the content codings acceptable in a response. When sent by a server in a response, Accept-Encoding provides information about which content codings are preferred in the content of a subsequent request to the same resource. An "identity" token is used as a synonym for "no encoding" in order to communicate when no encoding is preferred. Accept-Encoding = #( codings [ weight ] ) codings = content-coding / "identity" / "\*" Each codings value MAY be given an associated quality value (weight) representing the preference for that encoding, as defined in [Section 12.4.2](#section-12.4.2). The asterisk "\*" symbol in an Accept-Encoding field matches any available content coding not explicitly listed in the field. Examples: Accept-Encoding: compress, gzip Accept-Encoding: Accept-Encoding: \* Accept-Encoding: compress;q=0.5, gzip;q=1.0 Accept-Encoding: gzip;q=1.0, identity; q=0.5, \*;q=0 A server tests whether a content coding for a given representation is acceptable using these rules: 1. If no Accept-Encoding header field is in the request, any content coding is considered acceptable by the user agent. 2. If the representation has no content coding, then it is acceptable by default unless specifically excluded by the Accept- Encoding header field stating either "identity;q=0" or "\*;q=0" without a more specific entry for "identity". 3. If the representation's content coding is one of the content codings listed in the Accept-Encoding field value, then it is acceptable unless it is accompanied by a qvalue of 0. (As defined in [Section 12.4.2](#section-12.4.2), a qvalue of 0 means "not acceptable".) A representation could be encoded with multiple content codings. However, most content codings are alternative ways to accomplish the same purpose (e.g., data compression). When selecting between multiple content codings that have the same purpose, the acceptable content coding with the highest non-zero qvalue is preferred. An Accept-Encoding header field with a field value that is empty implies that the user agent does not want any content coding in response. If a non-empty Accept-Encoding header field is present in a request and none of the available representations for the response have a content coding that is listed as acceptable, the origin server SHOULD send a response without any content coding unless the identity coding is indicated as unacceptable. When the Accept-Encoding header field is present in a response, it indicates what content codings the resource was willing to accept in the associated request. The field value is evaluated the same way as in a request. Note that this information is specific to the associated request; the set of supported encodings might be different for other resources on the same server and could change over time or depend on other aspects of the request (such as the request method). Servers that fail a request due to an unsupported content coding ought to respond with a 415 (Unsupported Media Type) status and include an Accept-Encoding header field in that response, allowing clients to distinguish between issues related to content codings and media types. In order to avoid confusion with issues related to media types, servers that fail a request with a 415 status for reasons unrelated to content codings MUST NOT include the Accept- Encoding header field. The most common use of Accept-Encoding is in responses with a 415 (Unsupported Media Type) status code, in response to optimistic use of a content coding by clients. However, the header field can also be used to indicate to clients that content codings are supported in order to optimize future interactions. For example, a resource might include it in a 2xx (Successful) response when the request content was big enough to justify use of a compression coding but the client failed do so. #### 12.5.4. Accept-Language The "Accept-Language" header field can be used by user agents to indicate the set of natural languages that are preferred in the response. Language tags are defined in [Section 8.5.1](#section-8.5.1). Accept-Language = #( language-range [ weight ] ) language-range = <language-range, see [[RFC4647], Section 2.1](https://datatracker.ietf.org/doc/html/rfc4647#section-2.1)> Each language-range can be given an associated quality value representing an estimate of the user's preference for the languages specified by that range, as defined in [Section 12.4.2](#section-12.4.2). For example, Accept-Language: da, en-gb;q=0.8, en;q=0.7 would mean: "I prefer Danish, but will accept British English and other types of English". Note that some recipients treat the order in which language tags are listed as an indication of descending priority, particularly for tags that are assigned equal quality values (no value is the same as q=1). However, this behavior cannot be relied upon. For consistency and to maximize interoperability, many user agents assign each language tag a unique quality value while also listing them in order of decreasing quality. Additional discussion of language priority lists can be found in [Section 2.3 of [RFC4647]](https://datatracker.ietf.org/doc/html/rfc4647#section-2.3). For matching, [Section 3 of [RFC4647]](https://datatracker.ietf.org/doc/html/rfc4647#section-3) defines several matching schemes. Implementations can offer the most appropriate matching scheme for their requirements. The "Basic Filtering" scheme ([[RFC4647], Section 3.3.1](https://datatracker.ietf.org/doc/html/rfc4647#section-3.3.1)) is identical to the matching scheme that was previously defined for HTTP in [Section 14.4 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-14.4). It might be contrary to the privacy expectations of the user to send an Accept-Language header field with the complete linguistic preferences of the user in every request ([Section 17.13](#section-17.13)). Since intelligibility is highly dependent on the individual user, user agents need to allow user control over the linguistic preference (either through configuration of the user agent itself or by defaulting to a user controllable system setting). A user agent that does not provide such control to the user MUST NOT send an Accept- Language header field. | \*Note:\* User agents ought to provide guidance to users when | setting a preference, since users are rarely familiar with the | details of language matching as described above. For example, | users might assume that on selecting "en-gb", they will be | served any kind of English document if British English is not | available. A user agent might suggest, in such a case, to add | "en" to the list for better matching behavior. #### 12.5.5. Vary The "Vary" header field in a response describes what parts of a request message, aside from the method and target URI, might have influenced the origin server's process for selecting the content of this response. Vary = #( "\*" / field-name ) A Vary field value is either the wildcard member "\*" or a list of request field names, known as the selecting header fields, that might have had a role in selecting the representation for this response. Potential selecting header fields are not limited to fields defined by this specification. A list containing the member "\*" signals that other aspects of the request might have played a role in selecting the response representation, possibly including aspects outside the message syntax (e.g., the client's network address). A recipient will not be able to determine whether this response is appropriate for a later request without forwarding the request to the origin server. A proxy MUST NOT generate "\*" in a Vary field value. For example, a response that contains Vary: accept-encoding, accept-language indicates that the origin server might have used the request's Accept-Encoding and Accept-Language header fields (or lack thereof) as determining factors while choosing the content for this response. A Vary field containing a list of field names has two purposes: 1. To inform cache recipients that they MUST NOT use this response to satisfy a later request unless the later request has the same values for the listed header fields as the original request (Section 4.1 of [[CACHING](#ref-CACHING)]) or reuse of the response has been validated by the origin server. In other words, Vary expands the cache key required to match a new request to the stored cache entry. 2. To inform user agent recipients that this response was subject to content negotiation ([Section 12](#section-12)) and a different representation might be sent in a subsequent request if other values are provided in the listed header fields (proactive negotiation). An origin server SHOULD generate a Vary header field on a cacheable response when it wishes that response to be selectively reused for subsequent requests. Generally, that is the case when the response content has been tailored to better fit the preferences expressed by those selecting header fields, such as when an origin server has selected the response's language based on the request's Accept-Language header field. Vary might be elided when an origin server considers variance in content selection to be less significant than Vary's performance impact on caching, particularly when reuse is already limited by cache response directives (Section 5.2 of [[CACHING](#ref-CACHING)]). There is no need to send the Authorization field name in Vary because reuse of that response for a different user is prohibited by the field definition ([Section 11.6.2](#section-11.6.2)). Likewise, if the response content has been selected or influenced by network region, but the origin server wants the cached response to be reused even if recipients move from one region to another, then there is no need for the origin server to indicate such variance in Vary. 13. Conditional Requests ------------------------ A conditional request is an HTTP request with one or more request header fields that indicate a precondition to be tested before applying the request method to the target resource. [Section 13.2](#section-13.2) defines when to evaluate preconditions and their order of precedence when more than one precondition is present. Conditional GET requests are the most efficient mechanism for HTTP cache updates [[CACHING](#ref-CACHING)]. Conditionals can also be applied to state- changing methods, such as PUT and DELETE, to prevent the "lost update" problem: one client accidentally overwriting the work of another client that has been acting in parallel. ### 13.1. Preconditions Preconditions are usually defined with respect to a state of the target resource as a whole (its current value set) or the state as observed in a previously obtained representation (one value in that set). If a resource has multiple current representations, each with its own observable state, a precondition will assume that the mapping of each request to a selected representation ([Section 3.2](#section-3.2)) is consistent over time. Regardless, if the mapping is inconsistent or the server is unable to select an appropriate representation, then no harm will result when the precondition evaluates to false. Each precondition defined below consists of a comparison between a set of validators obtained from prior representations of the target resource to the current state of validators for the selected representation ([Section 8.8](#section-8.8)). Hence, these preconditions evaluate whether the state of the target resource has changed since a given state known by the client. The effect of such an evaluation depends on the method semantics and choice of conditional, as defined in [Section 13.2](#section-13.2). Other preconditions, defined by other specifications as extension fields, might place conditions on all recipients, on the state of the target resource in general, or on a group of resources. For instance, the "If" header field in WebDAV can make a request conditional on various aspects of multiple resources, such as locks, if the recipient understands and implements that field ([[WEBDAV](#ref-WEBDAV)], Section 10.4). Extensibility of preconditions is only possible when the precondition can be safely ignored if unknown (like If-Modified-Since), when deployment can be assumed for a given use case, or when implementation is signaled by some other property of the target resource. This encourages a focus on mutually agreed deployment of common standards. #### 13.1.1. If-Match The "If-Match" header field makes the request method conditional on the recipient origin server either having at least one current representation of the target resource, when the field value is "\*", or having a current representation of the target resource that has an entity tag matching a member of the list of entity tags provided in the field value. An origin server MUST use the strong comparison function when comparing entity tags for If-Match ([Section 8.8.3.2](#section-8.8.3.2)), since the client intends this precondition to prevent the method from being applied if there have been any changes to the representation data. If-Match = "\*" / #entity-tag Examples: If-Match: "xyzzy" If-Match: "xyzzy", "r2d2xxxx", "c3piozzzz" If-Match: \* If-Match is most often used with state-changing methods (e.g., POST, PUT, DELETE) to prevent accidental overwrites when multiple user agents might be acting in parallel on the same resource (i.e., to prevent the "lost update" problem). In general, it can be used with any method that involves the selection or modification of a representation to abort the request if the selected representation's current entity tag is not a member within the If-Match field value. When an origin server receives a request that selects a representation and that request includes an If-Match header field, the origin server MUST evaluate the If-Match condition per [Section 13.2](#section-13.2) prior to performing the method. To evaluate a received If-Match header field: 1. If the field value is "\*", the condition is true if the origin server has a current representation for the target resource. 2. If the field value is a list of entity tags, the condition is true if any of the listed tags match the entity tag of the selected representation. 3. Otherwise, the condition is false. An origin server that evaluates an If-Match condition MUST NOT perform the requested method if the condition evaluates to false. Instead, the origin server MAY indicate that the conditional request failed by responding with a 412 (Precondition Failed) status code. Alternatively, if the request is a state-changing operation that appears to have already been applied to the selected representation, the origin server MAY respond with a 2xx (Successful) status code (i.e., the change requested by the user agent has already succeeded, but the user agent might not be aware of it, perhaps because the prior response was lost or an equivalent change was made by some other user agent). Allowing an origin server to send a success response when a change request appears to have already been applied is more efficient for many authoring use cases, but comes with some risk if multiple user agents are making change requests that are very similar but not cooperative. For example, multiple user agents writing to a common resource as a semaphore (e.g., a nonatomic increment) are likely to collide and potentially lose important state transitions. For those kinds of resources, an origin server is better off being stringent in sending 412 for every failed precondition on an unsafe method. In other cases, excluding the ETag field from a success response might encourage the user agent to perform a GET as its next request to eliminate confusion about the resource's current state. A client MAY send an If-Match header field in a GET request to indicate that it would prefer a 412 (Precondition Failed) response if the selected representation does not match. However, this is only useful in range requests ([Section 14](#section-14)) for completing a previously received partial representation when there is no desire for a new representation. If-Range ([Section 13.1.5](#section-13.1.5)) is better suited for range requests when the client prefers to receive a new representation. A cache or intermediary MAY ignore If-Match because its interoperability features are only necessary for an origin server. Note that an If-Match header field with a list value containing "\*" and other values (including other instances of "\*") is syntactically invalid (therefore not allowed to be generated) and furthermore is unlikely to be interoperable. #### 13.1.2. If-None-Match The "If-None-Match" header field makes the request method conditional on a recipient cache or origin server either not having any current representation of the target resource, when the field value is "\*", or having a selected representation with an entity tag that does not match any of those listed in the field value. A recipient MUST use the weak comparison function when comparing entity tags for If-None-Match ([Section 8.8.3.2](#section-8.8.3.2)), since weak entity tags can be used for cache validation even if there have been changes to the representation data. If-None-Match = "\*" / #entity-tag Examples: If-None-Match: "xyzzy" If-None-Match: W/"xyzzy" If-None-Match: "xyzzy", "r2d2xxxx", "c3piozzzz" If-None-Match: W/"xyzzy", W/"r2d2xxxx", W/"c3piozzzz" If-None-Match: \* If-None-Match is primarily used in conditional GET requests to enable efficient updates of cached information with a minimum amount of transaction overhead. When a client desires to update one or more stored responses that have entity tags, the client SHOULD generate an If-None-Match header field containing a list of those entity tags when making a GET request; this allows recipient servers to send a 304 (Not Modified) response to indicate when one of those stored responses matches the selected representation. If-None-Match can also be used with a value of "\*" to prevent an unsafe request method (e.g., PUT) from inadvertently modifying an existing representation of the target resource when the client believes that the resource does not have a current representation ([Section 9.2.1](#section-9.2.1)). This is a variation on the "lost update" problem that might arise if more than one client attempts to create an initial representation for the target resource. When an origin server receives a request that selects a representation and that request includes an If-None-Match header field, the origin server MUST evaluate the If-None-Match condition per [Section 13.2](#section-13.2) prior to performing the method. To evaluate a received If-None-Match header field: 1. If the field value is "\*", the condition is false if the origin server has a current representation for the target resource. 2. If the field value is a list of entity tags, the condition is false if one of the listed tags matches the entity tag of the selected representation. 3. Otherwise, the condition is true. An origin server that evaluates an If-None-Match condition MUST NOT perform the requested method if the condition evaluates to false; instead, the origin server MUST respond with either a) the 304 (Not Modified) status code if the request method is GET or HEAD or b) the 412 (Precondition Failed) status code for all other request methods. Requirements on cache handling of a received If-None-Match header field are defined in Section 4.3.2 of [[CACHING](#ref-CACHING)]. Note that an If-None-Match header field with a list value containing "\*" and other values (including other instances of "\*") is syntactically invalid (therefore not allowed to be generated) and furthermore is unlikely to be interoperable. #### 13.1.3. If-Modified-Since The "If-Modified-Since" header field makes a GET or HEAD request method conditional on the selected representation's modification date being more recent than the date provided in the field value. Transfer of the selected representation's data is avoided if that data has not changed. If-Modified-Since = HTTP-date An example of the field is: If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT A recipient MUST ignore If-Modified-Since if the request contains an If-None-Match header field; the condition in If-None-Match is considered to be a more accurate replacement for the condition in If- Modified-Since, and the two are only combined for the sake of interoperating with older intermediaries that might not implement If-None-Match. A recipient MUST ignore the If-Modified-Since header field if the received field value is not a valid HTTP-date, the field value has more than one member, or if the request method is neither GET nor HEAD. A recipient MUST ignore the If-Modified-Since header field if the resource does not have a modification date available. A recipient MUST interpret an If-Modified-Since field value's timestamp in terms of the origin server's clock. If-Modified-Since is typically used for two distinct purposes: 1) to allow efficient updates of a cached representation that does not have an entity tag and 2) to limit the scope of a web traversal to resources that have recently changed. When used for cache updates, a cache will typically use the value of the cached message's Last-Modified header field to generate the field value of If-Modified-Since. This behavior is most interoperable for cases where clocks are poorly synchronized or when the server has chosen to only honor exact timestamp matches (due to a problem with Last-Modified dates that appear to go "back in time" when the origin server's clock is corrected or a representation is restored from an archived backup). However, caches occasionally generate the field value based on other data, such as the Date header field of the cached message or the clock time at which the message was received, particularly when the cached message does not contain a Last-Modified header field. When used for limiting the scope of retrieval to a recent time window, a user agent will generate an If-Modified-Since field value based on either its own clock or a Date header field received from the server in a prior response. Origin servers that choose an exact timestamp match based on the selected representation's Last-Modified header field will not be able to help the user agent limit its data transfers to only those changed during the specified window. When an origin server receives a request that selects a representation and that request includes an If-Modified-Since header field without an If-None-Match header field, the origin server SHOULD evaluate the If-Modified-Since condition per [Section 13.2](#section-13.2) prior to performing the method. To evaluate a received If-Modified-Since header field: 1. If the selected representation's last modification date is earlier or equal to the date provided in the field value, the condition is false. 2. Otherwise, the condition is true. An origin server that evaluates an If-Modified-Since condition SHOULD NOT perform the requested method if the condition evaluates to false; instead, the origin server SHOULD generate a 304 (Not Modified) response, including only those metadata that are useful for identifying or updating a previously cached response. Requirements on cache handling of a received If-Modified-Since header field are defined in Section 4.3.2 of [[CACHING](#ref-CACHING)]. #### 13.1.4. If-Unmodified-Since The "If-Unmodified-Since" header field makes the request method conditional on the selected representation's last modification date being earlier than or equal to the date provided in the field value. This field accomplishes the same purpose as If-Match for cases where the user agent does not have an entity tag for the representation. If-Unmodified-Since = HTTP-date An example of the field is: If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT A recipient MUST ignore If-Unmodified-Since if the request contains an If-Match header field; the condition in If-Match is considered to be a more accurate replacement for the condition in If-Unmodified- Since, and the two are only combined for the sake of interoperating with older intermediaries that might not implement If-Match. A recipient MUST ignore the If-Unmodified-Since header field if the received field value is not a valid HTTP-date (including when the field value appears to be a list of dates). A recipient MUST ignore the If-Unmodified-Since header field if the resource does not have a modification date available. A recipient MUST interpret an If-Unmodified-Since field value's timestamp in terms of the origin server's clock. If-Unmodified-Since is most often used with state-changing methods (e.g., POST, PUT, DELETE) to prevent accidental overwrites when multiple user agents might be acting in parallel on a resource that does not supply entity tags with its representations (i.e., to prevent the "lost update" problem). In general, it can be used with any method that involves the selection or modification of a representation to abort the request if the selected representation's last modification date has changed since the date provided in the If- Unmodified-Since field value. When an origin server receives a request that selects a representation and that request includes an If-Unmodified-Since header field without an If-Match header field, the origin server MUST evaluate the If-Unmodified-Since condition per [Section 13.2](#section-13.2) prior to performing the method. To evaluate a received If-Unmodified-Since header field: 1. If the selected representation's last modification date is earlier than or equal to the date provided in the field value, the condition is true. 2. Otherwise, the condition is false. An origin server that evaluates an If-Unmodified-Since condition MUST NOT perform the requested method if the condition evaluates to false. Instead, the origin server MAY indicate that the conditional request failed by responding with a 412 (Precondition Failed) status code. Alternatively, if the request is a state-changing operation that appears to have already been applied to the selected representation, the origin server MAY respond with a 2xx (Successful) status code (i.e., the change requested by the user agent has already succeeded, but the user agent might not be aware of it, perhaps because the prior response was lost or an equivalent change was made by some other user agent). Allowing an origin server to send a success response when a change request appears to have already been applied is more efficient for many authoring use cases, but comes with some risk if multiple user agents are making change requests that are very similar but not cooperative. In those cases, an origin server is better off being stringent in sending 412 for every failed precondition on an unsafe method. A client MAY send an If-Unmodified-Since header field in a GET request to indicate that it would prefer a 412 (Precondition Failed) response if the selected representation has been modified. However, this is only useful in range requests ([Section 14](#section-14)) for completing a previously received partial representation when there is no desire for a new representation. If-Range ([Section 13.1.5](#section-13.1.5)) is better suited for range requests when the client prefers to receive a new representation. A cache or intermediary MAY ignore If-Unmodified-Since because its interoperability features are only necessary for an origin server. #### 13.1.5. If-Range The "If-Range" header field provides a special conditional request mechanism that is similar to the If-Match and If-Unmodified-Since header fields but that instructs the recipient to ignore the Range header field if the validator doesn't match, resulting in transfer of the new selected representation instead of a 412 (Precondition Failed) response. If a client has a partial copy of a representation and wishes to have an up-to-date copy of the entire representation, it could use the Range header field with a conditional GET (using either or both of If-Unmodified-Since and If-Match.) However, if the precondition fails because the representation has been modified, the client would then have to make a second request to obtain the entire current representation. The "If-Range" header field allows a client to "short-circuit" the second request. Informally, its meaning is as follows: if the representation is unchanged, send me the part(s) that I am requesting in Range; otherwise, send me the entire representation. If-Range = entity-tag / HTTP-date A valid entity-tag can be distinguished from a valid HTTP-date by examining the first three characters for a DQUOTE. A client MUST NOT generate an If-Range header field in a request that does not contain a Range header field. A server MUST ignore an If- Range header field received in a request that does not contain a Range header field. An origin server MUST ignore an If-Range header field received in a request for a target resource that does not support Range requests. A client MUST NOT generate an If-Range header field containing an entity tag that is marked as weak. A client MUST NOT generate an If- Range header field containing an HTTP-date unless the client has no entity tag for the corresponding representation and the date is a strong validator in the sense defined by [Section 8.8.2.2](#section-8.8.2.2). A server that receives an If-Range header field on a Range request MUST evaluate the condition per [Section 13.2](#section-13.2) prior to performing the method. To evaluate a received If-Range header field containing an HTTP-date: 1. If the HTTP-date validator provided is not a strong validator in the sense defined by [Section 8.8.2.2](#section-8.8.2.2), the condition is false. 2. If the HTTP-date validator provided exactly matches the Last-Modified field value for the selected representation, the condition is true. 3. Otherwise, the condition is false. To evaluate a received If-Range header field containing an entity-tag: 1. If the entity-tag validator provided exactly matches the ETag field value for the selected representation using the strong comparison function ([Section 8.8.3.2](#section-8.8.3.2)), the condition is true. 2. Otherwise, the condition is false. A recipient of an If-Range header field MUST ignore the Range header field if the If-Range condition evaluates to false. Otherwise, the recipient SHOULD process the Range header field as requested. Note that the If-Range comparison is by exact match, including when the validator is an HTTP-date, and so it differs from the "earlier than or equal to" comparison used when evaluating an If-Unmodified-Since conditional. ### 13.2. Evaluation of Preconditions #### 13.2.1. When to Evaluate Except when excluded below, a recipient cache or origin server MUST evaluate received request preconditions after it has successfully performed its normal request checks and just before it would process the request content (if any) or perform the action associated with the request method. A server MUST ignore all received preconditions if its response to the same request without those conditions, prior to processing the request content, would have been a status code other than a 2xx (Successful) or 412 (Precondition Failed). In other words, redirects and failures that can be detected before significant processing occurs take precedence over the evaluation of preconditions. A server that is not the origin server for the target resource and cannot act as a cache for requests on the target resource MUST NOT evaluate the conditional request header fields defined by this specification, and it MUST forward them if the request is forwarded, since the generating client intends that they be evaluated by a server that can provide a current representation. Likewise, a server MUST ignore the conditional request header fields defined by this specification when received with a request method that does not involve the selection or modification of a selected representation, such as CONNECT, OPTIONS, or TRACE. Note that protocol extensions can modify the conditions under which preconditions are evaluated or the consequences of their evaluation. For example, the immutable cache directive (defined by [[RFC8246](https://datatracker.ietf.org/doc/html/rfc8246)]) instructs caches to forgo forwarding conditional requests when they hold a fresh response. Although conditional request header fields are defined as being usable with the HEAD method (to keep HEAD's semantics consistent with those of GET), there is no point in sending a conditional HEAD because a successful response is around the same size as a 304 (Not Modified) response and more useful than a 412 (Precondition Failed) response. #### 13.2.2. Precedence of Preconditions When more than one conditional request header field is present in a request, the order in which the fields are evaluated becomes important. In practice, the fields defined in this document are consistently implemented in a single, logical order, since "lost update" preconditions have more strict requirements than cache validation, a validated cache is more efficient than a partial response, and entity tags are presumed to be more accurate than date validators. A recipient cache or origin server MUST evaluate the request preconditions defined by this specification in the following order: 1. When recipient is the origin server and If-Match is present, evaluate the If-Match precondition: \* if true, continue to step 3 \* if false, respond 412 (Precondition Failed) unless it can be determined that the state-changing request has already succeeded (see [Section 13.1.1](#section-13.1.1)) 2. When recipient is the origin server, If-Match is not present, and If-Unmodified-Since is present, evaluate the If-Unmodified-Since precondition: \* if true, continue to step 3 \* if false, respond 412 (Precondition Failed) unless it can be determined that the state-changing request has already succeeded (see [Section 13.1.4](#section-13.1.4)) 3. When If-None-Match is present, evaluate the If-None-Match precondition: \* if true, continue to step 5 \* if false for GET/HEAD, respond 304 (Not Modified) \* if false for other methods, respond 412 (Precondition Failed) 4. When the method is GET or HEAD, If-None-Match is not present, and If-Modified-Since is present, evaluate the If-Modified-Since precondition: \* if true, continue to step 5 \* if false, respond 304 (Not Modified) 5. When the method is GET and both Range and If-Range are present, evaluate the If-Range precondition: \* if true and the Range is applicable to the selected representation, respond 206 (Partial Content) \* otherwise, ignore the Range header field and respond 200 (OK) 6. Otherwise, \* perform the requested method and respond according to its success or failure. Any extension to HTTP that defines additional conditional request header fields ought to define the order for evaluating such fields in relation to those defined in this document and other conditionals that might be found in practice. 14. Range Requests ------------------ Clients often encounter interrupted data transfers as a result of canceled requests or dropped connections. When a client has stored a partial representation, it is desirable to request the remainder of that representation in a subsequent request rather than transfer the entire representation. Likewise, devices with limited local storage might benefit from being able to request only a subset of a larger representation, such as a single page of a very large document, or the dimensions of an embedded image. Range requests are an OPTIONAL feature of HTTP, designed so that recipients not implementing this feature (or not supporting it for the target resource) can respond as if it is a normal GET request without impacting interoperability. Partial responses are indicated by a distinct status code to not be mistaken for full responses by caches that might not implement the feature. ### 14.1. Range Units Representation data can be partitioned into subranges when there are addressable structural units inherent to that data's content coding or media type. For example, octet (a.k.a. byte) boundaries are a structural unit common to all representation data, allowing partitions of the data to be identified as a range of bytes at some offset from the start or end of that data. This general notion of a "range unit" is used in the Accept-Ranges ([Section 14.3](#section-14.3)) response header field to advertise support for range requests, the Range ([Section 14.2](#section-14.2)) request header field to delineate the parts of a representation that are requested, and the Content-Range ([Section 14.4](#section-14.4)) header field to describe which part of a representation is being transferred. range-unit = token All range unit names are case-insensitive and ought to be registered within the "HTTP Range Unit Registry", as defined in [Section 16.5.1](#section-16.5.1). Range units are intended to be extensible, as described in [Section 16.5](#section-16.5). #### 14.1.1. Range Specifiers Ranges are expressed in terms of a range unit paired with a set of range specifiers. The range unit name determines what kinds of range-spec are applicable to its own specifiers. Hence, the following grammar is generic: each range unit is expected to specify requirements on when int-range, suffix-range, and other-range are allowed. A range request can specify a single range or a set of ranges within a single representation. ranges-specifier = range-unit "=" range-set range-set = 1#range-spec range-spec = int-range / suffix-range / other-range An int-range is a range expressed as two non-negative integers or as one non-negative integer through to the end of the representation data. The range unit specifies what the integers mean (e.g., they might indicate unit offsets from the beginning, inclusive numbered parts, etc.). int-range = first-pos "-" [ last-pos ] first-pos = 1\*DIGIT last-pos = 1\*DIGIT An int-range is invalid if the last-pos value is present and less than the first-pos. A suffix-range is a range expressed as a suffix of the representation data with the provided non-negative integer maximum length (in range units). In other words, the last N units of the representation data. suffix-range = "-" suffix-length suffix-length = 1\*DIGIT To provide for extensibility, the other-range rule is a mostly unconstrained grammar that allows application-specific or future range units to define additional range specifiers. other-range = 1\*( %x21-2B / %x2D-7E ) ; 1\*(VCHAR excluding comma) A ranges-specifier is invalid if it contains any range-spec that is invalid or undefined for the indicated range-unit. A valid ranges-specifier is "satisfiable" if it contains at least one range-spec that is satisfiable, as defined by the indicated range-unit. Otherwise, the ranges-specifier is "unsatisfiable". #### 14.1.2. Byte Ranges The "bytes" range unit is used to express subranges of a representation data's octet sequence. Each byte range is expressed as an integer range at some offset, relative to either the beginning (int-range) or end (suffix-range) of the representation data. Byte ranges do not use the other-range specifier. The first-pos value in a bytes int-range gives the offset of the first byte in a range. The last-pos value gives the offset of the last byte in the range; that is, the byte positions specified are inclusive. Byte offsets start at zero. If the representation data has a content coding applied, each byte range is calculated with respect to the encoded sequence of bytes, not the sequence of underlying bytes that would be obtained after decoding. Examples of bytes range specifiers: \* The first 500 bytes (byte offsets 0-499, inclusive): bytes=0-499 \* The second 500 bytes (byte offsets 500-999, inclusive): bytes=500-999 A client can limit the number of bytes requested without knowing the size of the selected representation. If the last-pos value is absent, or if the value is greater than or equal to the current length of the representation data, the byte range is interpreted as the remainder of the representation (i.e., the server replaces the value of last-pos with a value that is one less than the current length of the selected representation). A client can refer to the last N bytes (N > 0) of the selected representation using a suffix-range. If the selected representation is shorter than the specified suffix-length, the entire representation is used. Additional examples, assuming a representation of length 10000: \* The final 500 bytes (byte offsets 9500-9999, inclusive): bytes=-500 Or: bytes=9500- \* The first and last bytes only (bytes 0 and 9999): bytes=0-0,-1 \* The first, middle, and last 1000 bytes: bytes= 0-999, 4500-5499, -1000 \* Other valid (but not canonical) specifications of the second 500 bytes (byte offsets 500-999, inclusive): bytes=500-600,601-999 bytes=500-700,601-999 For a GET request, a valid bytes range-spec is satisfiable if it is either: \* an int-range with a first-pos that is less than the current length of the selected representation or \* a suffix-range with a non-zero suffix-length. When a selected representation has zero length, the only satisfiable form of range-spec in a GET request is a suffix-range with a non-zero suffix-length. In the byte-range syntax, first-pos, last-pos, and suffix-length are expressed as decimal number of octets. Since there is no predefined limit to the length of content, recipients MUST anticipate potentially large decimal numerals and prevent parsing errors due to integer conversion overflows. ### 14.2. Range The "Range" header field on a GET request modifies the method semantics to request transfer of only one or more subranges of the selected representation data ([Section 8.1](#section-8.1)), rather than the entire selected representation. Range = ranges-specifier A server MAY ignore the Range header field. However, origin servers and intermediate caches ought to support byte ranges when possible, since they support efficient recovery from partially failed transfers and partial retrieval of large representations. A server MUST ignore a Range header field received with a request method that is unrecognized or for which range handling is not defined. For this specification, GET is the only method for which range handling is defined. An origin server MUST ignore a Range header field that contains a range unit it does not understand. A proxy MAY discard a Range header field that contains a range unit it does not understand. A server that supports range requests MAY ignore or reject a Range header field that contains an invalid ranges-specifier ([Section 14.1.1](#section-14.1.1)), a ranges-specifier with more than two overlapping ranges, or a set of many small ranges that are not listed in ascending order, since these are indications of either a broken client or a deliberate denial-of-service attack ([Section 17.15](#section-17.15)). A client SHOULD NOT request multiple ranges that are inherently less efficient to process and transfer than a single range that encompasses the same data. A server that supports range requests MAY ignore a Range header field when the selected representation has no content (i.e., the selected representation's data is of zero length). A client that is requesting multiple ranges SHOULD list those ranges in ascending order (the order in which they would typically be received in a complete representation) unless there is a specific need to request a later part earlier. For example, a user agent processing a large representation with an internal catalog of parts might need to request later parts first, particularly if the representation consists of pages stored in reverse order and the user agent wishes to transfer one page at a time. The Range header field is evaluated after evaluating the precondition header fields defined in [Section 13.1](#section-13.1), and only if the result in absence of the Range header field would be a 200 (OK) response. In other words, Range is ignored when a conditional GET would result in a 304 (Not Modified) response. The If-Range header field ([Section 13.1.5](#section-13.1.5)) can be used as a precondition to applying the Range header field. If all of the preconditions are true, the server supports the Range header field for the target resource, the received Range field-value contains a valid ranges-specifier with a range-unit supported for that target resource, and that ranges-specifier is satisfiable with respect to the selected representation, the server SHOULD send a 206 (Partial Content) response with content containing one or more partial representations that correspond to the satisfiable range-spec(s) requested. The above does not imply that a server will send all requested ranges. In some cases, it may only be possible (or efficient) to send a portion of the requested ranges first, while expecting the client to re-request the remaining portions later if they are still desired (see [Section 15.3.7](#section-15.3.7)). If all of the preconditions are true, the server supports the Range header field for the target resource, the received Range field-value contains a valid ranges-specifier, and either the range-unit is not supported for that target resource or the ranges-specifier is unsatisfiable with respect to the selected representation, the server SHOULD send a 416 (Range Not Satisfiable) response. ### 14.3. Accept-Ranges The "Accept-Ranges" field in a response indicates whether an upstream server supports range requests for the target resource. Accept-Ranges = acceptable-ranges acceptable-ranges = 1#range-unit For example, a server that supports byte-range requests ([Section 14.1.2](#section-14.1.2)) can send the field Accept-Ranges: bytes to indicate that it supports byte range requests for that target resource, thereby encouraging its use by the client for future partial requests on the same request path. Range units are defined in [Section 14.1](#section-14.1). A client MAY generate range requests regardless of having received an Accept-Ranges field. The information only provides advice for the sake of improving performance and reducing unnecessary network transfers. Conversely, a client MUST NOT assume that receiving an Accept-Ranges field means that future range requests will return partial responses. The content might change, the server might only support range requests at certain times or under certain conditions, or a different intermediary might process the next request. A server that does not support any kind of range request for the target resource MAY send Accept-Ranges: none to advise the client not to attempt a range request on the same request path. The range unit "none" is reserved for this purpose. The Accept-Ranges field MAY be sent in a trailer section, but is preferred to be sent as a header field because the information is particularly useful for restarting large information transfers that have failed in mid-content (before the trailer section is received). ### 14.4. Content-Range The "Content-Range" header field is sent in a single part 206 (Partial Content) response to indicate the partial range of the selected representation enclosed as the message content, sent in each part of a multipart 206 response to indicate the range enclosed within each body part ([Section 14.6](#section-14.6)), and sent in 416 (Range Not Satisfiable) responses to provide information about the selected representation. Content-Range = range-unit SP ( range-resp / unsatisfied-range ) range-resp = incl-range "/" ( complete-length / "\*" ) incl-range = first-pos "-" last-pos unsatisfied-range = "\*/" complete-length complete-length = 1\*DIGIT If a 206 (Partial Content) response contains a Content-Range header field with a range unit ([Section 14.1](#section-14.1)) that the recipient does not understand, the recipient MUST NOT attempt to recombine it with a stored representation. A proxy that receives such a message SHOULD forward it downstream. Content-Range might also be sent as a request modifier to request a partial PUT, as described in [Section 14.5](#section-14.5), based on private agreements between client and origin server. A server MUST ignore a Content-Range header field received in a request with a method for which Content-Range support is not defined. For byte ranges, a sender SHOULD indicate the complete length of the representation from which the range has been extracted, unless the complete length is unknown or difficult to determine. An asterisk character ("\*") in place of the complete-length indicates that the representation length was unknown when the header field was generated. The following example illustrates when the complete length of the selected representation is known by the sender to be 1234 bytes: Content-Range: bytes 42-1233/1234 and this second example illustrates when the complete length is unknown: Content-Range: bytes 42-1233/\* A Content-Range field value is invalid if it contains a range-resp that has a last-pos value less than its first-pos value, or a complete-length value less than or equal to its last-pos value. The recipient of an invalid Content-Range MUST NOT attempt to recombine the received content with a stored representation. A server generating a 416 (Range Not Satisfiable) response to a byte- range request SHOULD send a Content-Range header field with an unsatisfied-range value, as in the following example: Content-Range: bytes \*/1234 The complete-length in a 416 response indicates the current length of the selected representation. The Content-Range header field has no meaning for status codes that do not explicitly describe its semantic. For this specification, only the 206 (Partial Content) and 416 (Range Not Satisfiable) status codes describe a meaning for Content-Range. The following are examples of Content-Range values in which the selected representation contains a total of 1234 bytes: \* The first 500 bytes: Content-Range: bytes 0-499/1234 \* The second 500 bytes: Content-Range: bytes 500-999/1234 \* All except for the first 500 bytes: Content-Range: bytes 500-1233/1234 \* The last 500 bytes: Content-Range: bytes 734-1233/1234 ### 14.5. Partial PUT Some origin servers support PUT of a partial representation when the user agent sends a Content-Range header field ([Section 14.4](#section-14.4)) in the request, though such support is inconsistent and depends on private agreements with user agents. In general, it requests that the state of the target resource be partly replaced with the enclosed content at an offset and length indicated by the Content-Range value, where the offset is relative to the current selected representation. An origin server SHOULD respond with a 400 (Bad Request) status code if it receives Content-Range on a PUT for a target resource that does not support partial PUT requests. Partial PUT is not backwards compatible with the original definition of PUT. It may result in the content being written as a complete replacement for the current representation. Partial resource updates are also possible by targeting a separately identified resource with state that overlaps or extends a portion of the larger resource, or by using a different method that has been specifically defined for partial updates (for example, the PATCH method defined in [[RFC5789](https://datatracker.ietf.org/doc/html/rfc5789)]). ### 14.6. Media Type multipart/byteranges When a 206 (Partial Content) response message includes the content of multiple ranges, they are transmitted as body parts in a multipart message body ([[RFC2046], Section 5.1](https://datatracker.ietf.org/doc/html/rfc2046#section-5.1)) with the media type of "multipart/byteranges". The "multipart/byteranges" media type includes one or more body parts, each with its own Content-Type and Content-Range fields. The required boundary parameter specifies the boundary string used to separate each body part. Implementation Notes: 1. Additional CRLFs might precede the first boundary string in the body. 2. Although [[RFC2046](https://datatracker.ietf.org/doc/html/rfc2046)] permits the boundary string to be quoted, some existing implementations handle a quoted boundary string incorrectly. 3. A number of clients and servers were coded to an early draft of the byteranges specification that used a media type of "multipart/x-byteranges", which is almost (but not quite) compatible with this type. Despite the name, the "multipart/byteranges" media type is not limited to byte ranges. The following example uses an "exampleunit" range unit: HTTP/1.1 206 Partial Content Date: Tue, 14 Nov 1995 06:25:24 GMT Last-Modified: Tue, 14 July 04:58:08 GMT Content-Length: 2331785 Content-Type: multipart/byteranges; boundary=THIS\_STRING\_SEPARATES --THIS\_STRING\_SEPARATES Content-Type: video/example Content-Range: exampleunit 1.2-4.3/25 ...the first range --THIS\_STRING\_SEPARATES Content-Type: video/example Content-Range: exampleunit 11.2-14.3/25 ...the second range --THIS\_STRING\_SEPARATES-- The following information serves as the registration form for the "multipart/byteranges" media type. Type name: multipart Subtype name: byteranges Required parameters: boundary Optional parameters: N/A Encoding considerations: only "7bit", "8bit", or "binary" are permitted Security considerations: see [Section 17](#section-17) Interoperability considerations: N/A Published specification: [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110) (see [Section 14.6](#section-14.6)) Applications that use this media type: HTTP components supporting multiple ranges in a single request Fragment identifier considerations: N/A Additional information: Deprecated alias names for this type: N/A Magic number(s): N/A File extension(s): N/A Macintosh file type code(s): N/A Person and email address to contact for further information: See Aut hors' Addresses section. Intended usage: COMMON Restrictions on usage: N/A Author: See Authors' Addresses section. Change controller: IESG 15. Status Codes ---------------- The status code of a response is a three-digit integer code that describes the result of the request and the semantics of the response, including whether the request was successful and what content is enclosed (if any). All valid status codes are within the range of 100 to 599, inclusive. The first digit of the status code defines the class of response. The last two digits do not have any categorization role. There are five values for the first digit: \* 1xx (Informational): The request was received, continuing process \* 2xx (Successful): The request was successfully received, understood, and accepted \* 3xx (Redirection): Further action needs to be taken in order to complete the request \* 4xx (Client Error): The request contains bad syntax or cannot be fulfilled \* 5xx (Server Error): The server failed to fulfill an apparently valid request HTTP status codes are extensible. A client is not required to understand the meaning of all registered status codes, though such understanding is obviously desirable. However, a client MUST understand the class of any status code, as indicated by the first digit, and treat an unrecognized status code as being equivalent to the x00 status code of that class. For example, if a client receives an unrecognized status code of 471, it can see from the first digit that there was something wrong with its request and treat the response as if it had received a 400 (Bad Request) status code. The response message will usually contain a representation that explains the status. Values outside the range 100..599 are invalid. Implementations often use three-digit integer values outside of that range (i.e., 600..999) for internal communication of non-HTTP status (e.g., library errors). A client that receives a response with an invalid status code SHOULD process the response as if it had a 5xx (Server Error) status code. A single request can have multiple associated responses: zero or more "interim" (non-final) responses with status codes in the "informational" (1xx) range, followed by exactly one "final" response with a status code in one of the other ranges. ### 15.1. Overview of Status Codes The status codes listed below are defined in this specification. The reason phrases listed here are only recommendations -- they can be replaced by local equivalents or left out altogether without affecting the protocol. Responses with status codes that are defined as heuristically cacheable (e.g., 200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, and 501 in this specification) can be reused by a cache with heuristic expiration unless otherwise indicated by the method definition or explicit cache controls [[CACHING](#ref-CACHING)]; all other status codes are not heuristically cacheable. Additional status codes, outside the scope of this specification, have been specified for use in HTTP. All such status codes ought to be registered within the "Hypertext Transfer Protocol (HTTP) Status Code Registry", as described in [Section 16.2](#section-16.2). ### 15.2. Informational 1xx The 1xx (Informational) class of status code indicates an interim response for communicating connection status or request progress prior to completing the requested action and sending a final response. Since HTTP/1.0 did not define any 1xx status codes, a server MUST NOT send a 1xx response to an HTTP/1.0 client. A 1xx response is terminated by the end of the header section; it cannot contain content or trailers. A client MUST be able to parse one or more 1xx responses received prior to a final response, even if the client does not expect one. A user agent MAY ignore unexpected 1xx responses. A proxy MUST forward 1xx responses unless the proxy itself requested the generation of the 1xx response. For example, if a proxy adds an "Expect: 100-continue" header field when it forwards a request, then it need not forward the corresponding 100 (Continue) response(s). #### 15.2.1. 100 Continue The 100 (Continue) status code indicates that the initial part of a request has been received and has not yet been rejected by the server. The server intends to send a final response after the request has been fully received and acted upon. When the request contains an Expect header field that includes a 100-continue expectation, the 100 response indicates that the server wishes to receive the request content, as described in [Section 10.1.1](#section-10.1.1). The client ought to continue sending the request and discard the 100 response. If the request did not contain an Expect header field containing the 100-continue expectation, the client can simply discard this interim response. #### 15.2.2. 101 Switching Protocols The 101 (Switching Protocols) status code indicates that the server understands and is willing to comply with the client's request, via the Upgrade header field ([Section 7.8](#section-7.8)), for a change in the application protocol being used on this connection. The server MUST generate an Upgrade header field in the response that indicates which protocol(s) will be in effect after this response. It is assumed that the server will only agree to switch protocols when it is advantageous to do so. For example, switching to a newer version of HTTP might be advantageous over older versions, and switching to a real-time, synchronous protocol might be advantageous when delivering resources that use such features. ### 15.3. Successful 2xx The 2xx (Successful) class of status code indicates that the client's request was successfully received, understood, and accepted. #### 15.3.1. 200 OK The 200 (OK) status code indicates that the request has succeeded. The content sent in a 200 response depends on the request method. For the methods defined by this specification, the intended meaning of the content can be summarized as: +================+============================================+ | Request Method | Response content is a representation of: | +================+============================================+ | GET | the target resource | +----------------+--------------------------------------------+ | HEAD | the target resource, like GET, but without | | | transferring the representation data | +----------------+--------------------------------------------+ | POST | the status of, or results obtained from, | | | the action | +----------------+--------------------------------------------+ | PUT, DELETE | the status of the action | +----------------+--------------------------------------------+ | OPTIONS | communication options for the target | | | resource | +----------------+--------------------------------------------+ | TRACE | the request message as received by the | | | server returning the trace | +----------------+--------------------------------------------+ Table 6 Aside from responses to CONNECT, a 200 response is expected to contain message content unless the message framing explicitly indicates that the content has zero length. If some aspect of the request indicates a preference for no content upon success, the origin server ought to send a 204 (No Content) response instead. For CONNECT, there is no content because the successful result is a tunnel, which begins immediately after the 200 response header section. A 200 response is heuristically cacheable; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [[CACHING](#ref-CACHING)]). In 200 responses to GET or HEAD, an origin server SHOULD send any available validator fields ([Section 8.8](#section-8.8)) for the selected representation, with both a strong entity tag and a Last-Modified date being preferred. In 200 responses to state-changing methods, any validator fields ([Section 8.8](#section-8.8)) sent in the response convey the current validators for the new representation formed as a result of successfully applying the request semantics. Note that the PUT method ([Section 9.3.4](#section-9.3.4)) has additional requirements that might preclude sending such validators. #### 15.3.2. 201 Created The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location header field is received, by the target URI. The 201 response content typically describes and links to the resource(s) created. Any validator fields ([Section 8.8](#section-8.8)) sent in the response convey the current validators for a new representation created by the request. Note that the PUT method ([Section 9.3.4](#section-9.3.4)) has additional requirements that might preclude sending such validators. #### 15.3.3. 202 Accepted The 202 (Accepted) status code indicates that the request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. There is no facility in HTTP for re-sending a status code from an asynchronous operation. The 202 response is intentionally noncommittal. Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent's connection to the server persist until the process is completed. The representation sent with this response ought to describe the request's current status and point to (or embed) a status monitor that can provide the user with an estimate of when the request will be fulfilled. #### 15.3.4. 203 Non-Authoritative Information The 203 (Non-Authoritative Information) status code indicates that the request was successful but the enclosed content has been modified from that of the origin server's 200 (OK) response by a transforming proxy ([Section 7.7](#section-7.7)). This status code allows the proxy to notify recipients when a transformation has been applied, since that knowledge might impact later decisions regarding the content. For example, future cache validation requests for the content might only be applicable along the same request path (through the same proxies). A 203 response is heuristically cacheable; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [[CACHING](#ref-CACHING)]). #### 15.3.5. 204 No Content The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response content. Metadata in the response header fields refer to the target resource and its selected representation after the requested action was applied. For example, if a 204 status code is received in response to a PUT request and the response contains an ETag field, then the PUT was successful and the ETag field value contains the entity tag for the new representation of that target resource. The 204 response allows a server to indicate that the action has been successfully applied to the target resource, while implying that the user agent does not need to traverse away from its current "document view" (if any). The server assumes that the user agent will provide some indication of the success to its user, in accord with its own interface, and apply any new or updated metadata in the response to its active representation. For example, a 204 status code is commonly used with document editing interfaces corresponding to a "save" action, such that the document being saved remains available to the user for editing. It is also frequently used with interfaces that expect automated data transfers to be prevalent, such as within distributed version control systems. A 204 response is terminated by the end of the header section; it cannot contain content or trailers. A 204 response is heuristically cacheable; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [[CACHING](#ref-CACHING)]). #### 15.3.6. 205 Reset Content The 205 (Reset Content) status code indicates that the server has fulfilled the request and desires that the user agent reset the "document view", which caused the request to be sent, to its original state as received from the origin server. This response is intended to support a common data entry use case where the user receives content that supports data entry (a form, notepad, canvas, etc.), enters or manipulates data in that space, causes the entered data to be submitted in a request, and then the data entry mechanism is reset for the next entry so that the user can easily initiate another input action. Since the 205 status code implies that no additional content will be provided, a server MUST NOT generate content in a 205 response. #### 15.3.7. 206 Partial Content The 206 (Partial Content) status code indicates that the server is successfully fulfilling a range request for the target resource by transferring one or more parts of the selected representation. A server that supports range requests ([Section 14](#section-14)) will usually attempt to satisfy all of the requested ranges, since sending less data will likely result in another client request for the remainder. However, a server might want to send only a subset of the data requested for reasons of its own, such as temporary unavailability, cache efficiency, load balancing, etc. Since a 206 response is self- descriptive, the client can still understand a response that only partially satisfies its range request. A client MUST inspect a 206 response's Content-Type and Content-Range field(s) to determine what parts are enclosed and whether additional requests are needed. A server that generates a 206 response MUST generate the following header fields, in addition to those required in the subsections below, if the field would have been sent in a 200 (OK) response to the same request: Date, Cache-Control, ETag, Expires, Content-Location, and Vary. A Content-Length header field present in a 206 response indicates the number of octets in the content of this message, which is usually not the complete length of the selected representation. Each Content-Range header field includes information about the selected representation's complete length. A sender that generates a 206 response to a request with an If-Range header field SHOULD NOT generate other representation header fields beyond those required because the client already has a prior response containing those header fields. Otherwise, a sender MUST generate all of the representation header fields that would have been sent in a 200 (OK) response to the same request. A 206 response is heuristically cacheable; i.e., unless otherwise indicated by explicit cache controls (see Section 4.2.2 of [[CACHING](#ref-CACHING)]). ##### 15.3.7.1. Single Part If a single part is being transferred, the server generating the 206 response MUST generate a Content-Range header field, describing what range of the selected representation is enclosed, and a content consisting of the range. For example: HTTP/1.1 206 Partial Content Date: Wed, 15 Nov 1995 06:25:24 GMT Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT Content-Range: bytes 21010-47021/47022 Content-Length: 26012 Content-Type: image/gif ... 26012 bytes of partial image data ##### 15.3.7.2. Multiple Parts If multiple parts are being transferred, the server generating the 206 response MUST generate "multipart/byteranges" content, as defined in [Section 14.6](#section-14.6), and a Content-Type header field containing the "multipart/byteranges" media type and its required boundary parameter. To avoid confusion with single-part responses, a server MUST NOT generate a Content-Range header field in the HTTP header section of a multiple part response (this field will be sent in each part instead). Within the header area of each body part in the multipart content, the server MUST generate a Content-Range header field corresponding to the range being enclosed in that body part. If the selected representation would have had a Content-Type header field in a 200 (OK) response, the server SHOULD generate that same Content-Type header field in the header area of each body part. For example: HTTP/1.1 206 Partial Content Date: Wed, 15 Nov 1995 06:25:24 GMT Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT Content-Length: 1741 Content-Type: multipart/byteranges; boundary=THIS\_STRING\_SEPARATES --THIS\_STRING\_SEPARATES Content-Type: application/pdf Content-Range: bytes 500-999/8000 ...the first range --THIS\_STRING\_SEPARATES Content-Type: application/pdf Content-Range: bytes 7000-7999/8000 ...the second range --THIS\_STRING\_SEPARATES-- When multiple ranges are requested, a server MAY coalesce any of the ranges that overlap, or that are separated by a gap that is smaller than the overhead of sending multiple parts, regardless of the order in which the corresponding range-spec appeared in the received Range header field. Since the typical overhead between each part of a "multipart/byteranges" is around 80 bytes, depending on the selected representation's media type and the chosen boundary parameter length, it can be less efficient to transfer many small disjoint parts than it is to transfer the entire selected representation. A server MUST NOT generate a multipart response to a request for a single range, since a client that does not request multiple parts might not support multipart responses. However, a server MAY generate a "multipart/byteranges" response with only a single body part if multiple ranges were requested and only one range was found to be satisfiable or only one range remained after coalescing. A client that cannot process a "multipart/byteranges" response MUST NOT generate a request that asks for multiple ranges. A server that generates a multipart response SHOULD send the parts in the same order that the corresponding range-spec appeared in the received Range header field, excluding those ranges that were deemed unsatisfiable or that were coalesced into other ranges. A client that receives a multipart response MUST inspect the Content-Range header field present in each body part in order to determine which range is contained in that body part; a client cannot rely on receiving the same ranges that it requested, nor the same order that it requested. ##### 15.3.7.3. Combining Parts A response might transfer only a subrange of a representation if the connection closed prematurely or if the request used one or more Range specifications. After several such transfers, a client might have received several ranges of the same representation. These ranges can only be safely combined if they all have in common the same strong validator ([Section 8.8.1](#section-8.8.1)). A client that has received multiple partial responses to GET requests on a target resource MAY combine those responses into a larger continuous range if they share the same strong validator. If the most recent response is an incomplete 200 (OK) response, then the header fields of that response are used for any combined response and replace those of the matching stored responses. If the most recent response is a 206 (Partial Content) response and at least one of the matching stored responses is a 200 (OK), then the combined response header fields consist of the most recent 200 response's header fields. If all of the matching stored responses are 206 responses, then the stored response with the most recent header fields is used as the source of header fields for the combined response, except that the client MUST use other header fields provided in the new response, aside from Content-Range, to replace all instances of the corresponding header fields in the stored response. The combined response content consists of the union of partial content ranges within the new response and all of the matching stored responses. If the union consists of the entire range of the representation, then the client MUST process the combined response as if it were a complete 200 (OK) response, including a Content-Length header field that reflects the complete length. Otherwise, the client MUST process the set of continuous ranges as one of the following: an incomplete 200 (OK) response if the combined response is a prefix of the representation, a single 206 (Partial Content) response containing "multipart/byteranges" content, or multiple 206 (Partial Content) responses, each with one continuous range that is indicated by a Content-Range header field. ### 15.4. Redirection 3xx The 3xx (Redirection) class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. There are several types of redirects: 1. Redirects that indicate this resource might be available at a different URI, as provided by the Location header field, as in the status codes 301 (Moved Permanently), 302 (Found), 307 (Temporary Redirect), and 308 (Permanent Redirect). 2. Redirection that offers a choice among matching resources capable of representing this resource, as in the 300 (Multiple Choices) status code. 3. Redirection to a different resource, identified by the Location header field, that can represent an indirect response to the request, as in the 303 (See Other) status code. 4. Redirection to a previously stored result, as in the 304 (Not Modified) status code. | \*Note:\* In HTTP/1.0, the status codes 301 (Moved Permanently) | and 302 (Found) were originally defined as method-preserving | ([HTTP/1.0], [Section 9.3](#section-9.3)) to match their implementation at | CERN; 303 (See Other) was defined for a redirection that | changed its method to GET. However, early user agents split on | whether to redirect POST requests as POST (according to then- | current specification) or as GET (the safer alternative when | redirected to a different site). Prevailing practice | eventually converged on changing the method to GET. 307 | (Temporary Redirect) and 308 (Permanent Redirect) [[RFC7538](https://datatracker.ietf.org/doc/html/rfc7538)] | were later added to unambiguously indicate method-preserving | redirects, and status codes 301 and 302 have been adjusted to | allow a POST request to be redirected as GET. If a Location header field ([Section 10.2.2](#section-10.2.2)) is provided, the user agent MAY automatically redirect its request to the URI referenced by the Location field value, even if the specific status code is not understood. Automatic redirection needs to be done with care for methods not known to be safe, as defined in [Section 9.2.1](#section-9.2.1), since the user might not wish to redirect an unsafe request. When automatically following a redirected request, the user agent SHOULD resend the original request message with the following modifications: 1. Replace the target URI with the URI referenced by the redirection response's Location header field value after resolving it relative to the original request's target URI. 2. Remove header fields that were automatically generated by the implementation, replacing them with updated values as appropriate to the new request. This includes: 1. Connection-specific header fields (see [Section 7.6.1](#section-7.6.1)), 2. Header fields specific to the client's proxy configuration, including (but not limited to) Proxy-Authorization, 3. Origin-specific header fields (if any), including (but not limited to) Host, 4. Validating header fields that were added by the implementation's cache (e.g., If-None-Match, If-Modified-Since), and 5. Resource-specific header fields, including (but not limited to) Referer, Origin, Authorization, and Cookie. 3. Consider removing header fields that were not automatically generated by the implementation (i.e., those present in the request because they were added by the calling context) where there are security implications; this includes but is not limited to Authorization and Cookie. 4. Change the request method according to the redirecting status code's semantics, if applicable. 5. If the request method has been changed to GET or HEAD, remove content-specific header fields, including (but not limited to) Content-Encoding, Content-Language, Content-Location, Content-Type, Content-Length, Digest, Last-Modified. A client SHOULD detect and intervene in cyclical redirections (i.e., "infinite" redirection loops). | \*Note:\* An earlier version of this specification recommended a | maximum of five redirections ([[RFC2068], Section 10.3](https://datatracker.ietf.org/doc/html/rfc2068#section-10.3)). | Content developers need to be aware that some clients might | implement such a fixed limitation. #### 15.4.1. 300 Multiple Choices The 300 (Multiple Choices) status code indicates that the target resource has more than one representation, each with its own more specific identifier, and information about the alternatives is being provided so that the user (or user agent) can select a preferred representation by redirecting its request to one or more of those identifiers. In other words, the server desires that the user agent engage in reactive negotiation to select the most appropriate representation(s) for its needs ([Section 12](#section-12)). If the server has a preferred choice, the server SHOULD generate a Location header field containing a preferred choice's URI reference. The user agent MAY use the Location field value for automatic redirection. For request methods other than HEAD, the server SHOULD generate content in the 300 response containing a list of representation metadata and URI reference(s) from which the user or user agent can choose the one most preferred. The user agent MAY make a selection from that list automatically if it understands the provided media type. A specific format for automatic selection is not defined by this specification because HTTP tries to remain orthogonal to the definition of its content. In practice, the representation is provided in some easily parsed format believed to be acceptable to the user agent, as determined by shared design or content negotiation, or in some commonly accepted hypertext format. A 300 response is heuristically cacheable; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [[CACHING](#ref-CACHING)]). | \*Note:\* The original proposal for the 300 status code defined | the URI header field as providing a list of alternative | representations, such that it would be usable for 200, 300, and | 406 responses and be transferred in responses to the HEAD | method. However, lack of deployment and disagreement over | syntax led to both URI and Alternates (a subsequent proposal) | being dropped from this specification. It is possible to | communicate the list as a Link header field value [[RFC8288](https://datatracker.ietf.org/doc/html/rfc8288)] | whose members have a relationship of "alternate", though | deployment is a chicken-and-egg problem. #### 15.4.2. 301 Moved Permanently The 301 (Moved Permanently) status code indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs. The server is suggesting that a user agent with link-editing capability can permanently replace references to the target URI with one of the new references sent by the server. However, this suggestion is usually ignored unless the user agent is actively editing references (e.g., engaged in authoring content), the connection is secured, and the origin server is a trusted authority for the content being edited. The server SHOULD generate a Location header field in the response containing a preferred URI reference for the new permanent URI. The user agent MAY use the Location field value for automatic redirection. The server's response content usually contains a short hypertext note with a hyperlink to the new URI(s). | \*Note:\* For historical reasons, a user agent MAY change the | request method from POST to GET for the subsequent request. If | this behavior is undesired, the 308 (Permanent Redirect) status | code can be used instead. A 301 response is heuristically cacheable; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [[CACHING](#ref-CACHING)]). #### 15.4.3. 302 Found The 302 (Found) status code indicates that the target resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client ought to continue to use the target URI for future requests. The server SHOULD generate a Location header field in the response containing a URI reference for the different URI. The user agent MAY use the Location field value for automatic redirection. The server's response content usually contains a short hypertext note with a hyperlink to the different URI(s). | \*Note:\* For historical reasons, a user agent MAY change the | request method from POST to GET for the subsequent request. If | this behavior is undesired, the 307 (Temporary Redirect) status | code can be used instead. #### 15.4.4. 303 See Other The 303 (See Other) status code indicates that the server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, which is intended to provide an indirect response to the original request. A user agent can perform a retrieval request targeting that URI (a GET or HEAD request if using HTTP), which might also be redirected, and present the eventual result as an answer to the original request. Note that the new URI in the Location header field is not considered equivalent to the target URI. This status code is applicable to any HTTP method. It is primarily used to allow the output of a POST action to redirect the user agent to a different resource, since doing so provides the information corresponding to the POST response as a resource that can be separately identified, bookmarked, and cached. A 303 response to a GET request indicates that the origin server does not have a representation of the target resource that can be transferred by the server over HTTP. However, the Location field value refers to a resource that is descriptive of the target resource, such that making a retrieval request on that other resource might result in a representation that is useful to recipients without implying that it represents the original target resource. Note that answers to the questions of what can be represented, what representations are adequate, and what might be a useful description are outside the scope of HTTP. Except for responses to a HEAD request, the representation of a 303 response ought to contain a short hypertext note with a hyperlink to the same URI reference provided in the Location header field. #### 15.4.5. 304 Not Modified The 304 (Not Modified) status code indicates that a conditional GET or HEAD request has been received and would have resulted in a 200 (OK) response if it were not for the fact that the condition evaluated to false. In other words, there is no need for the server to transfer a representation of the target resource because the request indicates that the client, which made the request conditional, already has a valid representation; the server is therefore redirecting the client to make use of that stored representation as if it were the content of a 200 (OK) response. The server generating a 304 response MUST generate any of the following header fields that would have been sent in a 200 (OK) response to the same request: \* Content-Location, Date, ETag, and Vary \* Cache-Control and Expires (see [[CACHING](#ref-CACHING)]) Since the goal of a 304 response is to minimize information transfer when the recipient already has one or more cached representations, a sender SHOULD NOT generate representation metadata other than the above listed fields unless said metadata exists for the purpose of guiding cache updates (e.g., Last-Modified might be useful if the response does not have an ETag field). Requirements on a cache that receives a 304 response are defined in Section 4.3.4 of [[CACHING](#ref-CACHING)]. If the conditional request originated with an outbound client, such as a user agent with its own cache sending a conditional GET to a shared proxy, then the proxy SHOULD forward the 304 response to that client. A 304 response is terminated by the end of the header section; it cannot contain content or trailers. #### 15.4.6. 305 Use Proxy The 305 (Use Proxy) status code was defined in a previous version of this specification and is now deprecated (Appendix B of [[RFC7231](https://datatracker.ietf.org/doc/html/rfc7231)]). #### 15.4.7. 306 (Unused) The 306 status code was defined in a previous version of this specification, is no longer used, and the code is reserved. #### 15.4.8. 307 Temporary Redirect The 307 (Temporary Redirect) status code indicates that the target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI. Since the redirection can change over time, the client ought to continue using the original target URI for future requests. The server SHOULD generate a Location header field in the response containing a URI reference for the different URI. The user agent MAY use the Location field value for automatic redirection. The server's response content usually contains a short hypertext note with a hyperlink to the different URI(s). #### 15.4.9. 308 Permanent Redirect The 308 (Permanent Redirect) status code indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs. The server is suggesting that a user agent with link-editing capability can permanently replace references to the target URI with one of the new references sent by the server. However, this suggestion is usually ignored unless the user agent is actively editing references (e.g., engaged in authoring content), the connection is secured, and the origin server is a trusted authority for the content being edited. The server SHOULD generate a Location header field in the response containing a preferred URI reference for the new permanent URI. The user agent MAY use the Location field value for automatic redirection. The server's response content usually contains a short hypertext note with a hyperlink to the new URI(s). A 308 response is heuristically cacheable; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [[CACHING](#ref-CACHING)]). | \*Note:\* This status code is much younger (June 2014) than its | sibling codes and thus might not be recognized everywhere. See | [Section 4 of [RFC7538]](https://datatracker.ietf.org/doc/html/rfc7538#section-4) for deployment considerations. ### 15.5. Client Error 4xx The 4xx (Client Error) class of status code indicates that the client seems to have erred. Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents SHOULD display any included representation to the user. #### 15.5.1. 400 Bad Request The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). #### 15.5.2. 401 Unauthorized The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field ([Section 11.6.1](#section-11.6.1)) containing at least one challenge applicable to the target resource. If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The user agent MAY repeat the request with a new or replaced Authorization header field ([Section 11.6.2](#section-11.6.2)). If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user agent SHOULD present the enclosed representation to the user, since it usually contains relevant diagnostic information. #### 15.5.3. 402 Payment Required The 402 (Payment Required) status code is reserved for future use. #### 15.5.4. 403 Forbidden The 403 (Forbidden) status code indicates that the server understood the request but refuses to fulfill it. A server that wishes to make public why the request has been forbidden can describe that reason in the response content (if any). If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT automatically repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials. An origin server that wishes to "hide" the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found). #### 15.5.5. 404 Not Found The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists. A 404 status code does not indicate whether this lack of representation is temporary or permanent; the 410 (Gone) status code is preferred over 404 if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent. A 404 response is heuristically cacheable; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [[CACHING](#ref-CACHING)]). #### 15.5.6. 405 Method Not Allowed The 405 (Method Not Allowed) status code indicates that the method received in the request-line is known by the origin server but not supported by the target resource. The origin server MUST generate an Allow header field in a 405 response containing a list of the target resource's currently supported methods. A 405 response is heuristically cacheable; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [[CACHING](#ref-CACHING)]). #### 15.5.7. 406 Not Acceptable The 406 (Not Acceptable) status code indicates that the target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request ([Section 12.1](#section-12.1)), and the server is unwilling to supply a default representation. The server SHOULD generate content containing a list of available representation characteristics and corresponding resource identifiers from which the user or user agent can choose the one most appropriate. A user agent MAY automatically select the most appropriate choice from that list. However, this specification does not define any standard for such automatic selection, as described in [Section 15.4.1](#section-15.4.1). #### 15.5.8. 407 Proxy Authentication Required The 407 (Proxy Authentication Required) status code is similar to 401 (Unauthorized), but it indicates that the client needs to authenticate itself in order to use a proxy for this request. The proxy MUST send a Proxy-Authenticate header field ([Section 11.7.1](#section-11.7.1)) containing a challenge applicable to that proxy for the request. The client MAY repeat the request with a new or replaced Proxy-Authorization header field ([Section 11.7.2](#section-11.7.2)). #### 15.5.9. 408 Request Timeout The 408 (Request Timeout) status code indicates that the server did not receive a complete request message within the time that it was prepared to wait. If the client has an outstanding request in transit, it MAY repeat that request. If the current connection is not usable (e.g., as it would be in HTTP/1.1 because request delimitation is lost), a new connection will be used. #### 15.5.10. 409 Conflict The 409 (Conflict) status code indicates that the request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request. The server SHOULD generate content that includes enough information for a user to recognize the source of the conflict. Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the representation being PUT included changes to a resource that conflict with those made by an earlier (third-party) request, the origin server might use a 409 response to indicate that it can't complete the request. In this case, the response representation would likely contain information useful for merging the differences based on the revision history. #### 15.5.11. 410 Gone The 410 (Gone) status code indicates that access to the target resource is no longer available at the origin server and that this condition is likely to be permanent. If the origin server does not know, or has no facility to determine, whether or not the condition is permanent, the status code 404 (Not Found) ought to be used instead. The 410 response is primarily intended to assist the task of web maintenance by notifying the recipient that the resource is intentionally unavailable and that the server owners desire that remote links to that resource be removed. Such an event is common for limited-time, promotional services and for resources belonging to individuals no longer associated with the origin server's site. It is not necessary to mark all permanently unavailable resources as "gone" or to keep the mark for any length of time -- that is left to the discretion of the server owner. A 410 response is heuristically cacheable; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [[CACHING](#ref-CACHING)]). #### 15.5.12. 411 Length Required The 411 (Length Required) status code indicates that the server refuses to accept the request without a defined Content-Length ([Section 8.6](#section-8.6)). The client MAY repeat the request if it adds a valid Content-Length header field containing the length of the request content. #### 15.5.13. 412 Precondition Failed The 412 (Precondition Failed) status code indicates that one or more conditions given in the request header fields evaluated to false when tested on the server ([Section 13](#section-13)). This response status code allows the client to place preconditions on the current resource state (its current representations and metadata) and, thus, prevent the request method from being applied if the target resource is in an unexpected state. #### 15.5.14. 413 Content Too Large The 413 (Content Too Large) status code indicates that the server is refusing to process a request because the request content is larger than the server is willing or able to process. The server MAY terminate the request, if the protocol version in use allows it; otherwise, the server MAY close the connection. If the condition is temporary, the server SHOULD generate a Retry-After header field to indicate that it is temporary and after what time the client MAY try again. #### 15.5.15. 414 URI Too Long The 414 (URI Too Long) status code indicates that the server is refusing to service the request because the target URI is longer than the server is willing to interpret. This rare condition is only likely to occur when a client has improperly converted a POST request to a GET request with long query information, when the client has descended into an infinite loop of redirection (e.g., a redirected URI prefix that points to a suffix of itself) or when the server is under attack by a client attempting to exploit potential security holes. A 414 response is heuristically cacheable; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [[CACHING](#ref-CACHING)]). #### 15.5.16. 415 Unsupported Media Type The 415 (Unsupported Media Type) status code indicates that the origin server is refusing to service the request because the content is in a format not supported by this method on the target resource. The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly. If the problem was caused by an unsupported content coding, the Accept-Encoding response header field ([Section 12.5.3](#section-12.5.3)) ought to be used to indicate which (if any) content codings would have been accepted in the request. On the other hand, if the cause was an unsupported media type, the Accept response header field ([Section 12.5.1](#section-12.5.1)) can be used to indicate which media types would have been accepted in the request. #### 15.5.17. 416 Range Not Satisfiable The 416 (Range Not Satisfiable) status code indicates that the set of ranges in the request's Range header field ([Section 14.2](#section-14.2)) has been rejected either because none of the requested ranges are satisfiable or because the client has requested an excessive number of small or overlapping ranges (a potential denial of service attack). Each range unit defines what is required for its own range sets to be satisfiable. For example, [Section 14.1.2](#section-14.1.2) defines what makes a bytes range set satisfiable. A server that generates a 416 response to a byte-range request SHOULD generate a Content-Range header field specifying the current length of the selected representation ([Section 14.4](#section-14.4)). For example: HTTP/1.1 416 Range Not Satisfiable Date: Fri, 20 Jan 2012 15:41:54 GMT Content-Range: bytes \*/47022 | \*Note:\* Because servers are free to ignore Range, many | implementations will respond with the entire selected | representation in a 200 (OK) response. That is partly because | most clients are prepared to receive a 200 (OK) to complete the | task (albeit less efficiently) and partly because clients might | not stop making an invalid range request until they have | received a complete representation. Thus, clients cannot | depend on receiving a 416 (Range Not Satisfiable) response even | when it is most appropriate. #### 15.5.18. 417 Expectation Failed The 417 (Expectation Failed) status code indicates that the expectation given in the request's Expect header field ([Section 10.1.1](#section-10.1.1)) could not be met by at least one of the inbound servers. #### 15.5.19. 418 (Unused) [RFC2324] was an April 1 RFC that lampooned the various ways HTTP was abused; one such abuse was the definition of an application-specific 418 status code, which has been deployed as a joke often enough for the code to be unusable for any future use. Therefore, the 418 status code is reserved in the IANA HTTP Status Code Registry. This indicates that the status code cannot be assigned to other applications currently. If future circumstances require its use (e.g., exhaustion of 4NN status codes), it can be re- assigned to another use. #### 15.5.20. 421 Misdirected Request The 421 (Misdirected Request) status code indicates that the request was directed at a server that is unable or unwilling to produce an authoritative response for the target URI. An origin server (or gateway acting on behalf of the origin server) sends 421 to reject a target URI that does not match an origin for which the server has been configured ([Section 4.3.1](#section-4.3.1)) or does not match the connection context over which the request was received ([Section 7.4](#section-7.4)). A client that receives a 421 (Misdirected Request) response MAY retry the request, whether or not the request method is idempotent, over a different connection, such as a fresh connection specific to the target resource's origin, or via an alternative service [[ALTSVC](#ref-ALTSVC)]. A proxy MUST NOT generate a 421 response. #### 15.5.21. 422 Unprocessable Content The 422 (Unprocessable Content) status code indicates that the server understands the content type of the request content (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request content is correct, but it was unable to process the contained instructions. For example, this status code can be sent if an XML request content contains well-formed (i.e., syntactically correct), but semantically erroneous XML instructions. #### 15.5.22. 426 Upgrade Required The 426 (Upgrade Required) status code indicates that the server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server MUST send an Upgrade header field in a 426 response to indicate the required protocol(s) ([Section 7.8](#section-7.8)). Example: HTTP/1.1 426 Upgrade Required Upgrade: HTTP/3.0 Connection: Upgrade Content-Length: 53 Content-Type: text/plain This service requires use of the HTTP/3.0 protocol. ### 15.6. Server Error 5xx The 5xx (Server Error) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method. Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition. A user agent SHOULD display any included representation to the user. These status codes are applicable to any request method. #### 15.6.1. 500 Internal Server Error The 500 (Internal Server Error) status code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. #### 15.6.2. 501 Not Implemented The 501 (Not Implemented) status code indicates that the server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource. A 501 response is heuristically cacheable; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [[CACHING](#ref-CACHING)]). #### 15.6.3. 502 Bad Gateway The 502 (Bad Gateway) status code indicates that the server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request. #### 15.6.4. 503 Service Unavailable The 503 (Service Unavailable) status code indicates that the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. The server MAY send a Retry-After header field ([Section 10.2.3](#section-10.2.3)) to suggest an appropriate amount of time for the client to wait before retrying the request. | \*Note:\* The existence of the 503 status code does not imply | that a server has to use it when becoming overloaded. Some | servers might simply refuse the connection. #### 15.6.5. 504 Gateway Timeout The 504 (Gateway Timeout) status code indicates that the server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request. #### 15.6.6. 505 HTTP Version Not Supported The 505 (HTTP Version Not Supported) status code indicates that the server does not support, or refuses to support, the major version of HTTP that was used in the request message. The server is indicating that it is unable or unwilling to complete the request using the same major version as the client, as described in [Section 2.5](#section-2.5), other than with this error message. The server SHOULD generate a representation for the 505 response that describes why that version is not supported and what other protocols are supported by that server. 16. Extending HTTP ------------------ HTTP defines a number of generic extension points that can be used to introduce capabilities to the protocol without introducing a new version, including methods, status codes, field names, and further extensibility points within defined fields, such as authentication schemes and cache directives (see Cache-Control extensions in Section 5.2.3 of [[CACHING](#ref-CACHING)]). Because the semantics of HTTP are not versioned, these extension points are persistent; the version of the protocol in use does not affect their semantics. Version-independent extensions are discouraged from depending on or interacting with the specific version of the protocol in use. When this is unavoidable, careful consideration needs to be given to how the extension can interoperate across versions. Additionally, specific versions of HTTP might have their own extensibility points, such as transfer codings in HTTP/1.1 ([Section 6.1](#section-6.1) of [HTTP/1.1]) and HTTP/2 SETTINGS or frame types ([HTTP/2]). These extension points are specific to the version of the protocol they occur within. Version-specific extensions cannot override or modify the semantics of a version-independent mechanism or extension point (like a method or header field) without explicitly being allowed by that protocol element. For example, the CONNECT method ([Section 9.3.6](#section-9.3.6)) allows this. These guidelines assure that the protocol operates correctly and predictably, even when parts of the path implement different versions of HTTP. ### 16.1. Method Extensibility #### 16.1.1. Method Registry The "Hypertext Transfer Protocol (HTTP) Method Registry", maintained by IANA at <<https://www.iana.org/assignments/http-methods>>, registers method names. HTTP method registrations MUST include the following fields: \* Method Name (see [Section 9](#section-9)) \* Safe ("yes" or "no", see [Section 9.2.1](#section-9.2.1)) \* Idempotent ("yes" or "no", see [Section 9.2.2](#section-9.2.2)) \* Pointer to specification text Values to be added to this namespace require IETF Review (see [[RFC8126], Section 4.8](https://datatracker.ietf.org/doc/html/rfc8126#section-4.8)). #### 16.1.2. Considerations for New Methods Standardized methods are generic; that is, they are potentially applicable to any resource, not just one particular media type, kind of resource, or application. As such, it is preferred that new methods be registered in a document that isn't specific to a single application or data format, since orthogonal technologies deserve orthogonal specification. Since message parsing ([Section 6](#section-6)) needs to be independent of method semantics (aside from responses to HEAD), definitions of new methods cannot change the parsing algorithm or prohibit the presence of content on either the request or the response message. Definitions of new methods can specify that only a zero-length content is allowed by requiring a Content-Length header field with a value of "0". Likewise, new methods cannot use the special host:port and asterisk forms of request target that are allowed for CONNECT and OPTIONS, respectively ([Section 7.1](#section-7.1)). A full URI in absolute form is needed for the target URI, which means either the request target needs to be sent in absolute form or the target URI will be reconstructed from the request context in the same way it is for other methods. A new method definition needs to indicate whether it is safe ([Section 9.2.1](#section-9.2.1)), idempotent ([Section 9.2.2](#section-9.2.2)), cacheable ([Section 9.2.3](#section-9.2.3)), what semantics are to be associated with the request content (if any), and what refinements the method makes to header field or status code semantics. If the new method is cacheable, its definition ought to describe how, and under what conditions, a cache can store a response and use it to satisfy a subsequent request. The new method ought to describe whether it can be made conditional ([Section 13.1](#section-13.1)) and, if so, how a server responds when the condition is false. Likewise, if the new method might have some use for partial response semantics ([Section 14.2](#section-14.2)), it ought to document this, too. | \*Note:\* Avoid defining a method name that starts with "M-", | since that prefix might be misinterpreted as having the | semantics assigned to it by [[RFC2774](https://datatracker.ietf.org/doc/html/rfc2774)]. ### 16.2. Status Code Extensibility #### 16.2.1. Status Code Registry The "Hypertext Transfer Protocol (HTTP) Status Code Registry", maintained by IANA at <[https://www.iana.org/assignments/http-status-](https://www.iana.org/assignments/http-status-codes) [codes](https://www.iana.org/assignments/http-status-codes)>, registers status code numbers. A registration MUST include the following fields: \* Status Code (3 digits) \* Short Description \* Pointer to specification text Values to be added to the HTTP status code namespace require IETF Review (see [[RFC8126], Section 4.8](https://datatracker.ietf.org/doc/html/rfc8126#section-4.8)). #### 16.2.2. Considerations for New Status Codes When it is necessary to express semantics for a response that are not defined by current status codes, a new status code can be registered. Status codes are generic; they are potentially applicable to any resource, not just one particular media type, kind of resource, or application of HTTP. As such, it is preferred that new status codes be registered in a document that isn't specific to a single application. New status codes are required to fall under one of the categories defined in [Section 15](#section-15). To allow existing parsers to process the response message, new status codes cannot disallow content, although they can mandate a zero-length content. Proposals for new status codes that are not yet widely deployed ought to avoid allocating a specific number for the code until there is clear consensus that it will be registered; instead, early drafts can use a notation such as "4NN", or "3N0" .. "3N9", to indicate the class of the proposed status code(s) without consuming a number prematurely. The definition of a new status code ought to explain the request conditions that would cause a response containing that status code (e.g., combinations of request header fields and/or method(s)) along with any dependencies on response header fields (e.g., what fields are required, what fields can modify the semantics, and what field semantics are further refined when used with the new status code). By default, a status code applies only to the request corresponding to the response it occurs within. If a status code applies to a larger scope of applicability -- for example, all requests to the resource in question or all requests to a server -- this must be explicitly specified. When doing so, it should be noted that not all clients can be expected to consistently apply a larger scope because they might not understand the new status code. The definition of a new final status code ought to specify whether or not it is heuristically cacheable. Note that any response with a final status code can be cached if the response has explicit freshness information. A status code defined as heuristically cacheable is allowed to be cached without explicit freshness information. Likewise, the definition of a status code can place constraints upon cache behavior if the must-understand cache directive is used. See [[CACHING](#ref-CACHING)] for more information. Finally, the definition of a new status code ought to indicate whether the content has any implied association with an identified resource ([Section 6.4.2](#section-6.4.2)). ### 16.3. Field Extensibility HTTP's most widely used extensibility point is the definition of new header and trailer fields. New fields can be defined such that, when they are understood by a recipient, they override or enhance the interpretation of previously defined fields, define preconditions on request evaluation, or refine the meaning of responses. However, defining a field doesn't guarantee its deployment or recognition by recipients. Most fields are designed with the expectation that a recipient can safely ignore (but forward downstream) any field not recognized. In other cases, the sender's ability to understand a given field might be indicated by its prior communication, perhaps in the protocol version or fields that it sent in prior messages, or its use of a specific media type. Likewise, direct inspection of support might be possible through an OPTIONS request or by interacting with a defined well-known URI [[RFC8615](https://datatracker.ietf.org/doc/html/rfc8615)] if such inspection is defined along with the field being introduced. #### 16.3.1. Field Name Registry The "Hypertext Transfer Protocol (HTTP) Field Name Registry" defines the namespace for HTTP field names. Any party can request registration of an HTTP field. See [Section 16.3.2](#section-16.3.2) for considerations to take into account when creating a new HTTP field. The "Hypertext Transfer Protocol (HTTP) Field Name Registry" is located at <<https://www.iana.org/assignments/http-fields/>>. Registration requests can be made by following the instructions located there or by sending an email to the "[email protected]" mailing list. Field names are registered on the advice of a designated expert (appointed by the IESG or their delegate). Fields with the status 'permanent' are Specification Required ([[RFC8126], Section 4.6](https://datatracker.ietf.org/doc/html/rfc8126#section-4.6)). Registration requests consist of the following information: Field name: The requested field name. It MUST conform to the field-name syntax defined in [Section 5.1](#section-5.1), and it SHOULD be restricted to just letters, digits, and hyphen ('-') characters, with the first character being a letter. Status: "permanent", "provisional", "deprecated", or "obsoleted". Specification document(s): Reference to the document that specifies the field, preferably including a URI that can be used to retrieve a copy of the document. Optional but encouraged for provisional registrations. An indication of the relevant section(s) can also be included, but is not required. And optionally: Comments: Additional information, such as about reserved entries. The expert(s) can define additional fields to be collected in the registry, in consultation with the community. Standards-defined names have a status of "permanent". Other names can also be registered as permanent if the expert(s) finds that they are in use, in consultation with the community. Other names should be registered as "provisional". Provisional entries can be removed by the expert(s) if -- in consultation with the community -- the expert(s) find that they are not in use. The expert(s) can change a provisional entry's status to permanent at any time. Note that names can be registered by third parties (including the expert(s)) if the expert(s) determines that an unregistered name is widely deployed and not likely to be registered in a timely manner otherwise. #### 16.3.2. Considerations for New Fields HTTP header and trailer fields are a widely used extension point for the protocol. While they can be used in an ad hoc fashion, fields that are intended for wider use need to be carefully documented to ensure interoperability. In particular, authors of specifications defining new fields are advised to consider and, where appropriate, document the following aspects: \* Under what conditions the field can be used; e.g., only in responses or requests, in all messages, only on responses to a particular request method, etc. \* Whether the field semantics are further refined by their context, such as their use with certain request methods or status codes. \* The scope of applicability for the information conveyed. By default, fields apply only to the message they are associated with, but some response fields are designed to apply to all representations of a resource, the resource itself, or an even broader scope. Specifications that expand the scope of a response field will need to carefully consider issues such as content negotiation, the time period of applicability, and (in some cases) multi-tenant server deployments. \* Under what conditions intermediaries are allowed to insert, delete, or modify the field's value. \* If the field is allowable in trailers; by default, it will not be (see [Section 6.5.1](#section-6.5.1)). \* Whether it is appropriate or even required to list the field name in the Connection header field (i.e., if the field is to be hop- by-hop; see [Section 7.6.1](#section-7.6.1)). \* Whether the field introduces any additional security considerations, such as disclosure of privacy-related data. Request header fields have additional considerations that need to be documented if the default behavior is not appropriate: \* If it is appropriate to list the field name in a Vary response header field (e.g., when the request header field is used by an origin server's content selection algorithm; see [Section 12.5.5](#section-12.5.5)). \* If the field is intended to be stored when received in a PUT request (see [Section 9.3.4](#section-9.3.4)). \* If the field ought to be removed when automatically redirecting a request due to security concerns (see [Section 15.4](#section-15.4)). ##### 16.3.2.1. Considerations for New Field Names Authors of specifications defining new fields are advised to choose a short but descriptive field name. Short names avoid needless data transmission; descriptive names avoid confusion and "squatting" on names that might have broader uses. To that end, limited-use fields (such as a header confined to a single application or use case) are encouraged to use a name that includes that use (or an abbreviation) as a prefix; for example, if the Foo Application needs a Description field, it might use "Foo- Desc"; "Description" is too generic, and "Foo-Description" is needlessly long. While the field-name syntax is defined to allow any token character, in practice some implementations place limits on the characters they accept in field-names. To be interoperable, new field names SHOULD constrain themselves to alphanumeric characters, "-", and ".", and SHOULD begin with a letter. For example, the underscore ("\_") character can be problematic when passed through non-HTTP gateway interfaces (see [Section 17.10](#section-17.10)). Field names ought not be prefixed with "X-"; see [[BCP178](#ref-BCP178)] for further information. Other prefixes are sometimes used in HTTP field names; for example, "Accept-" is used in many content negotiation headers, and "Content-" is used as explained in [Section 6.4](#section-6.4). These prefixes are only an aid to recognizing the purpose of a field and do not trigger automatic processing. ##### 16.3.2.2. Considerations for New Field Values A major task in the definition of a new HTTP field is the specification of the field value syntax: what senders should generate, and how recipients should infer semantics from what is received. Authors are encouraged (but not required) to use either the ABNF rules in this specification or those in [[RFC8941](https://datatracker.ietf.org/doc/html/rfc8941)] to define the syntax of new field values. Authors are advised to carefully consider how the combination of multiple field lines will impact them (see [Section 5.3](#section-5.3)). Because senders might erroneously send multiple values, and both intermediaries and HTTP libraries can perform combination automatically, this applies to all field values -- even when only a single value is anticipated. Therefore, authors are advised to delimit or encode values that contain commas (e.g., with the quoted-string rule of [Section 5.6.4](#section-5.6.4), the String data type of [[RFC8941](https://datatracker.ietf.org/doc/html/rfc8941)], or a field-specific encoding). This ensures that commas within field data are not confused with the commas that delimit a list value. For example, the Content-Type field value only allows commas inside quoted strings, which can be reliably parsed even when multiple values are present. The Location field value provides a counter- example that should not be emulated: because URIs can include commas, it is not possible to reliably distinguish between a single value that includes a comma from two values. Authors of fields with a singleton value (see [Section 5.5](#section-5.5)) are additionally advised to document how to treat messages where the multiple members are present (a sensible default would be to ignore the field, but this might not always be the right choice). ### 16.4. Authentication Scheme Extensibility #### 16.4.1. Authentication Scheme Registry The "Hypertext Transfer Protocol (HTTP) Authentication Scheme Registry" defines the namespace for the authentication schemes in challenges and credentials. It is maintained at <<https://www.iana.org/assignments/http-authschemes>>. Registrations MUST include the following fields: \* Authentication Scheme Name \* Pointer to specification text \* Notes (optional) Values to be added to this namespace require IETF Review (see [[RFC8126], Section 4.8](https://datatracker.ietf.org/doc/html/rfc8126#section-4.8)). #### 16.4.2. Considerations for New Authentication Schemes There are certain aspects of the HTTP Authentication framework that put constraints on how new authentication schemes can work: \* HTTP authentication is presumed to be stateless: all of the information necessary to authenticate a request MUST be provided in the request, rather than be dependent on the server remembering prior requests. Authentication based on, or bound to, the underlying connection is outside the scope of this specification and inherently flawed unless steps are taken to ensure that the connection cannot be used by any party other than the authenticated user (see [Section 3.3](#section-3.3)). \* The authentication parameter "realm" is reserved for defining protection spaces as described in [Section 11.5](#section-11.5). New schemes MUST NOT use it in a way incompatible with that definition. \* The "token68" notation was introduced for compatibility with existing authentication schemes and can only be used once per challenge or credential. Thus, new schemes ought to use the auth- param syntax instead, because otherwise future extensions will be impossible. \* The parsing of challenges and credentials is defined by this specification and cannot be modified by new authentication schemes. When the auth-param syntax is used, all parameters ought to support both token and quoted-string syntax, and syntactical constraints ought to be defined on the field value after parsing (i.e., quoted-string processing). This is necessary so that recipients can use a generic parser that applies to all authentication schemes. \*Note:\* The fact that the value syntax for the "realm" parameter is restricted to quoted-string was a bad design choice not to be repeated for new parameters. \* Definitions of new schemes ought to define the treatment of unknown extension parameters. In general, a "must-ignore" rule is preferable to a "must-understand" rule, because otherwise it will be hard to introduce new parameters in the presence of legacy recipients. Furthermore, it's good to describe the policy for defining new parameters (such as "update the specification" or "use this registry"). \* Authentication schemes need to document whether they are usable in origin-server authentication (i.e., using WWW-Authenticate), and/ or proxy authentication (i.e., using Proxy-Authenticate). \* The credentials carried in an Authorization header field are specific to the user agent and, therefore, have the same effect on HTTP caches as the "private" cache response directive (Section 5.2.2.7 of [[CACHING](#ref-CACHING)]), within the scope of the request in which they appear. Therefore, new authentication schemes that choose not to carry credentials in the Authorization header field (e.g., using a newly defined header field) will need to explicitly disallow caching, by mandating the use of cache response directives (e.g., "private"). \* Schemes using Authentication-Info, Proxy-Authentication-Info, or any other authentication related response header field need to consider and document the related security considerations (see [Section 17.16.4](#section-17.16.4)). ### 16.5. Range Unit Extensibility #### 16.5.1. Range Unit Registry The "HTTP Range Unit Registry" defines the namespace for the range unit names and refers to their corresponding specifications. It is maintained at <<https://www.iana.org/assignments/http-parameters>>. Registration of an HTTP Range Unit MUST include the following fields: \* Name \* Description \* Pointer to specification text Values to be added to this namespace require IETF Review (see [[RFC8126], Section 4.8](https://datatracker.ietf.org/doc/html/rfc8126#section-4.8)). #### 16.5.2. Considerations for New Range Units Other range units, such as format-specific boundaries like pages, sections, records, rows, or time, are potentially usable in HTTP for application-specific purposes, but are not commonly used in practice. Implementors of alternative range units ought to consider how they would work with content codings and general-purpose intermediaries. ### 16.6. Content Coding Extensibility #### 16.6.1. Content Coding Registry The "HTTP Content Coding Registry", maintained by IANA at <<https://www.iana.org/assignments/http-parameters/>>, registers content-coding names. Content coding registrations MUST include the following fields: \* Name \* Description \* Pointer to specification text Names of content codings MUST NOT overlap with names of transfer codings (per the "HTTP Transfer Coding Registry" located at <<https://www.iana.org/assignments/http-parameters/>>) unless the encoding transformation is identical (as is the case for the compression codings defined in [Section 8.4.1](#section-8.4.1)). Values to be added to this namespace require IETF Review (see [Section 4.8 of [RFC8126]](https://datatracker.ietf.org/doc/html/rfc8126#section-4.8)) and MUST conform to the purpose of content coding defined in [Section 8.4.1](#section-8.4.1). #### 16.6.2. Considerations for New Content Codings New content codings ought to be self-descriptive whenever possible, with optional parameters discoverable within the coding format itself, rather than rely on external metadata that might be lost during transit. ### 16.7. Upgrade Token Registry The "Hypertext Transfer Protocol (HTTP) Upgrade Token Registry" defines the namespace for protocol-name tokens used to identify protocols in the Upgrade header field. The registry is maintained at <<https://www.iana.org/assignments/http-upgrade-tokens>>. Each registered protocol name is associated with contact information and an optional set of specifications that details how the connection will be processed after it has been upgraded. Registrations happen on a "First Come First Served" basis (see [Section 4.4 of [RFC8126]](https://datatracker.ietf.org/doc/html/rfc8126#section-4.4)) and are subject to the following rules: 1. A protocol-name token, once registered, stays registered forever. 2. A protocol-name token is case-insensitive and registered with the preferred case to be generated by senders. 3. The registration MUST name a responsible party for the registration. 4. The registration MUST name a point of contact. 5. The registration MAY name a set of specifications associated with that token. Such specifications need not be publicly available. 6. The registration SHOULD name a set of expected "protocol-version" tokens associated with that token at the time of registration. 7. The responsible party MAY change the registration at any time. The IANA will keep a record of all such changes, and make them available upon request. 8. The IESG MAY reassign responsibility for a protocol token. This will normally only be used in the case when a responsible party cannot be contacted. 17. Security Considerations --------------------------- This section is meant to inform developers, information providers, and users of known security concerns relevant to HTTP semantics and its use for transferring information over the Internet. Considerations related to caching are discussed in Section 7 of [[CACHING](#ref-CACHING)], and considerations related to HTTP/1.1 message syntax and parsing are discussed in [Section 11](#section-11) of [HTTP/1.1]. The list of considerations below is not exhaustive. Most security concerns related to HTTP semantics are about securing server-side applications (code behind the HTTP interface), securing user agent processing of content received via HTTP, or secure use of the Internet in general, rather than security of the protocol. The security considerations for URIs, which are fundamental to HTTP operation, are discussed in Section 7 of [[URI](#ref-URI)]. Various organizations maintain topical information and links to current research on Web application security (e.g., [[OWASP](#ref-OWASP)]). ### 17.1. Establishing Authority HTTP relies on the notion of an "authoritative response": a response that has been determined by (or at the direction of) the origin server identified within the target URI to be the most appropriate response for that request given the state of the target resource at the time of response message origination. When a registered name is used in the authority component, the "http" URI scheme ([Section 4.2.1](#section-4.2.1)) relies on the user's local name resolution service to determine where it can find authoritative responses. This means that any attack on a user's network host table, cached names, or name resolution libraries becomes an avenue for attack on establishing authority for "http" URIs. Likewise, the user's choice of server for Domain Name Service (DNS), and the hierarchy of servers from which it obtains resolution results, could impact the authenticity of address mappings; DNS Security Extensions (DNSSEC, [[RFC4033](https://datatracker.ietf.org/doc/html/rfc4033)]) are one way to improve authenticity, as are the various mechanisms for making DNS requests over more secure transfer protocols. Furthermore, after an IP address is obtained, establishing authority for an "http" URI is vulnerable to attacks on Internet Protocol routing. The "https" scheme ([Section 4.2.2](#section-4.2.2)) is intended to prevent (or at least reveal) many of these potential attacks on establishing authority, provided that the negotiated connection is secured and the client properly verifies that the communicating server's identity matches the target URI's authority component ([Section 4.3.4](#section-4.3.4)). Correctly implementing such verification can be difficult (see [[Georgiev](#ref-Georgiev)]). Authority for a given origin server can be delegated through protocol extensions; for example, [[ALTSVC](#ref-ALTSVC)]. Likewise, the set of servers for which a connection is considered authoritative can be changed with a protocol extension like [[RFC8336](https://datatracker.ietf.org/doc/html/rfc8336)]. Providing a response from a non-authoritative source, such as a shared proxy cache, is often useful to improve performance and availability, but only to the extent that the source can be trusted or the distrusted response can be safely used. Unfortunately, communicating authority to users can be difficult. For example, "phishing" is an attack on the user's perception of authority, where that perception can be misled by presenting similar branding in hypertext, possibly aided by userinfo obfuscating the authority component (see [Section 4.2.1](#section-4.2.1)). User agents can reduce the impact of phishing attacks by enabling users to easily inspect a target URI prior to making an action, by prominently distinguishing (or rejecting) userinfo when present, and by not sending stored credentials and cookies when the referring document is from an unknown or untrusted source. ### 17.2. Risks of Intermediaries HTTP intermediaries are inherently situated for on-path attacks. Compromise of the systems on which the intermediaries run can result in serious security and privacy problems. Intermediaries might have access to security-related information, personal information about individual users and organizations, and proprietary information belonging to users and content providers. A compromised intermediary, or an intermediary implemented or configured without regard to security and privacy considerations, might be used in the commission of a wide range of potential attacks. Intermediaries that contain a shared cache are especially vulnerable to cache poisoning attacks, as described in Section 7 of [[CACHING](#ref-CACHING)]. Implementers need to consider the privacy and security implications of their design and coding decisions, and of the configuration options they provide to operators (especially the default configuration). Intermediaries are no more trustworthy than the people and policies under which they operate; HTTP cannot solve this problem. ### 17.3. Attacks Based on File and Path Names Origin servers frequently make use of their local file system to manage the mapping from target URI to resource representations. Most file systems are not designed to protect against malicious file or path names. Therefore, an origin server needs to avoid accessing names that have a special significance to the system when mapping the target resource to files, folders, or directories. For example, UNIX, Microsoft Windows, and other operating systems use ".." as a path component to indicate a directory level above the current one, and they use specially named paths or file names to send data to system devices. Similar naming conventions might exist within other types of storage systems. Likewise, local storage systems have an annoying tendency to prefer user-friendliness over security when handling invalid or unexpected characters, recomposition of decomposed characters, and case-normalization of case-insensitive names. Attacks based on such special names tend to focus on either denial- of-service (e.g., telling the server to read from a COM port) or disclosure of configuration and source files that are not meant to be served. ### 17.4. Attacks Based on Command, Code, or Query Injection Origin servers often use parameters within the URI as a means of identifying system services, selecting database entries, or choosing a data source. However, data received in a request cannot be trusted. An attacker could construct any of the request data elements (method, target URI, header fields, or content) to contain data that might be misinterpreted as a command, code, or query when passed through a command invocation, language interpreter, or database interface. For example, SQL injection is a common attack wherein additional query language is inserted within some part of the target URI or header fields (e.g., Host, Referer, etc.). If the received data is used directly within a SELECT statement, the query language might be interpreted as a database command instead of a simple string value. This type of implementation vulnerability is extremely common, in spite of being easy to prevent. In general, resource implementations ought to avoid use of request data in contexts that are processed or interpreted as instructions. Parameters ought to be compared to fixed strings and acted upon as a result of that comparison, rather than passed through an interface that is not prepared for untrusted data. Received data that isn't based on fixed parameters ought to be carefully filtered or encoded to avoid being misinterpreted. Similar considerations apply to request data when it is stored and later processed, such as within log files, monitoring tools, or when included within a data format that allows embedded scripts. ### 17.5. Attacks via Protocol Element Length Because HTTP uses mostly textual, character-delimited fields, parsers are often vulnerable to attacks based on sending very long (or very slow) streams of data, particularly where an implementation is expecting a protocol element with no predefined length ([Section 2.3](#section-2.3)). To promote interoperability, specific recommendations are made for minimum size limits on fields ([Section 5.4](#section-5.4)). These are minimum recommendations, chosen to be supportable even by implementations with limited resources; it is expected that most implementations will choose substantially higher limits. A server can reject a message that has a target URI that is too long ([Section 15.5.15](#section-15.5.15)) or request content that is too large ([Section 15.5.14](#section-15.5.14)). Additional status codes related to capacity limits have been defined by extensions to HTTP [[RFC6585](https://datatracker.ietf.org/doc/html/rfc6585)]. Recipients ought to carefully limit the extent to which they process other protocol elements, including (but not limited to) request methods, response status phrases, field names, numeric values, and chunk lengths. Failure to limit such processing can result in arbitrary code execution due to buffer or arithmetic overflows, and increased vulnerability to denial-of-service attacks. ### 17.6. Attacks Using Shared-Dictionary Compression Some attacks on encrypted protocols use the differences in size created by dynamic compression to reveal confidential information; for example, [[BREACH](#ref-BREACH)]. These attacks rely on creating a redundancy between attacker-controlled content and the confidential information, such that a dynamic compression algorithm using the same dictionary for both content will compress more efficiently when the attacker- controlled content matches parts of the confidential content. HTTP messages can be compressed in a number of ways, including using TLS compression, content codings, transfer codings, and other extension or version-specific mechanisms. The most effective mitigation for this risk is to disable compression on sensitive data, or to strictly separate sensitive data from attacker-controlled data so that they cannot share the same compression dictionary. With careful design, a compression scheme can be designed in a way that is not considered exploitable in limited use cases, such as HPACK ([[HPACK](#ref-HPACK)]). ### 17.7. Disclosure of Personal Information Clients are often privy to large amounts of personal information, including both information provided by the user to interact with resources (e.g., the user's name, location, mail address, passwords, encryption keys, etc.) and information about the user's browsing activity over time (e.g., history, bookmarks, etc.). Implementations need to prevent unintentional disclosure of personal information. ### 17.8. Privacy of Server Log Information A server is in the position to save personal data about a user's requests over time, which might identify their reading patterns or subjects of interest. In particular, log information gathered at an intermediary often contains a history of user agent interaction, across a multitude of sites, that can be traced to individual users. HTTP log information is confidential in nature; its handling is often constrained by laws and regulations. Log information needs to be securely stored and appropriate guidelines followed for its analysis. Anonymization of personal information within individual entries helps, but it is generally not sufficient to prevent real log traces from being re-identified based on correlation with other access characteristics. As such, access traces that are keyed to a specific client are unsafe to publish even if the key is pseudonymous. To minimize the risk of theft or accidental publication, log information ought to be purged of personally identifiable information, including user identifiers, IP addresses, and user- provided query parameters, as soon as that information is no longer necessary to support operational needs for security, auditing, or fraud control. ### 17.9. Disclosure of Sensitive Information in URIs URIs are intended to be shared, not secured, even when they identify secure resources. URIs are often shown on displays, added to templates when a page is printed, and stored in a variety of unprotected bookmark lists. Many servers, proxies, and user agents log or display the target URI in places where it might be visible to third parties. It is therefore unwise to include information within a URI that is sensitive, personally identifiable, or a risk to disclose. When an application uses client-side mechanisms to construct a target URI out of user-provided information, such as the query fields of a form using GET, potentially sensitive data might be provided that would not be appropriate for disclosure within a URI. POST is often preferred in such cases because it usually doesn't construct a URI; instead, POST of a form transmits the potentially sensitive data in the request content. However, this hinders caching and uses an unsafe method for what would otherwise be a safe request. Alternative workarounds include transforming the user-provided data prior to constructing the URI or filtering the data to only include common values that are not sensitive. Likewise, redirecting the result of a query to a different (server-generated) URI can remove potentially sensitive data from later links and provide a cacheable response for later reuse. Since the Referer header field tells a target site about the context that resulted in a request, it has the potential to reveal information about the user's immediate browsing history and any personal information that might be found in the referring resource's URI. Limitations on the Referer header field are described in [Section 10.1.3](#section-10.1.3) to address some of its security considerations. ### 17.10. Application Handling of Field Names Servers often use non-HTTP gateway interfaces and frameworks to process a received request and produce content for the response. For historical reasons, such interfaces often pass received field names as external variable names, using a name mapping suitable for environment variables. For example, the Common Gateway Interface (CGI) mapping of protocol- specific meta-variables, defined by [Section 4.1.18 of [RFC3875]](https://datatracker.ietf.org/doc/html/rfc3875#section-4.1.18), is applied to received header fields that do not correspond to one of CGI's standard variables; the mapping consists of prepending "HTTP\_" to each name and changing all instances of hyphen ("-") to underscore ("\_"). This same mapping has been inherited by many other application frameworks in order to simplify moving applications from one platform to the next. In CGI, a received Content-Length field would be passed as the meta- variable "CONTENT\_LENGTH" with a string value matching the received field's value. In contrast, a received "Content\_Length" header field would be passed as the protocol-specific meta-variable "HTTP\_CONTENT\_LENGTH", which might lead to some confusion if an application mistakenly reads the protocol-specific meta-variable instead of the default one. (This historical practice is why [Section 16.3.2.1](#section-16.3.2.1) discourages the creation of new field names that contain an underscore.) Unfortunately, mapping field names to different interface names can lead to security vulnerabilities if the mapping is incomplete or ambiguous. For example, if an attacker were to send a field named "Transfer\_Encoding", a naive interface might map that to the same variable name as the "Transfer-Encoding" field, resulting in a potential request smuggling vulnerability ([Section 11.2](#section-11.2) of [HTTP/1.1]). To mitigate the associated risks, implementations that perform such mappings are advised to make the mapping unambiguous and complete for the full range of potential octets received as a name (including those that are discouraged or forbidden by the HTTP grammar). For example, a field with an unusual name character might result in the request being blocked, the specific field being removed, or the name being passed with a different prefix to distinguish it from other fields. ### 17.11. Disclosure of Fragment after Redirects Although fragment identifiers used within URI references are not sent in requests, implementers ought to be aware that they will be visible to the user agent and any extensions or scripts running as a result of the response. In particular, when a redirect occurs and the original request's fragment identifier is inherited by the new reference in Location ([Section 10.2.2](#section-10.2.2)), this might have the effect of disclosing one site's fragment to another site. If the first site uses personal information in fragments, it ought to ensure that redirects to other sites include a (possibly empty) fragment component in order to block that inheritance. ### 17.12. Disclosure of Product Information The User-Agent ([Section 10.1.5](#section-10.1.5)), Via ([Section 7.6.3](#section-7.6.3)), and Server ([Section 10.2.4](#section-10.2.4)) header fields often reveal information about the respective sender's software systems. In theory, this can make it easier for an attacker to exploit known security holes; in practice, attackers tend to try all potential holes regardless of the apparent software versions being used. Proxies that serve as a portal through a network firewall ought to take special precautions regarding the transfer of header information that might identify hosts behind the firewall. The Via header field allows intermediaries to replace sensitive machine names with pseudonyms. ### 17.13. Browser Fingerprinting Browser fingerprinting is a set of techniques for identifying a specific user agent over time through its unique set of characteristics. These characteristics might include information related to how it uses the underlying transport protocol, feature capabilities, and scripting environment, though of particular interest here is the set of unique characteristics that might be communicated via HTTP. Fingerprinting is considered a privacy concern because it enables tracking of a user agent's behavior over time ([[Bujlow](#ref-Bujlow)]) without the corresponding controls that the user might have over other forms of data collection (e.g., cookies). Many general-purpose user agents (i.e., Web browsers) have taken steps to reduce their fingerprints. There are a number of request header fields that might reveal information to servers that is sufficiently unique to enable fingerprinting. The From header field is the most obvious, though it is expected that From will only be sent when self-identification is desired by the user. Likewise, Cookie header fields are deliberately designed to enable re-identification, so fingerprinting concerns only apply to situations where cookies are disabled or restricted by the user agent's configuration. The User-Agent header field might contain enough information to uniquely identify a specific device, usually when combined with other characteristics, particularly if the user agent sends excessive details about the user's system or extensions. However, the source of unique information that is least expected by users is proactive negotiation ([Section 12.1](#section-12.1)), including the Accept, Accept-Charset, Accept-Encoding, and Accept-Language header fields. In addition to the fingerprinting concern, detailed use of the Accept-Language header field can reveal information the user might consider to be of a private nature. For example, understanding a given language set might be strongly correlated to membership in a particular ethnic group. An approach that limits such loss of privacy would be for a user agent to omit the sending of Accept- Language except for sites that have been explicitly permitted, perhaps via interaction after detecting a Vary header field that indicates language negotiation might be useful. In environments where proxies are used to enhance privacy, user agents ought to be conservative in sending proactive negotiation header fields. General-purpose user agents that provide a high degree of header field configurability ought to inform users about the loss of privacy that might result if too much detail is provided. As an extreme privacy measure, proxies could filter the proactive negotiation header fields in relayed requests. ### 17.14. Validator Retention The validators defined by this specification are not intended to ensure the validity of a representation, guard against malicious changes, or detect on-path attacks. At best, they enable more efficient cache updates and optimistic concurrent writes when all participants are behaving nicely. At worst, the conditions will fail and the client will receive a response that is no more harmful than an HTTP exchange without conditional requests. An entity tag can be abused in ways that create privacy risks. For example, a site might deliberately construct a semantically invalid entity tag that is unique to the user or user agent, send it in a cacheable response with a long freshness time, and then read that entity tag in later conditional requests as a means of re-identifying that user or user agent. Such an identifying tag would become a persistent identifier for as long as the user agent retained the original cache entry. User agents that cache representations ought to ensure that the cache is cleared or replaced whenever the user performs privacy-maintaining actions, such as clearing stored cookies or changing to a private browsing mode. ### 17.15. Denial-of-Service Attacks Using Range Unconstrained multiple range requests are susceptible to denial-of- service attacks because the effort required to request many overlapping ranges of the same data is tiny compared to the time, memory, and bandwidth consumed by attempting to serve the requested data in many parts. Servers ought to ignore, coalesce, or reject egregious range requests, such as requests for more than two overlapping ranges or for many small ranges in a single set, particularly when the ranges are requested out of order for no apparent reason. Multipart range requests are not designed to support random access. ### 17.16. Authentication Considerations Everything about the topic of HTTP authentication is a security consideration, so the list of considerations below is not exhaustive. Furthermore, it is limited to security considerations regarding the authentication framework, in general, rather than discussing all of the potential considerations for specific authentication schemes (which ought to be documented in the specifications that define those schemes). Various organizations maintain topical information and links to current research on Web application security (e.g., [[OWASP](#ref-OWASP)]), including common pitfalls for implementing and using the authentication schemes found in practice. #### 17.16.1. Confidentiality of Credentials The HTTP authentication framework does not define a single mechanism for maintaining the confidentiality of credentials; instead, each authentication scheme defines how the credentials are encoded prior to transmission. While this provides flexibility for the development of future authentication schemes, it is inadequate for the protection of existing schemes that provide no confidentiality on their own, or that do not sufficiently protect against replay attacks. Furthermore, if the server expects credentials that are specific to each individual user, the exchange of those credentials will have the effect of identifying that user even if the content within credentials remains confidential. HTTP depends on the security properties of the underlying transport- or session-level connection to provide confidential transmission of fields. Services that depend on individual user authentication require a secured connection prior to exchanging credentials ([Section 4.2.2](#section-4.2.2)). #### 17.16.2. Credentials and Idle Clients Existing HTTP clients and user agents typically retain authentication information indefinitely. HTTP does not provide a mechanism for the origin server to direct clients to discard these cached credentials, since the protocol has no awareness of how credentials are obtained or managed by the user agent. The mechanisms for expiring or revoking credentials can be specified as part of an authentication scheme definition. Circumstances under which credential caching can interfere with the application's security model include but are not limited to: \* Clients that have been idle for an extended period, following which the server might wish to cause the client to re-prompt the user for credentials. \* Applications that include a session termination indication (such as a "logout" or "commit" button on a page) after which the server side of the application "knows" that there is no further reason for the client to retain the credentials. User agents that cache credentials are encouraged to provide a readily accessible mechanism for discarding cached credentials under user control. #### 17.16.3. Protection Spaces Authentication schemes that solely rely on the "realm" mechanism for establishing a protection space will expose credentials to all resources on an origin server. Clients that have successfully made authenticated requests with a resource can use the same authentication credentials for other resources on the same origin server. This makes it possible for a different resource to harvest authentication credentials for other resources. This is of particular concern when an origin server hosts resources for multiple parties under the same origin ([Section 11.5](#section-11.5)). Possible mitigation strategies include restricting direct access to authentication credentials (i.e., not making the content of the Authorization request header field available), and separating protection spaces by using a different host name (or port number) for each party. #### 17.16.4. Additional Response Fields Adding information to responses that are sent over an unencrypted channel can affect security and privacy. The presence of the Authentication-Info and Proxy-Authentication-Info header fields alone indicates that HTTP authentication is in use. Additional information could be exposed by the contents of the authentication-scheme specific parameters; this will have to be considered in the definitions of these schemes. 18. IANA Considerations ----------------------- The change controller for the following registrations is: "IETF ([email protected]) - Internet Engineering Task Force". ### 18.1. URI Scheme Registration IANA has updated the "Uniform Resource Identifier (URI) Schemes" registry [[BCP35](#ref-BCP35)] at <<https://www.iana.org/assignments/uri-schemes/>> with the permanent schemes listed in Table 2 in [Section 4.2](#section-4.2). ### 18.2. Method Registration IANA has updated the "Hypertext Transfer Protocol (HTTP) Method Registry" at <<https://www.iana.org/assignments/http-methods>> with the registration procedure of [Section 16.1.1](#section-16.1.1) and the method names summarized in the following table. +=========+======+============+=========+ | Method | Safe | Idempotent | Section | +=========+======+============+=========+ | CONNECT | no | no | 9.3.6 | +---------+------+------------+---------+ | DELETE | no | yes | 9.3.5 | +---------+------+------------+---------+ | GET | yes | yes | 9.3.1 | +---------+------+------------+---------+ | HEAD | yes | yes | 9.3.2 | +---------+------+------------+---------+ | OPTIONS | yes | yes | 9.3.7 | +---------+------+------------+---------+ | POST | no | no | 9.3.3 | +---------+------+------------+---------+ | PUT | no | yes | 9.3.4 | +---------+------+------------+---------+ | TRACE | yes | yes | 9.3.8 | +---------+------+------------+---------+ | \* | no | no | 18.2 | +---------+------+------------+---------+ Table 7 The method name "\*" is reserved because using "\*" as a method name would conflict with its usage as a wildcard in some fields (e.g., "Access-Control-Request-Method"). ### 18.3. Status Code Registration IANA has updated the "Hypertext Transfer Protocol (HTTP) Status Code Registry" at <<https://www.iana.org/assignments/http-status-codes>> with the registration procedure of [Section 16.2.1](#section-16.2.1) and the status code values summarized in the following table. +=======+===============================+=========+ | Value | Description | Section | +=======+===============================+=========+ | 100 | Continue | 15.2.1 | +-------+-------------------------------+---------+ | 101 | Switching Protocols | 15.2.2 | +-------+-------------------------------+---------+ | 200 | OK | 15.3.1 | +-------+-------------------------------+---------+ | 201 | Created | 15.3.2 | +-------+-------------------------------+---------+ | 202 | Accepted | 15.3.3 | +-------+-------------------------------+---------+ | 203 | Non-Authoritative Information | 15.3.4 | +-------+-------------------------------+---------+ | 204 | No Content | 15.3.5 | +-------+-------------------------------+---------+ | 205 | Reset Content | 15.3.6 | +-------+-------------------------------+---------+ | 206 | Partial Content | 15.3.7 | +-------+-------------------------------+---------+ | 300 | Multiple Choices | 15.4.1 | +-------+-------------------------------+---------+ | 301 | Moved Permanently | 15.4.2 | +-------+-------------------------------+---------+ | 302 | Found | 15.4.3 | +-------+-------------------------------+---------+ | 303 | See Other | 15.4.4 | +-------+-------------------------------+---------+ | 304 | Not Modified | 15.4.5 | +-------+-------------------------------+---------+ | 305 | Use Proxy | 15.4.6 | +-------+-------------------------------+---------+ | 306 | (Unused) | 15.4.7 | +-------+-------------------------------+---------+ | 307 | Temporary Redirect | 15.4.8 | +-------+-------------------------------+---------+ | 308 | Permanent Redirect | 15.4.9 | +-------+-------------------------------+---------+ | 400 | Bad Request | 15.5.1 | +-------+-------------------------------+---------+ | 401 | Unauthorized | 15.5.2 | +-------+-------------------------------+---------+ | 402 | Payment Required | 15.5.3 | +-------+-------------------------------+---------+ | 403 | Forbidden | 15.5.4 | +-------+-------------------------------+---------+ | 404 | Not Found | 15.5.5 | +-------+-------------------------------+---------+ | 405 | Method Not Allowed | 15.5.6 | +-------+-------------------------------+---------+ | 406 | Not Acceptable | 15.5.7 | +-------+-------------------------------+---------+ | 407 | Proxy Authentication Required | 15.5.8 | +-------+-------------------------------+---------+ | 408 | Request Timeout | 15.5.9 | +-------+-------------------------------+---------+ | 409 | Conflict | 15.5.10 | +-------+-------------------------------+---------+ | 410 | Gone | 15.5.11 | +-------+-------------------------------+---------+ | 411 | Length Required | 15.5.12 | +-------+-------------------------------+---------+ | 412 | Precondition Failed | 15.5.13 | +-------+-------------------------------+---------+ | 413 | Content Too Large | 15.5.14 | +-------+-------------------------------+---------+ | 414 | URI Too Long | 15.5.15 | +-------+-------------------------------+---------+ | 415 | Unsupported Media Type | 15.5.16 | +-------+-------------------------------+---------+ | 416 | Range Not Satisfiable | 15.5.17 | +-------+-------------------------------+---------+ | 417 | Expectation Failed | 15.5.18 | +-------+-------------------------------+---------+ | 418 | (Unused) | 15.5.19 | +-------+-------------------------------+---------+ | 421 | Misdirected Request | 15.5.20 | +-------+-------------------------------+---------+ | 422 | Unprocessable Content | 15.5.21 | +-------+-------------------------------+---------+ | 426 | Upgrade Required | 15.5.22 | +-------+-------------------------------+---------+ | 500 | Internal Server Error | 15.6.1 | +-------+-------------------------------+---------+ | 501 | Not Implemented | 15.6.2 | +-------+-------------------------------+---------+ | 502 | Bad Gateway | 15.6.3 | +-------+-------------------------------+---------+ | 503 | Service Unavailable | 15.6.4 | +-------+-------------------------------+---------+ | 504 | Gateway Timeout | 15.6.5 | +-------+-------------------------------+---------+ | 505 | HTTP Version Not Supported | 15.6.6 | +-------+-------------------------------+---------+ Table 8 ### 18.4. Field Name Registration This specification updates the HTTP-related aspects of the existing registration procedures for message header fields defined in [[RFC3864](https://datatracker.ietf.org/doc/html/rfc3864)]. It replaces the old procedures as they relate to HTTP by defining a new registration procedure and moving HTTP field definitions into a separate registry. IANA has created a new registry titled "Hypertext Transfer Protocol (HTTP) Field Name Registry" as outlined in [Section 16.3.1](#section-16.3.1). IANA has moved all entries in the "Permanent Message Header Field Names" and "Provisional Message Header Field Names" registries (see <<https://www.iana.org/assignments/message-headers/>>) with the protocol 'http' to this registry and has applied the following changes: 1. The 'Applicable Protocol' field has been omitted. 2. Entries that had a status of 'standard', 'experimental', 'reserved', or 'informational' have been made to have a status of 'permanent'. 3. Provisional entries without a status have been made to have a status of 'provisional'. 4. Permanent entries without a status (after confirmation that the registration document did not define one) have been made to have a status of 'provisional'. The expert(s) can choose to update the entries' status if there is evidence that another is more appropriate. IANA has annotated the "Permanent Message Header Field Names" and "Provisional Message Header Field Names" registries with the following note to indicate that HTTP field name registrations have moved: | \*Note\* | | HTTP field name registrations have been moved to | [https://www.iana.org/assignments/http-fields] per [[RFC9110](https://datatracker.ietf.org/doc/html/rfc9110)]. IANA has updated the "Hypertext Transfer Protocol (HTTP) Field Name Registry" with the field names listed in the following table. +===========================+============+=========+============+ | Field Name | Status | Section | Comments | +===========================+============+=========+============+ | Accept | permanent | 12.5.1 | | +---------------------------+------------+---------+------------+ | Accept-Charset | deprecated | 12.5.2 | | +---------------------------+------------+---------+------------+ | Accept-Encoding | permanent | 12.5.3 | | +---------------------------+------------+---------+------------+ | Accept-Language | permanent | 12.5.4 | | +---------------------------+------------+---------+------------+ | Accept-Ranges | permanent | 14.3 | | +---------------------------+------------+---------+------------+ | Allow | permanent | 10.2.1 | | +---------------------------+------------+---------+------------+ | Authentication-Info | permanent | 11.6.3 | | +---------------------------+------------+---------+------------+ | Authorization | permanent | 11.6.2 | | +---------------------------+------------+---------+------------+ | Connection | permanent | 7.6.1 | | +---------------------------+------------+---------+------------+ | Content-Encoding | permanent | 8.4 | | +---------------------------+------------+---------+------------+ | Content-Language | permanent | 8.5 | | +---------------------------+------------+---------+------------+ | Content-Length | permanent | 8.6 | | +---------------------------+------------+---------+------------+ | Content-Location | permanent | 8.7 | | +---------------------------+------------+---------+------------+ | Content-Range | permanent | 14.4 | | +---------------------------+------------+---------+------------+ | Content-Type | permanent | 8.3 | | +---------------------------+------------+---------+------------+ | Date | permanent | 6.6.1 | | +---------------------------+------------+---------+------------+ | ETag | permanent | 8.8.3 | | +---------------------------+------------+---------+------------+ | Expect | permanent | 10.1.1 | | +---------------------------+------------+---------+------------+ | From | permanent | 10.1.2 | | +---------------------------+------------+---------+------------+ | Host | permanent | 7.2 | | +---------------------------+------------+---------+------------+ | If-Match | permanent | 13.1.1 | | +---------------------------+------------+---------+------------+ | If-Modified-Since | permanent | 13.1.3 | | +---------------------------+------------+---------+------------+ | If-None-Match | permanent | 13.1.2 | | +---------------------------+------------+---------+------------+ | If-Range | permanent | 13.1.5 | | +---------------------------+------------+---------+------------+ | If-Unmodified-Since | permanent | 13.1.4 | | +---------------------------+------------+---------+------------+ | Last-Modified | permanent | 8.8.2 | | +---------------------------+------------+---------+------------+ | Location | permanent | 10.2.2 | | +---------------------------+------------+---------+------------+ | Max-Forwards | permanent | 7.6.2 | | +---------------------------+------------+---------+------------+ | Proxy-Authenticate | permanent | 11.7.1 | | +---------------------------+------------+---------+------------+ | Proxy-Authentication-Info | permanent | 11.7.3 | | +---------------------------+------------+---------+------------+ | Proxy-Authorization | permanent | 11.7.2 | | +---------------------------+------------+---------+------------+ | Range | permanent | 14.2 | | +---------------------------+------------+---------+------------+ | Referer | permanent | 10.1.3 | | +---------------------------+------------+---------+------------+ | Retry-After | permanent | 10.2.3 | | +---------------------------+------------+---------+------------+ | Server | permanent | 10.2.4 | | +---------------------------+------------+---------+------------+ | TE | permanent | 10.1.4 | | +---------------------------+------------+---------+------------+ | Trailer | permanent | 6.6.2 | | +---------------------------+------------+---------+------------+ | Upgrade | permanent | 7.8 | | +---------------------------+------------+---------+------------+ | User-Agent | permanent | 10.1.5 | | +---------------------------+------------+---------+------------+ | Vary | permanent | 12.5.5 | | +---------------------------+------------+---------+------------+ | Via | permanent | 7.6.3 | | +---------------------------+------------+---------+------------+ | WWW-Authenticate | permanent | 11.6.1 | | +---------------------------+------------+---------+------------+ | \* | permanent | 12.5.5 | (reserved) | +---------------------------+------------+---------+------------+ Table 9 The field name "\*" is reserved because using that name as an HTTP header field might conflict with its special semantics in the Vary header field ([Section 12.5.5](#section-12.5.5)). IANA has updated the "Content-MD5" entry in the new registry to have a status of 'obsoleted' with references to [Section 14.15 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-14.15) (for the definition of the header field) and [Appendix B of [RFC7231]](https://datatracker.ietf.org/doc/html/rfc7231#appendix-B) (which removed the field definition from the updated specification). ### 18.5. Authentication Scheme Registration IANA has updated the "Hypertext Transfer Protocol (HTTP) Authentication Scheme Registry" at <[https://www.iana.org/assignments/](https://www.iana.org/assignments/http-authschemes) [http-authschemes](https://www.iana.org/assignments/http-authschemes)> with the registration procedure of [Section 16.4.1](#section-16.4.1). No authentication schemes are defined in this document. ### 18.6. Content Coding Registration IANA has updated the "HTTP Content Coding Registry" at <<https://www.iana.org/assignments/http-parameters/>> with the registration procedure of [Section 16.6.1](#section-16.6.1) and the content coding names summarized in the table below. +============+===========================================+=========+ | Name | Description | Section | +============+===========================================+=========+ | compress | UNIX "compress" data format [[Welch](#ref-Welch)] | 8.4.1.1 | +------------+-------------------------------------------+---------+ | deflate | "deflate" compressed data ([[RFC1951](https://datatracker.ietf.org/doc/html/rfc1951)]) | 8.4.1.2 | | | inside the "zlib" data format ([[RFC1950](https://datatracker.ietf.org/doc/html/rfc1950)]) | | +------------+-------------------------------------------+---------+ | gzip | GZIP file format [[RFC1952](https://datatracker.ietf.org/doc/html/rfc1952)] | 8.4.1.3 | +------------+-------------------------------------------+---------+ | identity | Reserved | 12.5.3 | +------------+-------------------------------------------+---------+ | x-compress | Deprecated (alias for compress) | 8.4.1.1 | +------------+-------------------------------------------+---------+ | x-gzip | Deprecated (alias for gzip) | 8.4.1.3 | +------------+-------------------------------------------+---------+ Table 10 ### 18.7. Range Unit Registration IANA has updated the "HTTP Range Unit Registry" at <<https://www.iana.org/assignments/http-parameters/>> with the registration procedure of [Section 16.5.1](#section-16.5.1) and the range unit names summarized in the table below. +=================+==================================+=========+ | Range Unit Name | Description | Section | +=================+==================================+=========+ | bytes | a range of octets | 14.1.2 | +-----------------+----------------------------------+---------+ | none | reserved as keyword to indicate | 14.3 | | | range requests are not supported | | +-----------------+----------------------------------+---------+ Table 11 ### 18.8. Media Type Registration IANA has updated the "Media Types" registry at <<https://www.iana.org/assignments/media-types>> with the registration information in [Section 14.6](#section-14.6) for the media type "multipart/ byteranges". IANA has updated the registry note about "q" parameters with a link to [Section 12.5.1](#section-12.5.1) of this document. ### 18.9. Port Registration IANA has updated the "Service Name and Transport Protocol Port Number Registry" at <[https://www.iana.org/assignments/service-names-port-](https://www.iana.org/assignments/service-names-port-numbers/) [numbers/](https://www.iana.org/assignments/service-names-port-numbers/)> for the services on ports 80 and 443 that use UDP or TCP to: 1. use this document as "Reference", and 2. when currently unspecified, set "Assignee" to "IESG" and "Contact" to "IETF\_Chair". ### 18.10. Upgrade Token Registration IANA has updated the "Hypertext Transfer Protocol (HTTP) Upgrade Token Registry" at <[https://www.iana.org/assignments/http-upgrade-](https://www.iana.org/assignments/http-upgrade-tokens) [tokens](https://www.iana.org/assignments/http-upgrade-tokens)> with the registration procedure described in [Section 16.7](#section-16.7) and the upgrade token names summarized in the following table. +======+===================+=========================+=========+ | Name | Description | Expected Version Tokens | Section | +======+===================+=========================+=========+ | HTTP | Hypertext | any DIGIT.DIGIT (e.g., | 2.5 | | | Transfer Protocol | "2.0") | | +------+-------------------+-------------------------+---------+ Table 12 19. References -------------- ### 19.1. Normative References [CACHING] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP Caching", STD 98, [RFC 9111](https://datatracker.ietf.org/doc/html/rfc9111), DOI 10.17487/RFC9111, June 2022, <<https://www.rfc-editor.org/info/rfc9111>>. [RFC1950] Deutsch, P. and J-L. Gailly, "ZLIB Compressed Data Format Specification version 3.3", [RFC 1950](https://datatracker.ietf.org/doc/html/rfc1950), DOI 10.17487/RFC1950, May 1996, <<https://www.rfc-editor.org/info/rfc1950>>. [RFC1951] Deutsch, P., "DEFLATE Compressed Data Format Specification version 1.3", [RFC 1951](https://datatracker.ietf.org/doc/html/rfc1951), DOI 10.17487/RFC1951, May 1996, <<https://www.rfc-editor.org/info/rfc1951>>. [RFC1952] Deutsch, P., "GZIP file format specification version 4.3", [RFC 1952](https://datatracker.ietf.org/doc/html/rfc1952), DOI 10.17487/RFC1952, May 1996, <<https://www.rfc-editor.org/info/rfc1952>>. [RFC2046] Freed, N. and N. Borenstein, "Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types", [RFC 2046](https://datatracker.ietf.org/doc/html/rfc2046), DOI 10.17487/RFC2046, November 1996, <<https://www.rfc-editor.org/info/rfc2046>>. [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", [BCP 14](https://datatracker.ietf.org/doc/html/bcp14), [RFC 2119](https://datatracker.ietf.org/doc/html/rfc2119), DOI 10.17487/RFC2119, March 1997, <<https://www.rfc-editor.org/info/rfc2119>>. [RFC4647] Phillips, A., Ed. and M. Davis, Ed., "Matching of Language Tags", [BCP 47](https://datatracker.ietf.org/doc/html/bcp47), [RFC 4647](https://datatracker.ietf.org/doc/html/rfc4647), DOI 10.17487/RFC4647, September 2006, <<https://www.rfc-editor.org/info/rfc4647>>. [RFC4648] Josefsson, S., "The Base16, Base32, and Base64 Data Encodings", [RFC 4648](https://datatracker.ietf.org/doc/html/rfc4648), DOI 10.17487/RFC4648, October 2006, <<https://www.rfc-editor.org/info/rfc4648>>. [RFC5234] Crocker, D., Ed. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, [RFC 5234](https://datatracker.ietf.org/doc/html/rfc5234), DOI 10.17487/RFC5234, January 2008, <<https://www.rfc-editor.org/info/rfc5234>>. [RFC5280] Cooper, D., Santesson, S., Farrell, S., Boeyen, S., Housley, R., and W. Polk, "Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile", [RFC 5280](https://datatracker.ietf.org/doc/html/rfc5280), DOI 10.17487/RFC5280, May 2008, <<https://www.rfc-editor.org/info/rfc5280>>. [RFC5322] Resnick, P., Ed., "Internet Message Format", [RFC 5322](https://datatracker.ietf.org/doc/html/rfc5322), DOI 10.17487/RFC5322, October 2008, <<https://www.rfc-editor.org/info/rfc5322>>. [RFC5646] Phillips, A., Ed. and M. Davis, Ed., "Tags for Identifying Languages", [BCP 47](https://datatracker.ietf.org/doc/html/bcp47), [RFC 5646](https://datatracker.ietf.org/doc/html/rfc5646), DOI 10.17487/RFC5646, September 2009, <<https://www.rfc-editor.org/info/rfc5646>>. [RFC6125] Saint-Andre, P. and J. Hodges, "Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS)", [RFC 6125](https://datatracker.ietf.org/doc/html/rfc6125), DOI 10.17487/RFC6125, March 2011, <<https://www.rfc-editor.org/info/rfc6125>>. [RFC6365] Hoffman, P. and J. Klensin, "Terminology Used in Internationalization in the IETF", [BCP 166](https://datatracker.ietf.org/doc/html/bcp166), [RFC 6365](https://datatracker.ietf.org/doc/html/rfc6365), DOI 10.17487/RFC6365, September 2011, <<https://www.rfc-editor.org/info/rfc6365>>. [RFC7405] Kyzivat, P., "Case-Sensitive String Support in ABNF", [RFC 7405](https://datatracker.ietf.org/doc/html/rfc7405), DOI 10.17487/RFC7405, December 2014, <<https://www.rfc-editor.org/info/rfc7405>>. [RFC8174] Leiba, B., "Ambiguity of Uppercase vs Lowercase in [RFC](https://datatracker.ietf.org/doc/html/rfc2119) [2119](https://datatracker.ietf.org/doc/html/rfc2119) Key Words", [BCP 14](https://datatracker.ietf.org/doc/html/bcp14), [RFC 8174](https://datatracker.ietf.org/doc/html/rfc8174), DOI 10.17487/RFC8174, May 2017, <<https://www.rfc-editor.org/info/rfc8174>>. [TCP] Postel, J., "Transmission Control Protocol", STD 7, [RFC 793](https://datatracker.ietf.org/doc/html/rfc793), DOI 10.17487/RFC0793, September 1981, <<https://www.rfc-editor.org/info/rfc793>>. [TLS13] Rescorla, E., "The Transport Layer Security (TLS) Protocol Version 1.3", [RFC 8446](https://datatracker.ietf.org/doc/html/rfc8446), DOI 10.17487/RFC8446, August 2018, <<https://www.rfc-editor.org/info/rfc8446>>. [URI] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform Resource Identifier (URI): Generic Syntax", STD 66, [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986), DOI 10.17487/RFC3986, January 2005, <<https://www.rfc-editor.org/info/rfc3986>>. [USASCII] American National Standards Institute, "Coded Character Set -- 7-bit American Standard Code for Information Interchange", ANSI X3.4, 1986. [Welch] Welch, T., "A Technique for High-Performance Data Compression", IEEE Computer 17(6), DOI 10.1109/MC.1984.1659158, June 1984, <<https://ieeexplore.ieee.org/document/1659158/>>. ### 19.2. Informative References [ALTSVC] Nottingham, M., McManus, P., and J. Reschke, "HTTP Alternative Services", [RFC 7838](https://datatracker.ietf.org/doc/html/rfc7838), DOI 10.17487/RFC7838, April 2016, <<https://www.rfc-editor.org/info/rfc7838>>. [BCP13] Freed, N. and J. Klensin, "Multipurpose Internet Mail Extensions (MIME) Part Four: Registration Procedures", [BCP 13](https://datatracker.ietf.org/doc/html/bcp13), [RFC 4289](https://datatracker.ietf.org/doc/html/rfc4289), December 2005. Freed, N., Klensin, J., and T. Hansen, "Media Type Specifications and Registration Procedures", [BCP 13](https://datatracker.ietf.org/doc/html/bcp13), [RFC 6838](https://datatracker.ietf.org/doc/html/rfc6838), January 2013. <<https://www.rfc-editor.org/info/bcp13>> [BCP178] Saint-Andre, P., Crocker, D., and M. Nottingham, "Deprecating the "X-" Prefix and Similar Constructs in Application Protocols", [BCP 178](https://datatracker.ietf.org/doc/html/bcp178), [RFC 6648](https://datatracker.ietf.org/doc/html/rfc6648), June 2012. <<https://www.rfc-editor.org/info/bcp178>> [BCP35] Thaler, D., Ed., Hansen, T., and T. Hardie, "Guidelines and Registration Procedures for URI Schemes", [BCP 35](https://datatracker.ietf.org/doc/html/bcp35), [RFC 7595](https://datatracker.ietf.org/doc/html/rfc7595), June 2015. <<https://www.rfc-editor.org/info/bcp35>> [BREACH] Gluck, Y., Harris, N., and A. Prado, "BREACH: Reviving the CRIME Attack", July 2013, <<http://breachattack.com/resources/> BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf>. [Bujlow] Bujlow, T., Carela-Español, V., Solé-Pareta, J., and P. Barlet-Ros, "A Survey on Web Tracking: Mechanisms, Implications, and Defenses", In Proceedings of the IEEE 105(8), DOI 10.1109/JPROC.2016.2637878, August 2017, <<https://doi.org/10.1109/JPROC.2016.2637878>>. [COOKIE] Barth, A., "HTTP State Management Mechanism", [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265), DOI 10.17487/RFC6265, April 2011, <<https://www.rfc-editor.org/info/rfc6265>>. [Err1912] RFC Errata, Erratum ID 1912, [RFC 2978](https://datatracker.ietf.org/doc/html/rfc2978), <<https://www.rfc-editor.org/errata/eid1912>>. [Err5433] RFC Errata, Erratum ID 5433, [RFC 2978](https://datatracker.ietf.org/doc/html/rfc2978), <<https://www.rfc-editor.org/errata/eid5433>>. [Georgiev] Georgiev, M., Iyengar, S., Jana, S., Anubhai, R., Boneh, D., and V. Shmatikov, "The Most Dangerous Code in the World: Validating SSL Certificates in Non-Browser Software", In Proceedings of the 2012 ACM Conference on Computer and Communications Security (CCS '12), pp. 38-49, DOI 10.1145/2382196.2382204, October 2012, <<https://doi.org/10.1145/2382196.2382204>>. [HPACK] Peon, R. and H. Ruellan, "HPACK: Header Compression for HTTP/2", [RFC 7541](https://datatracker.ietf.org/doc/html/rfc7541), DOI 10.17487/RFC7541, May 2015, <<https://www.rfc-editor.org/info/rfc7541>>. [HTTP/1.0] Berners-Lee, T., Fielding, R., and H. Frystyk, "Hypertext Transfer Protocol -- HTTP/1.0", [RFC 1945](https://datatracker.ietf.org/doc/html/rfc1945), DOI 10.17487/RFC1945, May 1996, <<https://www.rfc-editor.org/info/rfc1945>>. [HTTP/1.1] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP/1.1", STD 99, [RFC 9112](https://datatracker.ietf.org/doc/html/rfc9112), DOI 10.17487/RFC9112, June 2022, <<https://www.rfc-editor.org/info/rfc9112>>. [HTTP/2] Thomson, M., Ed. and C. Benfield, Ed., "HTTP/2", [RFC 9113](https://datatracker.ietf.org/doc/html/rfc9113), DOI 10.17487/RFC9113, June 2022, <<https://www.rfc-editor.org/info/rfc9113>>. [HTTP/3] Bishop, M., Ed., "HTTP/3", [RFC 9114](https://datatracker.ietf.org/doc/html/rfc9114), DOI 10.17487/RFC9114, June 2022, <<https://www.rfc-editor.org/info/rfc9114>>. [ISO-8859-1] International Organization for Standardization, "Information technology -- 8-bit single-byte coded graphic character sets -- Part 1: Latin alphabet No. 1", ISO/ IEC 8859-1:1998, 1998. [Kri2001] Kristol, D., "HTTP Cookies: Standards, Privacy, and Politics", ACM Transactions on Internet Technology 1(2), November 2001, <[http://arxiv.org/abs/cs.SE/0105018](https://arxiv.org/abs/cs.SE/0105018)>. [OWASP] The Open Web Application Security Project, <<https://www.owasp.org/>>. [REST] Fielding, R.T., "Architectural Styles and the Design of Network-based Software Architectures", Doctoral Dissertation, University of California, Irvine, September 2000, <<https://roy.gbiv.com/pubs/dissertation/top.htm>>. [RFC1919] Chatel, M., "Classical versus Transparent IP Proxies", [RFC 1919](https://datatracker.ietf.org/doc/html/rfc1919), DOI 10.17487/RFC1919, March 1996, <<https://www.rfc-editor.org/info/rfc1919>>. [RFC2047] Moore, K., "MIME (Multipurpose Internet Mail Extensions) Part Three: Message Header Extensions for Non-ASCII Text", [RFC 2047](https://datatracker.ietf.org/doc/html/rfc2047), DOI 10.17487/RFC2047, November 1996, <<https://www.rfc-editor.org/info/rfc2047>>. [RFC2068] Fielding, R., Gettys, J., Mogul, J., Frystyk, H., and T. Berners-Lee, "Hypertext Transfer Protocol -- HTTP/1.1", [RFC 2068](https://datatracker.ietf.org/doc/html/rfc2068), DOI 10.17487/RFC2068, January 1997, <<https://www.rfc-editor.org/info/rfc2068>>. [RFC2145] Mogul, J. C., Fielding, R., Gettys, J., and H. Frystyk, "Use and Interpretation of HTTP Version Numbers", [RFC 2145](https://datatracker.ietf.org/doc/html/rfc2145), DOI 10.17487/RFC2145, May 1997, <<https://www.rfc-editor.org/info/rfc2145>>. [RFC2295] Holtman, K. and A. Mutz, "Transparent Content Negotiation in HTTP", [RFC 2295](https://datatracker.ietf.org/doc/html/rfc2295), DOI 10.17487/RFC2295, March 1998, <<https://www.rfc-editor.org/info/rfc2295>>. [RFC2324] Masinter, L., "Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0)", [RFC 2324](https://datatracker.ietf.org/doc/html/rfc2324), DOI 10.17487/RFC2324, 1 April 1998, <<https://www.rfc-editor.org/info/rfc2324>>. [RFC2557] Palme, J., Hopmann, A., and N. Shelness, "MIME Encapsulation of Aggregate Documents, such as HTML (MHTML)", [RFC 2557](https://datatracker.ietf.org/doc/html/rfc2557), DOI 10.17487/RFC2557, March 1999, <<https://www.rfc-editor.org/info/rfc2557>>. [RFC2616] Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, "Hypertext Transfer Protocol -- HTTP/1.1", [RFC 2616](https://datatracker.ietf.org/doc/html/rfc2616), DOI 10.17487/RFC2616, June 1999, <<https://www.rfc-editor.org/info/rfc2616>>. [RFC2617] Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, "HTTP Authentication: Basic and Digest Access Authentication", [RFC 2617](https://datatracker.ietf.org/doc/html/rfc2617), DOI 10.17487/RFC2617, June 1999, <<https://www.rfc-editor.org/info/rfc2617>>. [RFC2774] Nielsen, H., Leach, P., and S. Lawrence, "An HTTP Extension Framework", [RFC 2774](https://datatracker.ietf.org/doc/html/rfc2774), DOI 10.17487/RFC2774, February 2000, <<https://www.rfc-editor.org/info/rfc2774>>. [RFC2818] Rescorla, E., "HTTP Over TLS", [RFC 2818](https://datatracker.ietf.org/doc/html/rfc2818), DOI 10.17487/RFC2818, May 2000, <<https://www.rfc-editor.org/info/rfc2818>>. [RFC2978] Freed, N. and J. Postel, "IANA Charset Registration Procedures", [BCP 19](https://datatracker.ietf.org/doc/html/bcp19), [RFC 2978](https://datatracker.ietf.org/doc/html/rfc2978), DOI 10.17487/RFC2978, October 2000, <<https://www.rfc-editor.org/info/rfc2978>>. [RFC3040] Cooper, I., Melve, I., and G. Tomlinson, "Internet Web Replication and Caching Taxonomy", [RFC 3040](https://datatracker.ietf.org/doc/html/rfc3040), DOI 10.17487/RFC3040, January 2001, <<https://www.rfc-editor.org/info/rfc3040>>. [RFC3864] Klyne, G., Nottingham, M., and J. Mogul, "Registration Procedures for Message Header Fields", [BCP 90](https://datatracker.ietf.org/doc/html/bcp90), [RFC 3864](https://datatracker.ietf.org/doc/html/rfc3864), DOI 10.17487/RFC3864, September 2004, <<https://www.rfc-editor.org/info/rfc3864>>. [RFC3875] Robinson, D. and K. Coar, "The Common Gateway Interface (CGI) Version 1.1", [RFC 3875](https://datatracker.ietf.org/doc/html/rfc3875), DOI 10.17487/RFC3875, October 2004, <<https://www.rfc-editor.org/info/rfc3875>>. [RFC4033] Arends, R., Austein, R., Larson, M., Massey, D., and S. Rose, "DNS Security Introduction and Requirements", [RFC 4033](https://datatracker.ietf.org/doc/html/rfc4033), DOI 10.17487/RFC4033, March 2005, <<https://www.rfc-editor.org/info/rfc4033>>. [RFC4559] Jaganathan, K., Zhu, L., and J. Brezak, "SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows", [RFC 4559](https://datatracker.ietf.org/doc/html/rfc4559), DOI 10.17487/RFC4559, June 2006, <<https://www.rfc-editor.org/info/rfc4559>>. [RFC5789] Dusseault, L. and J. Snell, "PATCH Method for HTTP", [RFC 5789](https://datatracker.ietf.org/doc/html/rfc5789), DOI 10.17487/RFC5789, March 2010, <<https://www.rfc-editor.org/info/rfc5789>>. [RFC5905] Mills, D., Martin, J., Ed., Burbank, J., and W. Kasch, "Network Time Protocol Version 4: Protocol and Algorithms Specification", [RFC 5905](https://datatracker.ietf.org/doc/html/rfc5905), DOI 10.17487/RFC5905, June 2010, <<https://www.rfc-editor.org/info/rfc5905>>. [RFC6454] Barth, A., "The Web Origin Concept", [RFC 6454](https://datatracker.ietf.org/doc/html/rfc6454), DOI 10.17487/RFC6454, December 2011, <<https://www.rfc-editor.org/info/rfc6454>>. [RFC6585] Nottingham, M. and R. Fielding, "Additional HTTP Status Codes", [RFC 6585](https://datatracker.ietf.org/doc/html/rfc6585), DOI 10.17487/RFC6585, April 2012, <<https://www.rfc-editor.org/info/rfc6585>>. [RFC7230] Fielding, R., Ed. and J. Reschke, Ed., "Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing", [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230), DOI 10.17487/RFC7230, June 2014, <<https://www.rfc-editor.org/info/rfc7230>>. [RFC7231] Fielding, R., Ed. and J. Reschke, Ed., "Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content", [RFC 7231](https://datatracker.ietf.org/doc/html/rfc7231), DOI 10.17487/RFC7231, June 2014, <<https://www.rfc-editor.org/info/rfc7231>>. [RFC7232] Fielding, R., Ed. and J. Reschke, Ed., "Hypertext Transfer Protocol (HTTP/1.1): Conditional Requests", [RFC 7232](https://datatracker.ietf.org/doc/html/rfc7232), DOI 10.17487/RFC7232, June 2014, <<https://www.rfc-editor.org/info/rfc7232>>. [RFC7233] Fielding, R., Ed., Lafon, Y., Ed., and J. Reschke, Ed., "Hypertext Transfer Protocol (HTTP/1.1): Range Requests", [RFC 7233](https://datatracker.ietf.org/doc/html/rfc7233), DOI 10.17487/RFC7233, June 2014, <<https://www.rfc-editor.org/info/rfc7233>>. [RFC7234] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "Hypertext Transfer Protocol (HTTP/1.1): Caching", [RFC 7234](https://datatracker.ietf.org/doc/html/rfc7234), DOI 10.17487/RFC7234, June 2014, <<https://www.rfc-editor.org/info/rfc7234>>. [RFC7235] Fielding, R., Ed. and J. Reschke, Ed., "Hypertext Transfer Protocol (HTTP/1.1): Authentication", [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235), DOI 10.17487/RFC7235, June 2014, <<https://www.rfc-editor.org/info/rfc7235>>. [RFC7538] Reschke, J., "The Hypertext Transfer Protocol Status Code 308 (Permanent Redirect)", [RFC 7538](https://datatracker.ietf.org/doc/html/rfc7538), DOI 10.17487/RFC7538, April 2015, <<https://www.rfc-editor.org/info/rfc7538>>. [RFC7540] Belshe, M., Peon, R., and M. Thomson, Ed., "Hypertext Transfer Protocol Version 2 (HTTP/2)", [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540), DOI 10.17487/RFC7540, May 2015, <<https://www.rfc-editor.org/info/rfc7540>>. [RFC7578] Masinter, L., "Returning Values from Forms: multipart/ form-data", [RFC 7578](https://datatracker.ietf.org/doc/html/rfc7578), DOI 10.17487/RFC7578, July 2015, <<https://www.rfc-editor.org/info/rfc7578>>. [RFC7615] Reschke, J., "HTTP Authentication-Info and Proxy- Authentication-Info Response Header Fields", [RFC 7615](https://datatracker.ietf.org/doc/html/rfc7615), DOI 10.17487/RFC7615, September 2015, <<https://www.rfc-editor.org/info/rfc7615>>. [RFC7616] Shekh-Yusef, R., Ed., Ahrens, D., and S. Bremer, "HTTP Digest Access Authentication", [RFC 7616](https://datatracker.ietf.org/doc/html/rfc7616), DOI 10.17487/RFC7616, September 2015, <<https://www.rfc-editor.org/info/rfc7616>>. [RFC7617] Reschke, J., "The 'Basic' HTTP Authentication Scheme", [RFC 7617](https://datatracker.ietf.org/doc/html/rfc7617), DOI 10.17487/RFC7617, September 2015, <<https://www.rfc-editor.org/info/rfc7617>>. [RFC7694] Reschke, J., "Hypertext Transfer Protocol (HTTP) Client- Initiated Content-Encoding", [RFC 7694](https://datatracker.ietf.org/doc/html/rfc7694), DOI 10.17487/RFC7694, November 2015, <<https://www.rfc-editor.org/info/rfc7694>>. [RFC8126] Cotton, M., Leiba, B., and T. Narten, "Guidelines for Writing an IANA Considerations Section in RFCs", [BCP 26](https://datatracker.ietf.org/doc/html/bcp26), [RFC 8126](https://datatracker.ietf.org/doc/html/rfc8126), DOI 10.17487/RFC8126, June 2017, <<https://www.rfc-editor.org/info/rfc8126>>. [RFC8187] Reschke, J., "Indicating Character Encoding and Language for HTTP Header Field Parameters", [RFC 8187](https://datatracker.ietf.org/doc/html/rfc8187), DOI 10.17487/RFC8187, September 2017, <<https://www.rfc-editor.org/info/rfc8187>>. [RFC8246] McManus, P., "HTTP Immutable Responses", [RFC 8246](https://datatracker.ietf.org/doc/html/rfc8246), DOI 10.17487/RFC8246, September 2017, <<https://www.rfc-editor.org/info/rfc8246>>. [RFC8288] Nottingham, M., "Web Linking", [RFC 8288](https://datatracker.ietf.org/doc/html/rfc8288), DOI 10.17487/RFC8288, October 2017, <<https://www.rfc-editor.org/info/rfc8288>>. [RFC8336] Nottingham, M. and E. Nygren, "The ORIGIN HTTP/2 Frame", [RFC 8336](https://datatracker.ietf.org/doc/html/rfc8336), DOI 10.17487/RFC8336, March 2018, <<https://www.rfc-editor.org/info/rfc8336>>. [RFC8615] Nottingham, M., "Well-Known Uniform Resource Identifiers (URIs)", [RFC 8615](https://datatracker.ietf.org/doc/html/rfc8615), DOI 10.17487/RFC8615, May 2019, <<https://www.rfc-editor.org/info/rfc8615>>. [RFC8941] Nottingham, M. and P-H. Kamp, "Structured Field Values for HTTP", [RFC 8941](https://datatracker.ietf.org/doc/html/rfc8941), DOI 10.17487/RFC8941, February 2021, <<https://www.rfc-editor.org/info/rfc8941>>. [Sniffing] WHATWG, "MIME Sniffing", <<https://mimesniff.spec.whatwg.org>>. [WEBDAV] Dusseault, L., Ed., "HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV)", [RFC 4918](https://datatracker.ietf.org/doc/html/rfc4918), DOI 10.17487/RFC4918, June 2007, <<https://www.rfc-editor.org/info/rfc4918>>. Appendix A. Collected ABNF -------------------------- In the collected ABNF below, list rules are expanded per [Section 5.6.1](#section-5.6.1). Accept = [ ( media-range [ weight ] ) \*( OWS "," OWS ( media-range [ weight ] ) ) ] Accept-Charset = [ ( ( token / "\*" ) [ weight ] ) \*( OWS "," OWS ( ( token / "\*" ) [ weight ] ) ) ] Accept-Encoding = [ ( codings [ weight ] ) \*( OWS "," OWS ( codings [ weight ] ) ) ] Accept-Language = [ ( language-range [ weight ] ) \*( OWS "," OWS ( language-range [ weight ] ) ) ] Accept-Ranges = acceptable-ranges Allow = [ method \*( OWS "," OWS method ) ] Authentication-Info = [ auth-param \*( OWS "," OWS auth-param ) ] Authorization = credentials BWS = OWS Connection = [ connection-option \*( OWS "," OWS connection-option ) ] Content-Encoding = [ content-coding \*( OWS "," OWS content-coding ) ] Content-Language = [ language-tag \*( OWS "," OWS language-tag ) ] Content-Length = 1\*DIGIT Content-Location = absolute-URI / partial-URI Content-Range = range-unit SP ( range-resp / unsatisfied-range ) Content-Type = media-type Date = HTTP-date ETag = entity-tag Expect = [ expectation \*( OWS "," OWS expectation ) ] From = mailbox GMT = %x47.4D.54 ; GMT HTTP-date = IMF-fixdate / obs-date Host = uri-host [ ":" port ] IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT If-Match = "\*" / [ entity-tag \*( OWS "," OWS entity-tag ) ] If-Modified-Since = HTTP-date If-None-Match = "\*" / [ entity-tag \*( OWS "," OWS entity-tag ) ] If-Range = entity-tag / HTTP-date If-Unmodified-Since = HTTP-date Last-Modified = HTTP-date Location = URI-reference Max-Forwards = 1\*DIGIT OWS = \*( SP / HTAB ) Proxy-Authenticate = [ challenge \*( OWS "," OWS challenge ) ] Proxy-Authentication-Info = [ auth-param \*( OWS "," OWS auth-param ) ] Proxy-Authorization = credentials RWS = 1\*( SP / HTAB ) Range = ranges-specifier Referer = absolute-URI / partial-URI Retry-After = HTTP-date / delay-seconds Server = product \*( RWS ( product / comment ) ) TE = [ t-codings \*( OWS "," OWS t-codings ) ] Trailer = [ field-name \*( OWS "," OWS field-name ) ] URI-reference = <URI-reference, see [[URI](#ref-URI)], Section 4.1> Upgrade = [ protocol \*( OWS "," OWS protocol ) ] User-Agent = product \*( RWS ( product / comment ) ) Vary = [ ( "\*" / field-name ) \*( OWS "," OWS ( "\*" / field-name ) ) ] Via = [ ( received-protocol RWS received-by [ RWS comment ] ) \*( OWS "," OWS ( received-protocol RWS received-by [ RWS comment ] ) ) ] WWW-Authenticate = [ challenge \*( OWS "," OWS challenge ) ] absolute-URI = <absolute-URI, see [[URI](#ref-URI)], Section 4.3> absolute-path = 1\*( "/" segment ) acceptable-ranges = range-unit \*( OWS "," OWS range-unit ) asctime-date = day-name SP date3 SP time-of-day SP year auth-param = token BWS "=" BWS ( token / quoted-string ) auth-scheme = token authority = <authority, see [[URI](#ref-URI)], Section 3.2> challenge = auth-scheme [ 1\*SP ( token68 / [ auth-param \*( OWS "," OWS auth-param ) ] ) ] codings = content-coding / "identity" / "\*" comment = "(" \*( ctext / quoted-pair / comment ) ")" complete-length = 1\*DIGIT connection-option = token content-coding = token credentials = auth-scheme [ 1\*SP ( token68 / [ auth-param \*( OWS "," OWS auth-param ) ] ) ] ctext = HTAB / SP / %x21-27 ; '!'-''' / %x2A-5B ; '\*'-'[' / %x5D-7E ; ']'-'~' / obs-text date1 = day SP month SP year date2 = day "-" month "-" 2DIGIT date3 = month SP ( 2DIGIT / ( SP DIGIT ) ) day = 2DIGIT day-name = %x4D.6F.6E ; Mon / %x54.75.65 ; Tue / %x57.65.64 ; Wed / %x54.68.75 ; Thu / %x46.72.69 ; Fri / %x53.61.74 ; Sat / %x53.75.6E ; Sun day-name-l = %x4D.6F.6E.64.61.79 ; Monday / %x54.75.65.73.64.61.79 ; Tuesday / %x57.65.64.6E.65.73.64.61.79 ; Wednesday / %x54.68.75.72.73.64.61.79 ; Thursday / %x46.72.69.64.61.79 ; Friday / %x53.61.74.75.72.64.61.79 ; Saturday / %x53.75.6E.64.61.79 ; Sunday delay-seconds = 1\*DIGIT entity-tag = [ weak ] opaque-tag etagc = "!" / %x23-7E ; '#'-'~' / obs-text expectation = token [ "=" ( token / quoted-string ) parameters ] field-content = field-vchar [ 1\*( SP / HTAB / field-vchar ) field-vchar ] field-name = token field-value = \*field-content field-vchar = VCHAR / obs-text first-pos = 1\*DIGIT hour = 2DIGIT http-URI = "http://" authority path-abempty [ "?" query ] https-URI = "https://" authority path-abempty [ "?" query ] incl-range = first-pos "-" last-pos int-range = first-pos "-" [ last-pos ] language-range = <language-range, see [[RFC4647], Section 2.1](https://datatracker.ietf.org/doc/html/rfc4647#section-2.1)> language-tag = <Language-Tag, see [[RFC5646], Section 2.1](https://datatracker.ietf.org/doc/html/rfc5646#section-2.1)> last-pos = 1\*DIGIT mailbox = <mailbox, see [[RFC5322], Section 3.4](https://datatracker.ietf.org/doc/html/rfc5322#section-3.4)> media-range = ( "\*/\*" / ( type "/\*" ) / ( type "/" subtype ) ) parameters media-type = type "/" subtype parameters method = token minute = 2DIGIT month = %x4A.61.6E ; Jan / %x46.65.62 ; Feb / %x4D.61.72 ; Mar / %x41.70.72 ; Apr / %x4D.61.79 ; May / %x4A.75.6E ; Jun / %x4A.75.6C ; Jul / %x41.75.67 ; Aug / %x53.65.70 ; Sep / %x4F.63.74 ; Oct / %x4E.6F.76 ; Nov / %x44.65.63 ; Dec obs-date = [rfc850](https://datatracker.ietf.org/doc/html/rfc850)-date / asctime-date obs-text = %x80-FF opaque-tag = DQUOTE \*etagc DQUOTE other-range = 1\*( %x21-2B ; '!'-'+' / %x2D-7E ; '-'-'~' ) parameter = parameter-name "=" parameter-value parameter-name = token parameter-value = ( token / quoted-string ) parameters = \*( OWS ";" OWS [ parameter ] ) partial-URI = relative-part [ "?" query ] path-abempty = <path-abempty, see [[URI](#ref-URI)], Section 3.3> port = <port, see [[URI](#ref-URI)], Section 3.2.3> product = token [ "/" product-version ] product-version = token protocol = protocol-name [ "/" protocol-version ] protocol-name = token protocol-version = token pseudonym = token qdtext = HTAB / SP / "!" / %x23-5B ; '#'-'[' / %x5D-7E ; ']'-'~' / obs-text query = <query, see [[URI](#ref-URI)], Section 3.4> quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) quoted-string = DQUOTE \*( qdtext / quoted-pair ) DQUOTE qvalue = ( "0" [ "." \*3DIGIT ] ) / ( "1" [ "." \*3"0" ] ) range-resp = incl-range "/" ( complete-length / "\*" ) range-set = range-spec \*( OWS "," OWS range-spec ) range-spec = int-range / suffix-range / other-range range-unit = token ranges-specifier = range-unit "=" range-set received-by = pseudonym [ ":" port ] received-protocol = [ protocol-name "/" ] protocol-version relative-part = <relative-part, see [[URI](#ref-URI)], Section 4.2> [rfc850](https://datatracker.ietf.org/doc/html/rfc850)-date = day-name-l "," SP date2 SP time-of-day SP GMT second = 2DIGIT segment = <segment, see [[URI](#ref-URI)], Section 3.3> subtype = token suffix-length = 1\*DIGIT suffix-range = "-" suffix-length t-codings = "trailers" / ( transfer-coding [ weight ] ) tchar = "!" / "#" / "$" / "%" / "&" / "'" / "\*" / "+" / "-" / "." / "^" / "\_" / "`" / "|" / "~" / DIGIT / ALPHA time-of-day = hour ":" minute ":" second token = 1\*tchar token68 = 1\*( ALPHA / DIGIT / "-" / "." / "\_" / "~" / "+" / "/" ) \*"=" transfer-coding = token \*( OWS ";" OWS transfer-parameter ) transfer-parameter = token BWS "=" BWS ( token / quoted-string ) type = token unsatisfied-range = "\*/" complete-length uri-host = <host, see [[URI](#ref-URI)], Section 3.2.2> weak = %x57.2F ; W/ weight = OWS ";" OWS "q=" qvalue year = 4DIGIT Appendix B. Changes from Previous RFCs -------------------------------------- ### B.1. Changes from [RFC 2818](https://datatracker.ietf.org/doc/html/rfc2818) None. ### B.2. Changes from [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230) The sections introducing HTTP's design goals, history, architecture, conformance criteria, protocol versioning, URIs, message routing, and header fields have been moved here. The requirement on semantic conformance has been replaced with permission to ignore or work around implementation-specific failures. ([Section 2.2](#section-2.2)) The description of an origin and authoritative access to origin servers has been extended for both "http" and "https" URIs to account for alternative services and secured connections that are not necessarily based on TCP. (Sections [4.2.1](#section-4.2.1), [4.2.2](#section-4.2.2), [4.3.1](#section-4.3.1), and [7.3.3](#section-7.3.3)) Explicit requirements have been added to check the target URI scheme's semantics and reject requests that don't meet any associated requirements. ([Section 7.4](#section-7.4)) Parameters in media type, media range, and expectation can be empty via one or more trailing semicolons. ([Section 5.6.6](#section-5.6.6)) "Field value" now refers to the value after multiple field lines are combined with commas -- by far the most common use. To refer to a single header line's value, use "field line value". ([Section 6.3](#section-6.3)) Trailer field semantics now transcend the specifics of chunked transfer coding. The use of trailer fields has been further limited to allow generation as a trailer field only when the sender knows the field defines that usage and to allow merging into the header section only if the recipient knows the corresponding field definition permits and defines how to merge. In all other cases, implementations are encouraged either to store the trailer fields separately or to discard them instead of merging. ([Section 6.5.1](#section-6.5.1)) The priority of the absolute form of the request URI over the Host header field by origin servers has been made explicit to align with proxy handling. ([Section 7.2](#section-7.2)) The grammar definition for the Via field's "received-by" was expanded in [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230) due to changes in the URI grammar for host [[URI](#ref-URI)] that are not desirable for Via. For simplicity, we have removed uri-host from the received-by production because it can be encompassed by the existing grammar for pseudonym. In particular, this change removed comma from the allowed set of characters for a host name in received- by. ([Section 7.6.3](#section-7.6.3)) ### B.3. Changes from [RFC 7231](https://datatracker.ietf.org/doc/html/rfc7231) Minimum URI lengths to be supported by implementations are now recommended. ([Section 4.1](#section-4.1)) The following have been clarified: CR and NUL in field values are to be rejected or mapped to SP, and leading and trailing whitespace needs to be stripped from field values before they are consumed. ([Section 5.5](#section-5.5)) Parameters in media type, media range, and expectation can be empty via one or more trailing semicolons. ([Section 5.6.6](#section-5.6.6)) An abstract data type for HTTP messages has been introduced to define the components of a message and their semantics as an abstraction across multiple HTTP versions, rather than in terms of the specific syntax form of HTTP/1.1 in [HTTP/1.1], and reflect the contents after the message is parsed. This makes it easier to distinguish between requirements on the content (what is conveyed) versus requirements on the messaging syntax (how it is conveyed) and avoids baking limitations of early protocol versions into the future of HTTP. ([Section 6](#section-6)) The terms "payload" and "payload body" have been replaced with "content", to better align with its usage elsewhere (e.g., in field names) and to avoid confusion with frame payloads in HTTP/2 and HTTP/3. ([Section 6.4](#section-6.4)) The term "effective request URI" has been replaced with "target URI". ([Section 7.1](#section-7.1)) Restrictions on client retries have been loosened to reflect implementation behavior. ([Section 9.2.2](#section-9.2.2)) The fact that request bodies on GET, HEAD, and DELETE are not interoperable has been clarified. (Sections [9.3.1](#section-9.3.1), [9.3.2](#section-9.3.2), and [9.3.5](#section-9.3.5)) The use of the Content-Range header field ([Section 14.4](#section-14.4)) as a request modifier on PUT is allowed. ([Section 9.3.4](#section-9.3.4)) A superfluous requirement about setting Content-Length has been removed from the description of the OPTIONS method. ([Section 9.3.7](#section-9.3.7)) The normative requirement to use the "message/http" media type in TRACE responses has been removed. ([Section 9.3.8](#section-9.3.8)) List-based grammar for Expect has been restored for compatibility with [RFC 2616](https://datatracker.ietf.org/doc/html/rfc2616). ([Section 10.1.1](#section-10.1.1)) Accept and Accept-Encoding are allowed in response messages; the latter was introduced by [[RFC7694](https://datatracker.ietf.org/doc/html/rfc7694)]. ([Section 12.3](#section-12.3)) "Accept Parameters" (accept-params and accept-ext ABNF production) have been removed from the definition of the Accept field. ([Section 12.5.1](#section-12.5.1)) The Accept-Charset field is now deprecated. ([Section 12.5.2](#section-12.5.2)) The semantics of "\*" in the Vary header field when other values are present was clarified. ([Section 12.5.5](#section-12.5.5)) Range units are compared in a case-insensitive fashion. ([Section 14.1](#section-14.1)) The use of the Accept-Ranges field is not restricted to origin servers. ([Section 14.3](#section-14.3)) The process of creating a redirected request has been clarified. ([Section 15.4](#section-15.4)) Status code 308 (previously defined in [[RFC7538](https://datatracker.ietf.org/doc/html/rfc7538)]) has been added so that it's defined closer to status codes 301, 302, and 307. ([Section 15.4.9](#section-15.4.9)) Status code 421 (previously defined in [Section 9.1.2 of [RFC7540]](https://datatracker.ietf.org/doc/html/rfc7540#section-9.1.2)) has been added because of its general applicability. 421 is no longer defined as heuristically cacheable since the response is specific to the connection (not the target resource). ([Section 15.5.20](#section-15.5.20)) Status code 422 (previously defined in Section 11.2 of [[WEBDAV](#ref-WEBDAV)]) has been added because of its general applicability. ([Section 15.5.21](#section-15.5.21)) ### B.4. Changes from [RFC 7232](https://datatracker.ietf.org/doc/html/rfc7232) Previous revisions of HTTP imposed an arbitrary 60-second limit on the determination of whether Last-Modified was a strong validator to guard against the possibility that the Date and Last-Modified values are generated from different clocks or at somewhat different times during the preparation of the response. This specification has relaxed that to allow reasonable discretion. ([Section 8.8.2.2](#section-8.8.2.2)) An edge-case requirement on If-Match and If-Unmodified-Since has been removed that required a validator not to be sent in a 2xx response if validation fails because the change request has already been applied. (Sections [13.1.1](#section-13.1.1) and [13.1.4](#section-13.1.4)) The fact that If-Unmodified-Since does not apply to a resource without a concept of modification time has been clarified. ([Section 13.1.4](#section-13.1.4)) Preconditions can now be evaluated before the request content is processed rather than waiting until the response would otherwise be successful. ([Section 13.2](#section-13.2)) ### B.5. Changes from [RFC 7233](https://datatracker.ietf.org/doc/html/rfc7233) Refactored the range-unit and ranges-specifier grammars to simplify and reduce artificial distinctions between bytes and other (extension) range units, removing the overlapping grammar of other- range-unit by defining range units generically as a token and placing extensions within the scope of a range-spec (other-range). This disambiguates the role of list syntax (commas) in all range sets, including extension range units, for indicating a range-set of more than one range. Moving the extension grammar into range specifiers also allows protocol specific to byte ranges to be specified separately. It is now possible to define Range handling on extension methods. ([Section 14.2](#section-14.2)) Described use of the Content-Range header field ([Section 14.4](#section-14.4)) as a request modifier to perform a partial PUT. ([Section 14.5](#section-14.5)) ### B.6. Changes from [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235) None. ### B.7. Changes from [RFC 7538](https://datatracker.ietf.org/doc/html/rfc7538) None. ### B.8. Changes from [RFC 7615](https://datatracker.ietf.org/doc/html/rfc7615) None. ### B.9. Changes from [RFC 7694](https://datatracker.ietf.org/doc/html/rfc7694) This specification includes the extension defined in [[RFC7694](https://datatracker.ietf.org/doc/html/rfc7694)] but leaves out examples and deployment considerations. Acknowledgements Aside from the current editors, the following individuals deserve special recognition for their contributions to early aspects of HTTP and its core specifications: Marc Andreessen, Tim Berners-Lee, Robert Cailliau, Daniel W. Connolly, Bob Denny, John Franks, Jim Gettys, Jean-François Groff, Phillip M. Hallam-Baker, Koen Holtman, Jeffery L. Hostetler, Shel Kaphan, Dave Kristol, Yves Lafon, Scott D. Lawrence, Paul J. Leach, Håkon W. Lie, Ari Luotonen, Larry Masinter, Rob McCool, Jeffrey C. Mogul, Lou Montulli, David Morris, Henrik Frystyk Nielsen, Dave Raggett, Eric Rescorla, Tony Sanders, Lawrence C. Stewart, Marc VanHeyningen, and Steve Zilles. This document builds on the many contributions that went into past specifications of HTTP, including [HTTP/1.0], [[RFC2068](https://datatracker.ietf.org/doc/html/rfc2068)], [[RFC2145](https://datatracker.ietf.org/doc/html/rfc2145)], [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)], [[RFC2617](https://datatracker.ietf.org/doc/html/rfc2617)], [[RFC2818](https://datatracker.ietf.org/doc/html/rfc2818)], [[RFC7230](https://datatracker.ietf.org/doc/html/rfc7230)], [[RFC7231](https://datatracker.ietf.org/doc/html/rfc7231)], [[RFC7232](https://datatracker.ietf.org/doc/html/rfc7232)], [[RFC7233](https://datatracker.ietf.org/doc/html/rfc7233)], [[RFC7234](https://datatracker.ietf.org/doc/html/rfc7234)], and [[RFC7235](https://datatracker.ietf.org/doc/html/rfc7235)]. The acknowledgements within those documents still apply. Since 2014, the following contributors have helped improve this specification by reporting bugs, asking smart questions, drafting or reviewing text, and evaluating issues: Alan Egerton, Alex Rousskov, Amichai Rothman, Amos Jeffries, Anders Kaseorg, Andreas Gebhardt, Anne van Kesteren, Armin Abfalterer, Aron Duby, Asanka Herath, Asbjørn Ulsberg, Asta Olofsson, Attila Gulyas, Austin Wright, Barry Pollard, Ben Burkert, Benjamin Kaduk, Björn Höhrmann, Brad Fitzpatrick, Chris Pacejo, Colin Bendell, Cory Benfield, Cory Nelson, Daisuke Miyakawa, Dale Worley, Daniel Stenberg, Danil Suits, David Benjamin, David Matson, David Schinazi, Дилян Палаузов (Dilyan Palauzov), Eric Anderson, Eric Rescorla, Éric Vyncke, Erik Kline, Erwin Pe, Etan Kissling, Evert Pot, Evgeny Vrublevsky, Florian Best, Francesca Palombini, Igor Lubashev, James Callahan, James Peach, Jeffrey Yasskin, Kalin Gyokov, Kannan Goundan, 奥 一穂 (Kazuho Oku), Ken Murchison, Krzysztof Maczyński, Lars Eggert, Lucas Pardue, Martin Duke, Martin Dürst, Martin Thomson, Martynas Jusevičius, Matt Menke, Matthias Pigulla, Mattias Grenfeldt, Michael Osipov, Mike Bishop, Mike Pennisi, Mike Taylor, Mike West, Mohit Sethi, Murray Kucherawy, Nathaniel J. Smith, Nicholas Hurley, Nikita Prokhorov, Patrick McManus, Piotr Sikora, Poul-Henning Kamp, Rick van Rein, Robert Wilton, Roberto Polli, Roman Danyliw, Samuel Williams, Semyon Kholodnov, Simon Pieters, Simon Schüppel, Stefan Eissing, Taylor Hunt, Todd Greer, Tommy Pauly, Vasiliy Faronov, Vladimir Lashchev, Wenbo Zhu, William A. Rowe Jr., Willy Tarreau, Xingwei Liu, Yishuai Li, and Zaheduzzaman Sarker. Index 1 2 3 4 5 A B C D E F G H I L M N O P R S T U V W X 1 100 Continue (status code) \*\_[Section 15.2.1](#section-15.2.1)\_\* 100-continue (expect value) \*\_[Section 10.1.1](#section-10.1.1)\_\* 101 Switching Protocols (status code) \*\_[Section 15.2.2](#section-15.2.2)\_\* 1xx Informational (status code class) \*\_[Section 15.2](#section-15.2)\_\* 2 200 OK (status code) \*\_[Section 15.3.1](#section-15.3.1)\_\* 201 Created (status code) \*\_[Section 15.3.2](#section-15.3.2)\_\* 202 Accepted (status code) \*\_[Section 15.3.3](#section-15.3.3)\_\* 203 Non-Authoritative Information (status code) \*\_[Section 15.3](#section-15.3) .4\_\* 204 No Content (status code) \*\_[Section 15.3.5](#section-15.3.5)\_\* 205 Reset Content (status code) \*\_[Section 15.3.6](#section-15.3.6)\_\* 206 Partial Content (status code) \*\_[Section 15.3.7](#section-15.3.7)\_\* 2xx Successful (status code class) \*\_[Section 15.3](#section-15.3)\_\* 3 300 Multiple Choices (status code) \*\_[Section 15.4.1](#section-15.4.1)\_\* 301 Moved Permanently (status code) \*\_[Section 15.4.2](#section-15.4.2)\_\* 302 Found (status code) \*\_[Section 15.4.3](#section-15.4.3)\_\* 303 See Other (status code) \*\_[Section 15.4.4](#section-15.4.4)\_\* 304 Not Modified (status code) \*\_[Section 15.4.5](#section-15.4.5)\_\* 305 Use Proxy (status code) \*\_[Section 15.4.6](#section-15.4.6)\_\* 306 (Unused) (status code) \*\_[Section 15.4.7](#section-15.4.7)\_\* 307 Temporary Redirect (status code) \*\_[Section 15.4.8](#section-15.4.8)\_\* 308 Permanent Redirect (status code) \*\_[Section 15.4.9](#section-15.4.9)\_\* 3xx Redirection (status code class) \*\_[Section 15.4](#section-15.4)\_\* 4 400 Bad Request (status code) \*\_[Section 15.5.1](#section-15.5.1)\_\* 401 Unauthorized (status code) \*\_[Section 15.5.2](#section-15.5.2)\_\* 402 Payment Required (status code) \*\_[Section 15.5.3](#section-15.5.3)\_\* 403 Forbidden (status code) \*\_[Section 15.5.4](#section-15.5.4)\_\* 404 Not Found (status code) \*\_[Section 15.5.5](#section-15.5.5)\_\* 405 Method Not Allowed (status code) \*\_[Section 15.5.6](#section-15.5.6)\_\* 406 Not Acceptable (status code) \*\_[Section 15.5.7](#section-15.5.7)\_\* 407 Proxy Authentication Required (status code) \*\_[Section 15.5](#section-15.5) .8\_\* 408 Request Timeout (status code) \*\_[Section 15.5.9](#section-15.5.9)\_\* 409 Conflict (status code) \*\_[Section 15.5.10](#section-15.5.10)\_\* 410 Gone (status code) \*\_[Section 15.5.11](#section-15.5.11)\_\* 411 Length Required (status code) \*\_[Section 15.5.12](#section-15.5.12)\_\* 412 Precondition Failed (status code) \*\_[Section 15.5.13](#section-15.5.13)\_\* 413 Content Too Large (status code) \*\_[Section 15.5.14](#section-15.5.14)\_\* 414 URI Too Long (status code) \*\_[Section 15.5.15](#section-15.5.15)\_\* 415 Unsupported Media Type (status code) \*\_[Section 15.5.16](#section-15.5.16)\_\* 416 Range Not Satisfiable (status code) \*\_[Section 15.5.17](#section-15.5.17)\_\* 417 Expectation Failed (status code) \*\_[Section 15.5.18](#section-15.5.18)\_\* 418 (Unused) (status code) \*\_[Section 15.5.19](#section-15.5.19)\_\* 421 Misdirected Request (status code) \*\_[Section 15.5.20](#section-15.5.20)\_\* 422 Unprocessable Content (status code) \*\_[Section 15.5.21](#section-15.5.21)\_\* 426 Upgrade Required (status code) \*\_[Section 15.5.22](#section-15.5.22)\_\* 4xx Client Error (status code class) \*\_[Section 15.5](#section-15.5)\_\* 5 500 Internal Server Error (status code) \*\_[Section 15.6.1](#section-15.6.1)\_\* 501 Not Implemented (status code) \*\_[Section 15.6.2](#section-15.6.2)\_\* 502 Bad Gateway (status code) \*\_[Section 15.6.3](#section-15.6.3)\_\* 503 Service Unavailable (status code) \*\_[Section 15.6.4](#section-15.6.4)\_\* 504 Gateway Timeout (status code) \*\_[Section 15.6.5](#section-15.6.5)\_\* 505 HTTP Version Not Supported (status code) \*\_[Section 15.6.6](#section-15.6.6)\_ \* 5xx Server Error (status code class) \*\_[Section 15.6](#section-15.6)\_\* A accelerator \*\_[Section 3.7](#section-3.7), Paragraph 6\_\* Accept header field \*\_[Section 12.5.1](#section-12.5.1)\_\* Accept-Charset header field \*\_[Section 12.5.2](#section-12.5.2)\_\* Accept-Encoding header field \*\_[Section 12.5.3](#section-12.5.3)\_\* Accept-Language header field \*\_[Section 12.5.4](#section-12.5.4)\_\* Accept-Ranges header field \*\_[Section 14.3](#section-14.3)\_\* Allow header field \*\_[Section 10.2.1](#section-10.2.1)\_\* Authentication-Info header field \*\_[Section 11.6.3](#section-11.6.3)\_\* authoritative response \*\_[Section 17.1](#section-17.1)\_\* Authorization header field \*\_[Section 11.6.2](#section-11.6.2)\_\* B browser \*\_[Section 3.5](#section-3.5)\_\* C cache \*\_[Section 3.8](#section-3.8)\_\* cacheable \*\_[Section 3.8](#section-3.8), Paragraph 4\_\* client \*\_[Section 3.3](#section-3.3)\_\* clock \*\_[Section 5.6.7](#section-5.6.7)\_\* complete \*\_[Section 6.1](#section-6.1)\_\* compress (Coding Format) [Section 8.4.1.1](#section-8.4.1.1) compress (content coding) \*\_[Section 8.4.1](#section-8.4.1)\_\* conditional request \*\_[Section 13](#section-13)\_\* CONNECT method \*\_[Section 9.3.6](#section-9.3.6)\_\* connection \*\_[Section 3.3](#section-3.3)\_\* Connection header field \*\_[Section 7.6.1](#section-7.6.1)\_\* content [Section 6.4](#section-6.4) content coding \*\_[Section 8.4.1](#section-8.4.1)\_\* content negotiation [Section 1.3](#section-1.3), Paragraph 4 Content-Encoding header field \*\_[Section 8.4](#section-8.4)\_\* Content-Language header field \*\_[Section 8.5](#section-8.5)\_\* Content-Length header field \*\_[Section 8.6](#section-8.6)\_\* Content-Location header field \*\_[Section 8.7](#section-8.7)\_\* Content-MD5 header field \*\_[Section 18.4](#section-18.4), Paragraph 10\_\* Content-Range header field \*\_[Section 14.4](#section-14.4)\_\*; [Section 14.5](#section-14.5) Content-Type header field \*\_[Section 8.3](#section-8.3)\_\* control data \*\_[Section 6.2](#section-6.2)\_\* D Date header field \*\_[Section 6.6.1](#section-6.6.1)\_\* deflate (Coding Format) [Section 8.4.1.2](#section-8.4.1.2) deflate (content coding) \*\_[Section 8.4.1](#section-8.4.1)\_\* DELETE method \*\_[Section 9.3.5](#section-9.3.5)\_\* Delimiters [Section 5.6.2](#section-5.6.2), Paragraph 3 downstream \*\_[Section 3.7](#section-3.7), Paragraph 4\_\* E effective request URI \*\_[Section 7.1](#section-7.1), Paragraph 8.1\_\* ETag field \*\_[Section 8.8.3](#section-8.8.3)\_\* Expect header field \*\_[Section 10.1.1](#section-10.1.1)\_\* F field \*\_[Section 5](#section-5)\_\*; [Section 6.3](#section-6.3) field line [Section 5.2](#section-5.2), Paragraph 1 field line value [Section 5.2](#section-5.2), Paragraph 1 field name [Section 5.2](#section-5.2), Paragraph 1 field value [Section 5.2](#section-5.2), Paragraph 2 Fields \* \*\_[Section 18.4](#section-18.4), Paragraph 9\_\* Accept \*\_[Section 12.5.1](#section-12.5.1)\_\* Accept-Charset \*\_[Section 12.5.2](#section-12.5.2)\_\* Accept-Encoding \*\_[Section 12.5.3](#section-12.5.3)\_\* Accept-Language \*\_[Section 12.5.4](#section-12.5.4)\_\* Accept-Ranges \*\_[Section 14.3](#section-14.3)\_\* Allow \*\_[Section 10.2.1](#section-10.2.1)\_\* Authentication-Info \*\_[Section 11.6.3](#section-11.6.3)\_\* Authorization \*\_[Section 11.6.2](#section-11.6.2)\_\* Connection \*\_[Section 7.6.1](#section-7.6.1)\_\* Content-Encoding \*\_[Section 8.4](#section-8.4)\_\* Content-Language \*\_[Section 8.5](#section-8.5)\_\* Content-Length \*\_[Section 8.6](#section-8.6)\_\* Content-Location \*\_[Section 8.7](#section-8.7)\_\* Content-MD5 \*\_[Section 18.4](#section-18.4), Paragraph 10\_\* Content-Range \*\_[Section 14.4](#section-14.4)\_\*; [Section 14.5](#section-14.5) Content-Type \*\_[Section 8.3](#section-8.3)\_\* Date \*\_[Section 6.6.1](#section-6.6.1)\_\* ETag \*\_[Section 8.8.3](#section-8.8.3)\_\* Expect \*\_[Section 10.1.1](#section-10.1.1)\_\* From \*\_[Section 10.1.2](#section-10.1.2)\_\* Host \*\_[Section 7.2](#section-7.2)\_\* If-Match \*\_[Section 13.1.1](#section-13.1.1)\_\* If-Modified-Since \*\_[Section 13.1.3](#section-13.1.3)\_\* If-None-Match \*\_[Section 13.1.2](#section-13.1.2)\_\* If-Range \*\_[Section 13.1.5](#section-13.1.5)\_\* If-Unmodified-Since \*\_[Section 13.1.4](#section-13.1.4)\_\* Last-Modified \*\_[Section 8.8.2](#section-8.8.2)\_\* Location \*\_[Section 10.2.2](#section-10.2.2)\_\* Max-Forwards \*\_[Section 7.6.2](#section-7.6.2)\_\* Proxy-Authenticate \*\_[Section 11.7.1](#section-11.7.1)\_\* Proxy-Authentication-Info \*\_[Section 11.7.3](#section-11.7.3)\_\* Proxy-Authorization \*\_[Section 11.7.2](#section-11.7.2)\_\* Range \*\_[Section 14.2](#section-14.2)\_\* Referer \*\_[Section 10.1.3](#section-10.1.3)\_\* Retry-After \*\_[Section 10.2.3](#section-10.2.3)\_\* Server \*\_[Section 10.2.4](#section-10.2.4)\_\* TE \*\_[Section 10.1.4](#section-10.1.4)\_\* Trailer \*\_[Section 6.6.2](#section-6.6.2)\_\* Upgrade \*\_[Section 7.8](#section-7.8)\_\* User-Agent \*\_[Section 10.1.5](#section-10.1.5)\_\* Vary \*\_[Section 12.5.5](#section-12.5.5)\_\* Via \*\_[Section 7.6.3](#section-7.6.3)\_\* WWW-Authenticate \*\_[Section 11.6.1](#section-11.6.1)\_\* Fragment Identifiers [Section 4.2.5](#section-4.2.5) From header field \*\_[Section 10.1.2](#section-10.1.2)\_\* G gateway \*\_[Section 3.7](#section-3.7), Paragraph 6\_\* GET method \*\_[Section 9.3.1](#section-9.3.1)\_\* Grammar ALPHA \*\_[Section 2.1](#section-2.1)\_\* Accept \*\_[Section 12.5.1](#section-12.5.1)\_\* Accept-Charset \*\_[Section 12.5.2](#section-12.5.2)\_\* Accept-Encoding \*\_[Section 12.5.3](#section-12.5.3)\_\* Accept-Language \*\_[Section 12.5.4](#section-12.5.4)\_\* Accept-Ranges \*\_[Section 14.3](#section-14.3)\_\* Allow \*\_[Section 10.2.1](#section-10.2.1)\_\* Authentication-Info \*\_[Section 11.6.3](#section-11.6.3)\_\* Authorization \*\_[Section 11.6.2](#section-11.6.2)\_\* BWS \*\_[Section 5.6.3](#section-5.6.3)\_\* CR \*\_[Section 2.1](#section-2.1)\_\* CRLF \*\_[Section 2.1](#section-2.1)\_\* CTL \*\_[Section 2.1](#section-2.1)\_\* Connection \*\_[Section 7.6.1](#section-7.6.1)\_\* Content-Encoding \*\_[Section 8.4](#section-8.4)\_\* Content-Language \*\_[Section 8.5](#section-8.5)\_\* Content-Length \*\_[Section 8.6](#section-8.6)\_\* Content-Location \*\_[Section 8.7](#section-8.7)\_\* Content-Range \*\_[Section 14.4](#section-14.4)\_\* Content-Type \*\_[Section 8.3](#section-8.3)\_\* DIGIT \*\_[Section 2.1](#section-2.1)\_\* DQUOTE \*\_[Section 2.1](#section-2.1)\_\* Date \*\_[Section 6.6.1](#section-6.6.1)\_\* ETag \*\_[Section 8.8.3](#section-8.8.3)\_\* Expect \*\_[Section 10.1.1](#section-10.1.1)\_\* From \*\_[Section 10.1.2](#section-10.1.2)\_\* GMT \*\_[Section 5.6.7](#section-5.6.7)\_\* HEXDIG \*\_[Section 2.1](#section-2.1)\_\* HTAB \*\_[Section 2.1](#section-2.1)\_\* HTTP-date \*\_[Section 5.6.7](#section-5.6.7)\_\* Host \*\_[Section 7.2](#section-7.2)\_\* IMF-fixdate \*\_[Section 5.6.7](#section-5.6.7)\_\* If-Match \*\_[Section 13.1.1](#section-13.1.1)\_\* If-Modified-Since \*\_[Section 13.1.3](#section-13.1.3)\_\* If-None-Match \*\_[Section 13.1.2](#section-13.1.2)\_\* If-Range \*\_[Section 13.1.5](#section-13.1.5)\_\* If-Unmodified-Since \*\_[Section 13.1.4](#section-13.1.4)\_\* LF \*\_[Section 2.1](#section-2.1)\_\* Last-Modified \*\_[Section 8.8.2](#section-8.8.2)\_\* Location \*\_[Section 10.2.2](#section-10.2.2)\_\* Max-Forwards \*\_[Section 7.6.2](#section-7.6.2)\_\* OCTET \*\_[Section 2.1](#section-2.1)\_\* OWS \*\_[Section 5.6.3](#section-5.6.3)\_\* Proxy-Authenticate \*\_[Section 11.7.1](#section-11.7.1)\_\* Proxy-Authentication-Info \*\_[Section 11.7.3](#section-11.7.3)\_\* Proxy-Authorization \*\_[Section 11.7.2](#section-11.7.2)\_\* RWS \*\_[Section 5.6.3](#section-5.6.3)\_\* Range \*\_[Section 14.2](#section-14.2)\_\* Referer \*\_[Section 10.1.3](#section-10.1.3)\_\* Retry-After \*\_[Section 10.2.3](#section-10.2.3)\_\* SP \*\_[Section 2.1](#section-2.1)\_\* Server \*\_[Section 10.2.4](#section-10.2.4)\_\* TE \*\_[Section 10.1.4](#section-10.1.4)\_\* Trailer \*\_[Section 6.6.2](#section-6.6.2)\_\* URI-reference \*\_[Section 4.1](#section-4.1)\_\* Upgrade \*\_[Section 7.8](#section-7.8)\_\* User-Agent \*\_[Section 10.1.5](#section-10.1.5)\_\* VCHAR \*\_[Section 2.1](#section-2.1)\_\* Vary \*\_[Section 12.5.5](#section-12.5.5)\_\* Via \*\_[Section 7.6.3](#section-7.6.3)\_\* WWW-Authenticate \*\_[Section 11.6.1](#section-11.6.1)\_\* absolute-URI \*\_[Section 4.1](#section-4.1)\_\* absolute-path \*\_[Section 4.1](#section-4.1)\_\* acceptable-ranges \*\_[Section 14.3](#section-14.3)\_\* asctime-date \*\_[Section 5.6.7](#section-5.6.7)\_\* auth-param \*\_[Section 11.2](#section-11.2)\_\* auth-scheme \*\_[Section 11.1](#section-11.1)\_\* authority \*\_[Section 4.1](#section-4.1)\_\* challenge \*\_[Section 11.3](#section-11.3)\_\* codings \*\_[Section 12.5.3](#section-12.5.3)\_\* comment \*\_[Section 5.6.5](#section-5.6.5)\_\* complete-length \*\_[Section 14.4](#section-14.4)\_\* connection-option \*\_[Section 7.6.1](#section-7.6.1)\_\* content-coding \*\_[Section 8.4.1](#section-8.4.1)\_\* credentials \*\_[Section 11.4](#section-11.4)\_\* ctext \*\_[Section 5.6.5](#section-5.6.5)\_\* date1 \*\_[Section 5.6.7](#section-5.6.7)\_\* day \*\_[Section 5.6.7](#section-5.6.7)\_\* day-name \*\_[Section 5.6.7](#section-5.6.7)\_\* day-name-l \*\_[Section 5.6.7](#section-5.6.7)\_\* delay-seconds \*\_[Section 10.2.3](#section-10.2.3)\_\* entity-tag \*\_[Section 8.8.3](#section-8.8.3)\_\* etagc \*\_[Section 8.8.3](#section-8.8.3)\_\* field-content \*\_[Section 5.5](#section-5.5)\_\* field-name \*\_[Section 5.1](#section-5.1)\_\*; [Section 6.6.2](#section-6.6.2) field-value \*\_[Section 5.5](#section-5.5)\_\* field-vchar \*\_[Section 5.5](#section-5.5)\_\* first-pos \*\_[Section 14.1.1](#section-14.1.1)\_\*; [Section 14.4](#section-14.4) hour \*\_[Section 5.6.7](#section-5.6.7)\_\* http-URI \*\_[Section 4.2.1](#section-4.2.1)\_\* https-URI \*\_[Section 4.2.2](#section-4.2.2)\_\* incl-range \*\_[Section 14.4](#section-14.4)\_\* int-range \*\_[Section 14.1.1](#section-14.1.1)\_\* language-range \*\_[Section 12.5.4](#section-12.5.4)\_\* language-tag \*\_[Section 8.5.1](#section-8.5.1)\_\* last-pos \*\_[Section 14.1.1](#section-14.1.1)\_\*; [Section 14.4](#section-14.4) media-range \*\_[Section 12.5.1](#section-12.5.1)\_\* media-type \*\_[Section 8.3.1](#section-8.3.1)\_\* method \*\_[Section 9.1](#section-9.1)\_\* minute \*\_[Section 5.6.7](#section-5.6.7)\_\* month \*\_[Section 5.6.7](#section-5.6.7)\_\* obs-date \*\_[Section 5.6.7](#section-5.6.7)\_\* obs-text \*\_[Section 5.5](#section-5.5)\_\* opaque-tag \*\_[Section 8.8.3](#section-8.8.3)\_\* other-range \*\_[Section 14.1.1](#section-14.1.1)\_\* parameter \*\_[Section 5.6.6](#section-5.6.6)\_\* parameter-name \*\_[Section 5.6.6](#section-5.6.6)\_\* parameter-value \*\_[Section 5.6.6](#section-5.6.6)\_\* parameters \*\_[Section 5.6.6](#section-5.6.6)\_\* partial-URI \*\_[Section 4.1](#section-4.1)\_\* port \*\_[Section 4.1](#section-4.1)\_\* product \*\_[Section 10.1.5](#section-10.1.5)\_\* product-version \*\_[Section 10.1.5](#section-10.1.5)\_\* protocol-name \*\_[Section 7.6.3](#section-7.6.3)\_\* protocol-version \*\_[Section 7.6.3](#section-7.6.3)\_\* pseudonym \*\_[Section 7.6.3](#section-7.6.3)\_\* qdtext \*\_[Section 5.6.4](#section-5.6.4)\_\* query \*\_[Section 4.1](#section-4.1)\_\* quoted-pair \*\_[Section 5.6.4](#section-5.6.4)\_\* quoted-string \*\_[Section 5.6.4](#section-5.6.4)\_\* qvalue \*\_[Section 12.4.2](#section-12.4.2)\_\* range-resp \*\_[Section 14.4](#section-14.4)\_\* range-set \*\_[Section 14.1.1](#section-14.1.1)\_\* range-spec \*\_[Section 14.1.1](#section-14.1.1)\_\* range-unit \*\_[Section 14.1](#section-14.1)\_\* ranges-specifier \*\_[Section 14.1.1](#section-14.1.1)\_\* received-by \*\_[Section 7.6.3](#section-7.6.3)\_\* received-protocol \*\_[Section 7.6.3](#section-7.6.3)\_\* [rfc850](https://datatracker.ietf.org/doc/html/rfc850)-date \*\_[Section 5.6.7](#section-5.6.7)\_\* second \*\_[Section 5.6.7](#section-5.6.7)\_\* segment \*\_[Section 4.1](#section-4.1)\_\* subtype \*\_[Section 8.3.1](#section-8.3.1)\_\* suffix-length \*\_[Section 14.1.1](#section-14.1.1)\_\* suffix-range \*\_[Section 14.1.1](#section-14.1.1)\_\* t-codings \*\_[Section 10.1.4](#section-10.1.4)\_\* tchar \*\_[Section 5.6.2](#section-5.6.2)\_\* time-of-day \*\_[Section 5.6.7](#section-5.6.7)\_\* token \*\_[Section 5.6.2](#section-5.6.2)\_\* token68 \*\_[Section 11.2](#section-11.2)\_\* transfer-coding \*\_[Section 10.1.4](#section-10.1.4)\_\* transfer-parameter \*\_[Section 10.1.4](#section-10.1.4)\_\* type \*\_[Section 8.3.1](#section-8.3.1)\_\* unsatisfied-range \*\_[Section 14.4](#section-14.4)\_\* uri-host \*\_[Section 4.1](#section-4.1)\_\* weak \*\_[Section 8.8.3](#section-8.8.3)\_\* weight \*\_[Section 12.4.2](#section-12.4.2)\_\* year \*\_[Section 5.6.7](#section-5.6.7)\_\* gzip (Coding Format) [Section 8.4.1.3](#section-8.4.1.3) gzip (content coding) \*\_[Section 8.4.1](#section-8.4.1)\_\* H HEAD method \*\_[Section 9.3.2](#section-9.3.2)\_\* Header Fields Accept \*\_[Section 12.5.1](#section-12.5.1)\_\* Accept-Charset \*\_[Section 12.5.2](#section-12.5.2)\_\* Accept-Encoding \*\_[Section 12.5.3](#section-12.5.3)\_\* Accept-Language \*\_[Section 12.5.4](#section-12.5.4)\_\* Accept-Ranges \*\_[Section 14.3](#section-14.3)\_\* Allow \*\_[Section 10.2.1](#section-10.2.1)\_\* Authentication-Info \*\_[Section 11.6.3](#section-11.6.3)\_\* Authorization \*\_[Section 11.6.2](#section-11.6.2)\_\* Connection \*\_[Section 7.6.1](#section-7.6.1)\_\* Content-Encoding \*\_[Section 8.4](#section-8.4)\_\* Content-Language \*\_[Section 8.5](#section-8.5)\_\* Content-Length \*\_[Section 8.6](#section-8.6)\_\* Content-Location \*\_[Section 8.7](#section-8.7)\_\* Content-MD5 \*\_[Section 18.4](#section-18.4), Paragraph 10\_\* Content-Range \*\_[Section 14.4](#section-14.4)\_\*; [Section 14.5](#section-14.5) Content-Type \*\_[Section 8.3](#section-8.3)\_\* Date \*\_[Section 6.6.1](#section-6.6.1)\_\* ETag \*\_[Section 8.8.3](#section-8.8.3)\_\* Expect \*\_[Section 10.1.1](#section-10.1.1)\_\* From \*\_[Section 10.1.2](#section-10.1.2)\_\* Host \*\_[Section 7.2](#section-7.2)\_\* If-Match \*\_[Section 13.1.1](#section-13.1.1)\_\* If-Modified-Since \*\_[Section 13.1.3](#section-13.1.3)\_\* If-None-Match \*\_[Section 13.1.2](#section-13.1.2)\_\* If-Range \*\_[Section 13.1.5](#section-13.1.5)\_\* If-Unmodified-Since \*\_[Section 13.1.4](#section-13.1.4)\_\* Last-Modified \*\_[Section 8.8.2](#section-8.8.2)\_\* Location \*\_[Section 10.2.2](#section-10.2.2)\_\* Max-Forwards \*\_[Section 7.6.2](#section-7.6.2)\_\* Proxy-Authenticate \*\_[Section 11.7.1](#section-11.7.1)\_\* Proxy-Authentication-Info \*\_[Section 11.7.3](#section-11.7.3)\_\* Proxy-Authorization \*\_[Section 11.7.2](#section-11.7.2)\_\* Range \*\_[Section 14.2](#section-14.2)\_\* Referer \*\_[Section 10.1.3](#section-10.1.3)\_\* Retry-After \*\_[Section 10.2.3](#section-10.2.3)\_\* Server \*\_[Section 10.2.4](#section-10.2.4)\_\* TE \*\_[Section 10.1.4](#section-10.1.4)\_\* Trailer \*\_[Section 6.6.2](#section-6.6.2)\_\* Upgrade \*\_[Section 7.8](#section-7.8)\_\* User-Agent \*\_[Section 10.1.5](#section-10.1.5)\_\* Vary \*\_[Section 12.5.5](#section-12.5.5)\_\* Via \*\_[Section 7.6.3](#section-7.6.3)\_\* WWW-Authenticate \*\_[Section 11.6.1](#section-11.6.1)\_\* header section \*\_[Section 6.3](#section-6.3)\_\* Host header field \*\_[Section 7.2](#section-7.2)\_\* http URI scheme \*\_[Section 4.2.1](#section-4.2.1)\_\* https URI scheme \*\_[Section 4.2.2](#section-4.2.2)\_\* I idempotent \*\_[Section 9.2.2](#section-9.2.2)\_\* If-Match header field \*\_[Section 13.1.1](#section-13.1.1)\_\* If-Modified-Since header field \*\_[Section 13.1.3](#section-13.1.3)\_\* If-None-Match header field \*\_[Section 13.1.2](#section-13.1.2)\_\* If-Range header field \*\_[Section 13.1.5](#section-13.1.5)\_\* If-Unmodified-Since header field \*\_[Section 13.1.4](#section-13.1.4)\_\* inbound \*\_[Section 3.7](#section-3.7), Paragraph 4\_\* incomplete \*\_[Section 6.1](#section-6.1)\_\* interception proxy \*\_[Section 3.7](#section-3.7), Paragraph 10\_\* intermediary \*\_[Section 3.7](#section-3.7)\_\* L Last-Modified header field \*\_[Section 8.8.2](#section-8.8.2)\_\* list-based field [Section 5.5](#section-5.5), Paragraph 7 Location header field \*\_[Section 10.2.2](#section-10.2.2)\_\* M Max-Forwards header field \*\_[Section 7.6.2](#section-7.6.2)\_\* Media Type multipart/byteranges \*\_[Section 14.6](#section-14.6)\_\* multipart/x-byteranges [Section 14.6](#section-14.6), Paragraph 4, Item 3 message [Section 3.4](#section-3.4); \*\_[Section 6](#section-6)\_\* message abstraction \*\_[Section 6](#section-6)\_\* messages \*\_[Section 3.4](#section-3.4)\_\* metadata \*\_[Section 8.8](#section-8.8)\_\* Method \* \*\_[Section 18.2](#section-18.2), Paragraph 3\_\* CONNECT \*\_[Section 9.3.6](#section-9.3.6)\_\* DELETE \*\_[Section 9.3.5](#section-9.3.5)\_\* GET \*\_[Section 9.3.1](#section-9.3.1)\_\* HEAD \*\_[Section 9.3.2](#section-9.3.2)\_\* OPTIONS \*\_[Section 9.3.7](#section-9.3.7)\_\* POST \*\_[Section 9.3.3](#section-9.3.3)\_\* PUT \*\_[Section 9.3.4](#section-9.3.4)\_\* TRACE \*\_[Section 9.3.8](#section-9.3.8)\_\* multipart/byteranges Media Type \*\_[Section 14.6](#section-14.6)\_\* multipart/x-byteranges Media Type [Section 14.6](#section-14.6), Paragraph 4, Item 3 N non-transforming proxy \*\_[Section 7.7](#section-7.7)\_\* O OPTIONS method \*\_[Section 9.3.7](#section-9.3.7)\_\* origin \*\_[Section 4.3.1](#section-4.3.1)\_\*; [Section 11.5](#section-11.5) origin server \*\_[Section 3.6](#section-3.6)\_\* outbound \*\_[Section 3.7](#section-3.7), Paragraph 4\_\* P phishing \*\_[Section 17.1](#section-17.1)\_\* POST method \*\_[Section 9.3.3](#section-9.3.3)\_\* Protection Space [Section 11.5](#section-11.5) proxy \*\_[Section 3.7](#section-3.7), Paragraph 5\_\* Proxy-Authenticate header field \*\_[Section 11.7.1](#section-11.7.1)\_\* Proxy-Authentication-Info header field \*\_[Section 11.7.3](#section-11.7.3)\_\* Proxy-Authorization header field \*\_[Section 11.7.2](#section-11.7.2)\_\* PUT method \*\_[Section 9.3.4](#section-9.3.4)\_\* R Range header field \*\_[Section 14.2](#section-14.2)\_\* Realm [Section 11.5](#section-11.5) recipient \*\_[Section 3.4](#section-3.4)\_\* Referer header field \*\_[Section 10.1.3](#section-10.1.3)\_\* representation \*\_[Section 3.2](#section-3.2)\_\* request \*\_[Section 3.4](#section-3.4)\_\* request target \*\_[Section 7.1](#section-7.1)\_\* resource \*\_[Section 3.1](#section-3.1)\_\*; [Section 4](#section-4) response \*\_[Section 3.4](#section-3.4)\_\* Retry-After header field \*\_[Section 10.2.3](#section-10.2.3)\_\* reverse proxy \*\_[Section 3.7](#section-3.7), Paragraph 6\_\* S safe \*\_[Section 9.2.1](#section-9.2.1)\_\* satisfiable range \*\_[Section 14.1.1](#section-14.1.1)\_\* secured \*\_[Section 4.2.2](#section-4.2.2)\_\* selected representation \*\_[Section 3.2](#section-3.2), Paragraph 4\_\*; [Section 8.8](#section-8.8); [Section 13.1](#section-13.1) self-descriptive \*\_[Section 6](#section-6)\_\* sender \*\_[Section 3.4](#section-3.4)\_\* server \*\_[Section 3.3](#section-3.3)\_\* Server header field \*\_[Section 10.2.4](#section-10.2.4)\_\* singleton field [Section 5.5](#section-5.5), Paragraph 6 spider \*\_[Section 3.5](#section-3.5)\_\* Status Code [Section 15](#section-15) Status Codes Final [Section 15](#section-15), Paragraph 7 Informational [Section 15](#section-15), Paragraph 7 Interim [Section 15](#section-15), Paragraph 7 Status Codes Classes 1xx Informational \*\_[Section 15.2](#section-15.2)\_\* 2xx Successful \*\_[Section 15.3](#section-15.3)\_\* 3xx Redirection \*\_[Section 15.4](#section-15.4)\_\* 4xx Client Error \*\_[Section 15.5](#section-15.5)\_\* 5xx Server Error \*\_[Section 15.6](#section-15.6)\_\* T target resource \*\_[Section 7.1](#section-7.1)\_\* target URI \*\_[Section 7.1](#section-7.1)\_\* TE header field \*\_[Section 10.1.4](#section-10.1.4)\_\* TRACE method \*\_[Section 9.3.8](#section-9.3.8)\_\* Trailer Fields \*\_[Section 6.5](#section-6.5)\_\* ETag \*\_[Section 8.8.3](#section-8.8.3)\_\* Trailer header field \*\_[Section 6.6.2](#section-6.6.2)\_\* trailer section \*\_[Section 6.5](#section-6.5)\_\* trailers \*\_[Section 6.5](#section-6.5)\_\* transforming proxy \*\_[Section 7.7](#section-7.7)\_\* transparent proxy \*\_[Section 3.7](#section-3.7), Paragraph 10\_\* tunnel \*\_[Section 3.7](#section-3.7), Paragraph 8\_\* U unsatisfiable range \*\_[Section 14.1.1](#section-14.1.1)\_\* Upgrade header field \*\_[Section 7.8](#section-7.8)\_\* upstream \*\_[Section 3.7](#section-3.7), Paragraph 4\_\* URI \*\_[Section 4](#section-4)\_\* origin \*\_[Section 4.3.1](#section-4.3.1)\_\* URI reference \*\_[Section 4.1](#section-4.1)\_\* URI scheme http \*\_[Section 4.2.1](#section-4.2.1)\_\* https \*\_[Section 4.2.2](#section-4.2.2)\_\* user agent \*\_[Section 3.5](#section-3.5)\_\* User-Agent header field \*\_[Section 10.1.5](#section-10.1.5)\_\* V validator \*\_[Section 8.8](#section-8.8)\_\* strong \*\_[Section 8.8.1](#section-8.8.1)\_\* weak \*\_[Section 8.8.1](#section-8.8.1)\_\* Vary header field \*\_[Section 12.5.5](#section-12.5.5)\_\* Via header field \*\_[Section 7.6.3](#section-7.6.3)\_\* W WWW-Authenticate header field \*\_[Section 11.6.1](#section-11.6.1)\_\* X x-compress (content coding) \*\_[Section 8.4.1](#section-8.4.1)\_\* x-gzip (content coding) \*\_[Section 8.4.1](#section-8.4.1)\_\* Authors' Addresses Roy T. Fielding (editor) Adobe 345 Park Ave San Jose, CA 95110 United States of America Email: [email protected] URI: <https://roy.gbiv.com/> Mark Nottingham (editor) Fastly Prahran Australia Email: [email protected] URI: <https://www.mnot.net/> Julian Reschke (editor) greenbytes GmbH Hafenweg 16 48155 Münster Germany Email: [email protected] URI: <https://greenbytes.de/tech/webdav/>
programming_docs
http Network Error Logging Network Error Logging ===================== Network Error Logging ===================== **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. Network Error Logging is a mechanism that can be configured via the [`NEL`](headers/nel) HTTP *[response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header)*. This experimental header allows web sites and applications to opt-in to receive reports about failed (and, if desired, successful) network fetches from supporting browsers. Reports are sent to a reporting group defined within a [`Report-To`](headers/report-to) header. Usage ----- Web applications opt in to this behavior with the NEL header, which is a *[JSON-encoded](https://developer.mozilla.org/en-US/docs/Glossary/Response_header)* object: ``` NEL: { "report\_to": "nel", "max\_age": 31556952 } ``` An origin considered secure by the browser is required. The following object keys can be specified in the NEL header: report\_to The [reporting API](https://developer.mozilla.org/en-US/docs/Web/API/Reporting_API) group to send network error reports to (see below). max\_age Specifies the lifetime of the policy, in seconds (in a similar way to e.g. HSTS policies are time-restricted). The referenced reporting group should have a lifetime at least as long as the NEL policy. include\_subdomains If true, the policy applies to all subdomains under the origin that the policy header is set. The reporting group should also be set to include subdomains, if this option is to be enabled. success\_fraction Floating point value between 0 and 1 which specifies the proportion of **successful** network requests to report. Defaults to 0, so that no successful network requests will be reported if the key is not present in the JSON payload. failure\_fraction Floating point value between 0 and 1 which specifies the proportion of **failed** network requests to report. Defaults to 1, so that all failed network requests will be reported if the key is not present in the JSON payload. The reporting group referenced above is defined in the usual manner within the [`Report-To`](headers/report-to) header, for example: ``` Report-To: { "group": "nel", "max\_age": 31556952, "endpoints": [ { "url": "https://example.com/csp-reports" } ] } ``` Error reports ------------- In these examples, the entire reporting API payload is shown. The top-level `"body"` key contains the network error report. ### HTTP 400 (Bad Request) response ``` { "age": 20, "type": "network-error", "url": "https://example.com/previous-page", "body": { "elapsed\_time": 338, "method": "POST", "phase": "application", "protocol": "http/1.1", "referrer": "https://example.com/previous-page", "sampling\_fraction": 1, "server\_ip": "137.205.28.66", "status\_code": 400, "type": "http.error", "url": "https://example.com/bad-request" } } ``` ### DNS name not resolved Note that the phase is set to `dns` in this report and no `server_ip` is available to include. ``` { "age": 20, "type": "network-error", "url": "https://example.com/previous-page", "body": { "elapsed\_time": 18, "method": "POST", "phase": "dns", "protocol": "http/1.1", "referrer": "https://example.com/previous-page", "sampling\_fraction": 1, "server\_ip": "", "status\_code": 0, "type": "dns.name\_not\_resolved", "url": "https://example-host.com/" } } ``` The type of the network error may be one of the following pre-defined values from the specification, but browsers can add and send their own error types: `dns.unreachable` The user's DNS server is unreachable `dns.name_not_resolved` The user's DNS server responded but was unable to resolve an IP address for the requested URI. `dns.failed` Request to the DNS server failed due to reasons not covered by previous errors (e.g. SERVFAIL) `dns.address_changed` For security reasons, if the server IP address that delivered the original report is different to the current server IP address at time of error generation, the report data will be downgraded to only include information about this problem and the type set to `dns.address_changed`. `tcp.timed_out` TCP connection to the server timed out `tcp.closed` The TCP connection was closed by the server `tcp.reset` The TCP connection was reset `tcp.refused` The TCP connection was refused by the server `tcp.aborted` The TCP connection was aborted `tcp.address_invalid` The IP address is invalid `tcp.address_unreachable` The IP address is unreachable `tcp.failed` The TCP connection failed due to reasons not covered by previous errors `http.error` The user agent successfully received a response, but it had a [4xx](https://httpwg.org/specs/rfc9110.html#status.4xx) or [5xx](https://httpwg.org/specs/rfc9110.html#status.5xx) status code `http.protocol.error` The connection was aborted due to an HTTP protocol error `http.response.invalid` Response is empty, has a content-length mismatch, has improper encoding, and/or other conditions that prevent user agent from processing the response `http.response.redirect_loop` The request was aborted due to a detected redirect loop `http.failed` The connection failed due to errors in HTTP protocol not covered by previous errors Specifications -------------- | Specification | | --- | | [Network Error Logging # nel-response-header](https://w3c.github.io/network-error-logging/#nel-response-header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Network_Error_Logging` | 71 | 79 | No | No | 58 | No | 71 | 71 | No | 50 | No | 10.2 | http Cookies Cookies ======= Using HTTP cookies ================== An **HTTP cookie** (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser. The browser may store the cookie and send it back to the same server with later requests. Typically, an HTTP cookie is used to tell if two requests come from the same browser—keeping a user logged in, for example. It remembers stateful information for the [stateless](overview#http_is_stateless_but_not_sessionless) HTTP protocol. Cookies are mainly used for three purposes: Session management Logins, shopping carts, game scores, or anything else the server should remember Personalization User preferences, themes, and other settings Tracking Recording and analyzing user behavior Cookies were once used for general client-side storage. While this made sense when they were the only way to store data on the client, modern storage APIs are now recommended. Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API) (`localStorage` and `sessionStorage`) and [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API). **Note:** To see stored cookies (and other storage that a web page can use), you can enable the [Storage Inspector](https://firefox-source-docs.mozilla.org/devtools-user/storage_inspector/index.html) in Developer Tools and select Cookies from the storage tree. Creating cookies ---------------- After receiving an HTTP request, a server can send one or more [`Set-Cookie`](headers/set-cookie) headers with the response. The browser usually stores the cookie and sends it with requests made to the same server inside a [`Cookie`](headers/cookie) HTTP header. You can specify an expiration date or time period after which the cookie shouldn't be sent. You can also set additional restrictions to a specific domain and path to limit where the cookie is sent. For details about the header attributes mentioned below, refer to the [`Set-Cookie`](headers/set-cookie) reference article. ### The `Set-Cookie` and `Cookie` headers The [`Set-Cookie`](headers/set-cookie) HTTP response header sends cookies from the server to the user agent. A simple cookie is set like this: ``` Set-Cookie: <cookie-name>=<cookie-value> ``` This instructs the server sending headers to tell the client to store a pair of cookies: ``` HTTP/2.0 200 OK Content-Type: text/html Set-Cookie: yummy\_cookie=choco Set-Cookie: tasty\_cookie=strawberry [page content] ``` Then, with every subsequent request to the server, the browser sends all previously stored cookies back to the server using the [`Cookie`](headers/cookie) header. ``` GET /sample\_page.html HTTP/2.0 Host: www.example.org Cookie: yummy\_cookie=choco; tasty\_cookie=strawberry ``` **Note:** Here's how to use the `Set-Cookie` header in various server-side applications: * [PHP](https://www.php.net/manual/en/function.setcookie.php) * [Node.JS](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_response_setheader_name_value) * [Python](https://docs.python.org/3/library/http.cookies.html) * [Ruby on Rails](https://api.rubyonrails.org/classes/ActionDispatch/Cookies.html) ### Define the lifetime of a cookie The lifetime of a cookie can be defined in two ways: * *Session* cookies are deleted when the current session ends. The browser defines when the "current session" ends, and some browsers use *session restoring* when restarting. This can cause session cookies to last indefinitely. * *Permanent* cookies are deleted at a date specified by the `Expires` attribute, or after a period of time specified by the `Max-Age` attribute. For example: ``` Set-Cookie: id=a3fWa; Expires=Thu, 31 Oct 2021 07:28:00 GMT; ``` **Note:** When you set an `Expires` date and time, they're relative to the client the cookie is being set on, not the server. If your site authenticates users, it should regenerate and resend session cookies, even ones that already exist, whenever a user authenticates. This approach helps prevent [session fixation attacks](https://developer.mozilla.org/en-US/docs/Web/Security/Types_of_attacks#session_fixation), where a third party can reuse a user's session. ### Restrict access to cookies You can ensure that cookies are sent securely and aren't accessed by unintended parties or scripts in one of two ways: with the `Secure` attribute and the `HttpOnly` attribute. A cookie with the `Secure` attribute is only sent to the server with an encrypted request over the HTTPS protocol. It's never sent with unsecured HTTP (except on localhost), which means [man-in-the-middle](https://developer.mozilla.org/en-US/docs/Glossary/MitM) attackers can't access it easily. Insecure sites (with `http:` in the URL) can't set cookies with the `Secure` attribute. However, don't assume that `Secure` prevents all access to sensitive information in cookies. For example, someone with access to the client's hard disk (or JavaScript if the `HttpOnly` attribute isn't set) can read and modify the information. A cookie with the `HttpOnly` attribute is inaccessible to the JavaScript [`Document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) API; it's only sent to the server. For example, cookies that persist in server-side sessions don't need to be available to JavaScript and should have the `HttpOnly` attribute. This precaution helps mitigate cross-site scripting ([XSS](https://developer.mozilla.org/en-US/docs/Web/Security/Types_of_attacks#cross-site_scripting_(xss))) attacks. Here's an example: ``` Set-Cookie: id=a3fWa; Expires=Thu, 21 Oct 2021 07:28:00 GMT; Secure; HttpOnly ``` ### Define where cookies are sent The `Domain` and `Path` attributes define the *scope* of a cookie: what URLs the cookies should be sent to. #### Domain attribute The `Domain` attribute specifies which hosts can receive a cookie. If unspecified, the attribute defaults to the same [host](https://developer.mozilla.org/en-US/docs/Glossary/Host) that set the cookie, *excluding subdomains*. If `Domain` *is* specified, then subdomains are always included. Therefore, specifying `Domain` is less restrictive than omitting it. However, it can be helpful when subdomains need to share information about a user. For example, if you set `Domain=mozilla.org`, cookies are available on subdomains like `developer.mozilla.org`. #### Path attribute The `Path` attribute indicates a URL path that must exist in the requested URL in order to send the `Cookie` header. The `%x2F` ("/") character is considered a directory separator, and subdirectories match as well. For example, if you set `Path=/docs`, these request paths match: * `/docs` * `/docs/` * `/docs/Web/` * `/docs/Web/HTTP` But these request paths don't: * `/` * `/docsets` * `/fr/docs` #### SameSite attribute The [`SameSite`](headers/set-cookie/samesite) attribute lets servers specify whether/when cookies are sent with cross-site requests (where [Site](https://developer.mozilla.org/en-US/docs/Glossary/Site) is defined by the registrable domain and the *scheme*: http or https). This provides some protection against cross-site request forgery attacks ([CSRF](https://developer.mozilla.org/en-US/docs/Glossary/CSRF)). It takes three possible values: `Strict`, `Lax`, and `None`. With `Strict`, the browser only sends the cookie with requests from the cookie's origin site. `Lax` is similar, except the browser also sends the cookie when the user *navigates* to the cookie's origin site (even if the user is coming from a different site). For example, by following a link from an external site. `None` specifies that cookies are sent on both originating and cross-site requests, but *only in secure contexts* (i.e., if `SameSite=None` then the `Secure` attribute must also be set). If no `SameSite` attribute is set, the cookie is treated as `Lax`. Here's an example: ``` Set-Cookie: mykey=myvalue; SameSite=Strict ``` **Note:** The standard related to `SameSite` recently changed (MDN documents the new behavior above). See the cookies [Browser compatibility](headers/set-cookie/samesite#browser_compatibility) table for information about how the attribute is handled in specific browser versions: * `SameSite=Lax` is the new default if `SameSite` isn't specified. Previously, cookies were sent for all requests by default. * Cookies with `SameSite=None` must now also specify the `Secure` attribute (they require a secure context). * Cookies from the same domain are no longer considered to be from the same site if sent using a different scheme (`http:` or `https:`). #### Cookie prefixes Because of the design of the cookie mechanism, a server can't confirm that a cookie was set from a secure origin or even tell *where* a cookie was originally set. A vulnerable application on a subdomain can set a cookie with the `Domain` attribute, which gives access to that cookie on all other subdomains. This mechanism can be abused in a *session fixation* attack. See [session fixation](https://developer.mozilla.org/en-US/docs/Web/Security/Types_of_attacks#session_fixation) for primary mitigation methods. As a [defense-in-depth measure](https://en.wikipedia.org/wiki/Defense_in_depth_(computing)), however, you can use *cookie prefixes* to assert specific facts about the cookie. Two prefixes are available: `__Host-` If a cookie name has this prefix, it's accepted in a [`Set-Cookie`](headers/set-cookie) header only if it's also marked with the `Secure` attribute, was sent from a secure origin, does *not* include a `Domain` attribute, and has the `Path` attribute set to `/`. This way, these cookies can be seen as "domain-locked". `__Secure-` If a cookie name has this prefix, it's accepted in a [`Set-Cookie`](headers/set-cookie) header only if it's marked with the `Secure` attribute and was sent from a secure origin. This is weaker than the `__Host-` prefix. The browser will reject cookies with these prefixes that don't comply with their restrictions. Note that this ensures that subdomain-created cookies with prefixes are either confined to the subdomain or ignored completely. As the application server only checks for a specific cookie name when determining if the user is authenticated or a CSRF token is correct, this effectively acts as a defense measure against session fixation. **Note:** On the application server, the web application *must* check for the full cookie name including the prefix. User agents *do not* strip the prefix from the cookie before sending it in a request's [`Cookie`](headers/cookie) header. For more information about cookie prefixes and the current state of browser support, see the [Prefixes section of the Set-Cookie reference article](headers/set-cookie#cookie_prefixes). #### JavaScript access using Document.cookie You can create new cookies via JavaScript using the [`Document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) property. You can access existing cookies from JavaScript as well if the `HttpOnly` flag isn't set. ``` document.cookie = "yummy\_cookie=choco"; document.cookie = "tasty\_cookie=strawberry"; console.log(document.cookie); // logs "yummy\_cookie=choco; tasty\_cookie=strawberry" ``` Cookies created via JavaScript can't include the `HttpOnly` flag. Please note the security issues in the [Security](#security) section below. Cookies available to JavaScript can be stolen through XSS. Security -------- **Note:** When you store information in cookies, keep in mind that all cookie values are visible to, and can be changed by, the end user. Depending on the application, you may want to use an opaque identifier that the server looks up, or investigate alternative authentication/confidentiality mechanisms such as JSON Web Tokens. Ways to mitigate attacks involving cookies: * Use the `HttpOnly` attribute to prevent access to cookie values via JavaScript. * Cookies that are used for sensitive information (such as indicating authentication) should have a short lifetime, with the `SameSite` attribute set to `Strict` or `Lax`. (See [SameSite attribute](#samesite_attribute), above.) In [browsers that support SameSite](headers/set-cookie#browser_compatibility), this ensures that the authentication cookie isn't sent with cross-site requests. This would make the request effectively unauthenticated to the application server. Tracking and privacy -------------------- ### Third-party cookies A cookie is associated with a particular domain and scheme (such as `http` or `https`), and may also be associated with subdomains if the [`Set-Cookie`](headers/set-cookie) `Domain` attribute is set. If the cookie domain and scheme match the current page, the cookie is considered to be from the same site as the page, and is referred to as a *first-party cookie*. If the domain and scheme are different, the cookie is not considered to be from the same site, and is referred to as a *third-party cookie*. While the server hosting a web page sets first-party cookies, the page may contain images or other components stored on servers in other domains (for example, ad banners) that may set third-party cookies. These are mainly used for advertising and tracking across the web. For example, the [types of cookies used by Google](https://policies.google.com/technologies/types). A third-party server can create a profile of a user's browsing history and habits based on cookies sent to it by the same browser when accessing multiple sites. Firefox, by default, blocks third-party cookies that are known to contain trackers. Third-party cookies (or just tracking cookies) may also be blocked by other browser settings or extensions. Cookie blocking can cause some third-party components (such as social media widgets) not to function as intended. **Note:** Servers can (and should) set the cookie [SameSite attribute](headers/set-cookie/samesite) to specify whether or not cookies may be sent to third party sites. ### Cookie-related regulations Legislation or regulations that cover the use of cookies include: * The General Data Privacy Regulation (GDPR) in the European Union * The ePrivacy Directive in the EU * The California Consumer Privacy Act These regulations have global reach. They apply to any site on the *World Wide* Web that users from these jurisdictions access (the EU and California, with the caveat that California's law applies only to entities with gross revenue over 25 million USD, among things). These regulations include requirements such as: * Notifying users that your site uses cookies. * Allowing users to opt out of receiving some or all cookies. * Allowing users to use the bulk of your service without receiving cookies. There may be other regulations that govern the use of cookies in your locality. The burden is on you to know and comply with these regulations. There are companies that offer "cookie banner" code that helps you comply with these regulations. Other ways to store information in the browser ---------------------------------------------- Another approach to storing data in the browser is the [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API). The [window.sessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) and [window.localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) properties correspond to session and permanent cookies in duration, but have larger storage limits than cookies, and are never sent to a server. More structured and larger amounts of data can be stored using the [IndexedDB API](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API), or a library built on it. There are some techniques designed to recreate cookies after they're deleted. These are known as "zombie" cookies. These techniques violate the principles of user privacy and user control, may violate data privacy regulations, and could expose a website using them to legal liability. See also -------- * [`Set-Cookie`](headers/set-cookie) * [`Cookie`](headers/cookie) * [`Document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) * [`Navigator.cookieEnabled`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/cookieEnabled) * [SameSite cookies](headers/set-cookie/samesite) * [Inspecting cookies using the Storage Inspector](https://firefox-source-docs.mozilla.org/devtools-user/storage_inspector/index.html) * [Cookie specification: RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265) * [HTTP cookie on Wikipedia](https://en.wikipedia.org/wiki/HTTP_cookie) * [Cookies, the GDPR, and the ePrivacy Directive](https://gdpr.eu/cookies/)
programming_docs
http Headers Headers ======= HTTP headers ============ **HTTP headers** let the client and the server pass additional information with an HTTP request or response. An HTTP header consists of its case-insensitive name followed by a colon (`:`), then by its value. [Whitespace](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace) before the value is ignored. Custom proprietary headers have historically been used with an `X-` prefix, but this convention was deprecated in June 2012 because of the inconveniences it caused when nonstandard fields became standard in [RFC 6648](https://datatracker.ietf.org/doc/html/rfc6648); others are listed in an [IANA registry](https://www.iana.org/assignments/message-headers/message-headers.xhtml#perm-headers), whose original content was defined in [RFC 4229](https://datatracker.ietf.org/doc/html/rfc4229). IANA also maintains a [registry of proposed new HTTP headers](https://www.iana.org/assignments/message-headers/message-headers.xhtml#prov-headers). Headers can be grouped according to their contexts: * [Request headers](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) contain more information about the resource to be fetched, or about the client requesting the resource. * [Response headers](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) hold additional information about the response, like its location or about the server providing it. * [Representation headers](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header) contain information about the body of the resource, like its [MIME type](basics_of_http/mime_types), or encoding/compression applied. * [Payload headers](https://developer.mozilla.org/en-US/docs/Glossary/Payload_header) contain representation-independent information about payload data, including content length and the encoding used for transport. Headers can also be grouped according to how [proxies](https://developer.mozilla.org/en-US/docs/Glossary/Proxy_server) handle them: * [`Connection`](headers/connection) * [`Keep-Alive`](headers/keep-alive) * [`Proxy-Authenticate`](headers/proxy-authenticate) * [`Proxy-Authorization`](headers/proxy-authorization) * [`TE`](headers/te) * [`Trailer`](headers/trailer) * [`Transfer-Encoding`](headers/transfer-encoding) * [`Upgrade`](headers/upgrade) (see also [Protocol upgrade mechanism](protocol_upgrade_mechanism)). End-to-end headers These headers *must* be transmitted to the final recipient of the message: the server for a request, or the client for a response. Intermediate proxies must retransmit these headers unmodified and caches must store them. Hop-by-hop headers These headers are meaningful only for a single transport-level connection, and *must not* be retransmitted by proxies or cached. Note that only hop-by-hop headers may be set using the [`Connection`](headers/connection) header. Authentication -------------- [`WWW-Authenticate`](headers/www-authenticate) Defines the authentication method that should be used to access a resource. [`Authorization`](headers/authorization) Contains the credentials to authenticate a user-agent with a server. [`Proxy-Authenticate`](headers/proxy-authenticate) Defines the authentication method that should be used to access a resource behind a proxy server. [`Proxy-Authorization`](headers/proxy-authorization) Contains the credentials to authenticate a user agent with a proxy server. Caching ------- [`Age`](headers/age) The time, in seconds, that the object has been in a proxy cache. [`Cache-Control`](headers/cache-control) Directives for caching mechanisms in both requests and responses. [`Clear-Site-Data`](headers/clear-site-data) Clears browsing data (e.g. cookies, storage, cache) associated with the requesting website. [`Expires`](headers/expires) The date/time after which the response is considered stale. [`Pragma`](headers/pragma) Implementation-specific header that may have various effects anywhere along the request-response chain. Used for backwards compatibility with HTTP/1.0 caches where the `Cache-Control` header is not yet present. [`Warning`](headers/warning) Deprecated General warning information about possible problems. Client hints ------------ HTTP [Client hints](client_hints) are a set of request headers that provide useful information about the client such as device type and network conditions, and allow servers to optimize what is served for those conditions. Servers proactively requests the client hint headers they are interested in from the client using [`Accept-CH`](headers/accept-ch). The client may then choose to include the requested headers in subsequent requests. [`Accept-CH`](headers/accept-ch) Experimental Servers can advertise support for Client Hints using the `Accept-CH` header field or an equivalent HTML `<meta>` element with [`http-equiv`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#attr-http-equiv) attribute. [`Accept-CH-Lifetime`](headers/accept-ch-lifetime) Experimental Deprecated Servers can ask the client to remember the set of Client Hints that the server supports for a specified period of time, to enable delivery of Client Hints on subsequent requests to the server's origin. The different categories of client hints are listed below. ### User agent client hints The [UA client hints](client_hints#user-agent_client_hints) are request headers that provide information about the user agent and the platform/architecture on which it is running: [`Sec-CH-UA`](headers/sec-ch-ua) Experimental User agent's branding and version. [`Sec-CH-UA-Arch`](headers/sec-ch-ua-arch) Experimental User agent's underlying platform architecture. [`Sec-CH-UA-Bitness`](headers/sec-ch-ua-bitness) Experimental User agent's underlying CPU architecture bitness (for example "64" bit). [`Sec-CH-UA-Full-Version`](headers/sec-ch-ua-full-version) Deprecated User agent's full semantic version string. [`Sec-CH-UA-Full-Version-List`](headers/sec-ch-ua-full-version-list) Experimental Full version for each brand in the user agent's brand list. [`Sec-CH-UA-Mobile`](headers/sec-ch-ua-mobile) Experimental User agent is running on a mobile device or, more generally, prefers a "mobile" user experience. [`Sec-CH-UA-Model`](headers/sec-ch-ua-model) Experimental User agent's device model. [`Sec-CH-UA-Platform`](headers/sec-ch-ua-platform) Experimental User agent's underlying operation system/platform. [`Sec-CH-UA-Platform-Version`](headers/sec-ch-ua-platform-version) Experimental User agent's underlying operation system version. ### Device client hints [`Content-DPR`](headers/content-dpr) Deprecated Experimental *Response header* used to confirm the image device to pixel ratio in requests where the [`DPR`](headers/dpr) client hint was used to select an image resource. [`Device-Memory`](headers/device-memory) Deprecated Experimental Approximate amount of available client RAM memory. This is part of the [Device Memory API](https://developer.mozilla.org/en-US/docs/Web/API/Device_Memory_API). [`DPR`](headers/dpr) Deprecated Experimental Client device pixel ratio (DPR), which is the number of physical device pixels corresponding to every CSS pixel. [`Viewport-Width`](headers/viewport-width) Deprecated Experimental A number that indicates the layout viewport width in CSS pixels. The provided pixel value is a number rounded to the smallest following integer (i.e. ceiling value). [`Width`](headers/width) Deprecated Experimental A number that indicates the desired resource width in physical pixels (i.e. intrinsic size of an image). ### Network client hints Network client hints allow a server to choose what information is sent based on the user choice and network bandwidth and latency. [`Downlink`](headers/downlink) Approximate bandwidth of the client's connection to the server, in Mbps. This is part of the [Network Information API](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API). [`ECT`](headers/ect) The [effective connection type](https://developer.mozilla.org/en-US/docs/Glossary/Effective_connection_type) ("network profile") that best matches the connection's latency and bandwidth. This is part of the [Network Information API](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API). [`RTT`](headers/rtt) Application layer round trip time (RTT) in milliseconds, which includes the server processing time. This is part of the [Network Information API](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API). [`Save-Data`](headers/save-data) Experimental A boolean that indicates the user agent's preference for reduced data usage. Conditionals ------------ [`Last-Modified`](headers/last-modified) The last modification date of the resource, used to compare several versions of the same resource. It is less accurate than [`ETag`](headers/etag), but easier to calculate in some environments. Conditional requests using [`If-Modified-Since`](headers/if-modified-since) and [`If-Unmodified-Since`](headers/if-unmodified-since) use this value to change the behavior of the request. [`ETag`](headers/etag) A unique string identifying the version of the resource. Conditional requests using [`If-Match`](headers/if-match) and [`If-None-Match`](headers/if-none-match) use this value to change the behavior of the request. [`If-Match`](headers/if-match) Makes the request conditional, and applies the method only if the stored resource matches one of the given ETags. [`If-None-Match`](headers/if-none-match) Makes the request conditional, and applies the method only if the stored resource *doesn't* match any of the given ETags. This is used to update caches (for safe requests), or to prevent uploading a new resource when one already exists. [`If-Modified-Since`](headers/if-modified-since) Makes the request conditional, and expects the resource to be transmitted only if it has been modified after the given date. This is used to transmit data only when the cache is out of date. [`If-Unmodified-Since`](headers/if-unmodified-since) Makes the request conditional, and expects the resource to be transmitted only if it has not been modified after the given date. This ensures the coherence of a new fragment of a specific range with previous ones, or to implement an optimistic concurrency control system when modifying existing documents. [`Vary`](headers/vary) Determines how to match request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server. Connection management --------------------- [`Connection`](headers/connection) Controls whether the network connection stays open after the current transaction finishes. [`Keep-Alive`](headers/keep-alive) Controls how long a persistent connection should stay open. Content negotiation ------------------- [Content negotiation](content_negotiation) headers. [`Accept`](headers/accept) Informs the server about the [types](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) of data that can be sent back. [`Accept-Encoding`](headers/accept-encoding) The encoding algorithm, usually a [compression algorithm](compression), that can be used on the resource sent back. [`Accept-Language`](headers/accept-language) Informs the server about the human language the server is expected to send back. This is a hint and is not necessarily under the full control of the user: the server should always pay attention not to override an explicit user choice (like selecting a language from a dropdown). Controls -------- [`Expect`](headers/expect) Indicates expectations that need to be fulfilled by the server to properly handle the request. [`Max-Forwards`](headers/max-forwards) When using [`TRACE`](methods/trace), indicates the maximum number of hops the request can do before being reflected to the sender. Cookies ------- [`Cookie`](headers/cookie) Contains stored [HTTP cookies](cookies) previously sent by the server with the [`Set-Cookie`](headers/set-cookie) header. [`Set-Cookie`](headers/set-cookie) Send cookies from the server to the user-agent. CORS ---- *Learn more about CORS [here](https://developer.mozilla.org/en-US/docs/Glossary/CORS).* [`Access-Control-Allow-Origin`](headers/access-control-allow-origin) Indicates whether the response can be shared. [`Access-Control-Allow-Credentials`](headers/access-control-allow-credentials) Indicates whether the response to the request can be exposed when the credentials flag is true. [`Access-Control-Allow-Headers`](headers/access-control-allow-headers) Used in response to a [preflight request](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request) to indicate which HTTP headers can be used when making the actual request. [`Access-Control-Allow-Methods`](headers/access-control-allow-methods) Specifies the methods allowed when accessing the resource in response to a preflight request. [`Access-Control-Expose-Headers`](headers/access-control-expose-headers) Indicates which headers can be exposed as part of the response by listing their names. [`Access-Control-Max-Age`](headers/access-control-max-age) Indicates how long the results of a preflight request can be cached. [`Access-Control-Request-Headers`](headers/access-control-request-headers) Used when issuing a preflight request to let the server know which HTTP headers will be used when the actual request is made. [`Access-Control-Request-Method`](headers/access-control-request-method) Used when issuing a preflight request to let the server know which [HTTP method](methods) will be used when the actual request is made. [`Origin`](headers/origin) Indicates where a fetch originates from. [`Timing-Allow-Origin`](headers/timing-allow-origin) Specifies origins that are allowed to see values of attributes retrieved via features of the [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/Resource_Timing_API), which would otherwise be reported as zero due to cross-origin restrictions. Downloads --------- [`Content-Disposition`](headers/content-disposition) Indicates if the resource transmitted should be displayed inline (default behavior without the header), or if it should be handled like a download and the browser should present a "Save As" dialog. Message body information ------------------------ [`Content-Length`](headers/content-length) The size of the resource, in decimal number of bytes. [`Content-Type`](headers/content-type) Indicates the media type of the resource. [`Content-Encoding`](headers/content-encoding) Used to specify the compression algorithm. [`Content-Language`](headers/content-language) Describes the human language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language. [`Content-Location`](headers/content-location) Indicates an alternate location for the returned data. Proxies ------- [`Forwarded`](headers/forwarded) Contains information from the client-facing side of proxy servers that is altered or lost when a proxy is involved in the path of the request. [`X-Forwarded-For`](headers/x-forwarded-for) Non-standard Identifies the originating IP addresses of a client connecting to a web server through an HTTP proxy or a load balancer. [`X-Forwarded-Host`](headers/x-forwarded-host) Non-standard Identifies the original host requested that a client used to connect to your proxy or load balancer. [`X-Forwarded-Proto`](headers/x-forwarded-proto) Non-standard Identifies the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer. [`Via`](headers/via) Added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers. Redirects --------- [`Location`](headers/location) Indicates the URL to redirect a page to. Request context --------------- [`From`](headers/from) Contains an Internet email address for a human user who controls the requesting user agent. [`Host`](headers/host) Specifies the domain name of the server (for virtual hosting), and (optionally) the TCP port number on which the server is listening. [`Referer`](headers/referer) The address of the previous web page from which a link to the currently requested page was followed. [`Referrer-Policy`](headers/referrer-policy) Governs which referrer information sent in the [`Referer`](headers/referer) header should be included with requests made. [`User-Agent`](headers/user-agent) Contains a characteristic string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent. See also the [Firefox user agent string reference](headers/user-agent/firefox). Response context ---------------- [`Allow`](headers/allow) Lists the set of HTTP request methods supported by a resource. [`Server`](headers/server) Contains information about the software used by the origin server to handle the request. Range requests -------------- [`Accept-Ranges`](headers/accept-ranges) Indicates if the server supports range requests, and if so in which unit the range can be expressed. [`Range`](headers/range) Indicates the part of a document that the server should return. [`If-Range`](headers/if-range) Creates a conditional range request that is only fulfilled if the given etag or date matches the remote resource. Used to prevent downloading two ranges from incompatible version of the resource. [`Content-Range`](headers/content-range) Indicates where in a full body message a partial message belongs. Security -------- [`Cross-Origin-Embedder-Policy`](headers/cross-origin-embedder-policy) (COEP) Allows a server to declare an embedder policy for a given document. [`Cross-Origin-Opener-Policy`](headers/cross-origin-opener-policy) (COOP) Prevents other domains from opening/controlling a window. [`Cross-Origin-Resource-Policy`](headers/cross-origin-resource-policy) (CORP) Prevents other domains from reading the response of the resources to which this header is applied. [`Content-Security-Policy`](headers/content-security-policy) ([CSP](https://developer.mozilla.org/en-US/docs/Glossary/CSP)) Controls resources the user agent is allowed to load for a given page. [`Content-Security-Policy-Report-Only`](headers/content-security-policy-report-only) Allows web developers to experiment with policies by monitoring, but not enforcing, their effects. These violation reports consist of [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON) documents sent via an HTTP `POST` request to the specified URI. [`Expect-CT`](headers/expect-ct) Allows sites to opt in to reporting and/or enforcement of Certificate Transparency requirements, which prevents the use of misissued certificates for that site from going unnoticed. When a site enables the Expect-CT header, they are requesting that Chrome check that any certificate for that site appears in public CT logs. [`Feature-Policy`](headers/feature-policy) Provides a mechanism to allow and deny the use of browser features in its own frame, and in iframes that it embeds. [`Origin-Isolation`](headers/origin-isolation) Experimental Provides a mechanism to allow web applications to isolate their origins. [`Strict-Transport-Security`](headers/strict-transport-security) ([HSTS](https://developer.mozilla.org/en-US/docs/Glossary/HSTS)) Force communication using HTTPS instead of HTTP. [`Upgrade-Insecure-Requests`](headers/upgrade-insecure-requests) Sends a signal to the server expressing the client's preference for an encrypted and authenticated response, and that it can successfully handle the [`upgrade-insecure-requests`](headers/content-security-policy/upgrade-insecure-requests) directive. [`X-Content-Type-Options`](headers/x-content-type-options) Disables MIME sniffing and forces browser to use the type given in [`Content-Type`](headers/content-type). [`X-Download-Options`](headers/x-download-options) The [`X-Download-Options`](https://docs.microsoft.com/previous-versions/windows/internet-explorer/ie-developer/compatibility/jj542450(v=vs.85)?#the-noopen-directive) HTTP header indicates that the browser (Internet Explorer) should not display the option to "Open" a file that has been downloaded from an application, to prevent phishing attacks as the file otherwise would gain access to execute in the context of the application. [`X-Frame-Options`](headers/x-frame-options) (XFO) Indicates whether a browser should be allowed to render a page in a [`<frame>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frame), [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe), [`<embed>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed) or [`<object>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object). [`X-Permitted-Cross-Domain-Policies`](headers/x-permitted-cross-domain-policies) Specifies if a cross-domain policy file (`crossdomain.xml`) is allowed. The file may define a policy to grant clients, such as Adobe's Flash Player (now obsolete), Adobe Acrobat, Microsoft Silverlight (now obsolete), or Apache Flex, permission to handle data across domains that would otherwise be restricted due to the [Same-Origin Policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). See the [Cross-domain Policy File Specification](https://www.adobe.com/devnet-docs/acrobatetk/tools/AppSec/CrossDomain_PolicyFile_Specification.pdf) for more information. [`X-Powered-By`](headers/x-powered-by) May be set by hosting environments or other frameworks and contains information about them while not providing any usefulness to the application or its visitors. Unset this header to avoid exposing potential vulnerabilities. [`X-XSS-Protection`](headers/x-xss-protection) Enables cross-site scripting filtering. ### Fetch metadata request headers [Fetch metadata request headers](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_metadata_request_header) provides information about the context from which the request originated. This allows a server to make decisions about whether a request should be allowed based on where the request came from and how the resource will be used. [`Sec-Fetch-Site`](headers/sec-fetch-site) It is a request header that indicates the relationship between a request initiator's origin and its target's origin. It is a Structured Header whose value is a token with possible values `cross-site`, `same-origin`, `same-site`, and `none`. [`Sec-Fetch-Mode`](headers/sec-fetch-mode) It is a request header that indicates the request's mode to a server. It is a Structured Header whose value is a token with possible values `cors`, `navigate`, `no-cors`, `same-origin`, and `websocket`. [`Sec-Fetch-User`](headers/sec-fetch-user) It is a request header that indicates whether or not a navigation request was triggered by user activation. It is a Structured Header whose value is a boolean so possible values are `?0` for false and `?1` for true. [`Sec-Fetch-Dest`](headers/sec-fetch-dest) It is a request header that indicates the request's destination to a server. It is a Structured Header whose value is a token with possible values `audio`, `audioworklet`, `document`, `embed`, `empty`, `font`, `image`, `manifest`, `object`, `paintworklet`, `report`, `script`, `serviceworker`, `sharedworker`, `style`, `track`, `video`, `worker`, and `xslt`. [`Service-Worker-Navigation-Preload`](headers/service-worker-navigation-preload) A request header sent in preemptive request to [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) a resource during service worker boot. The value, which is set with [`NavigationPreloadManager.setHeaderValue()`](https://developer.mozilla.org/en-US/docs/Web/API/NavigationPreloadManager/setHeaderValue), can be used to inform a server that a different resource should be returned than in a normal `fetch()` operation. Server-sent events ------------------ [`Last-Event-ID`](headers/last-event-id) TBD [`NEL`](headers/nel) Experimental Defines a mechanism that enables developers to declare a network error reporting policy. [`Ping-From`](headers/ping-from) TBD [`Ping-To`](headers/ping-to) TBD [`Report-To`](headers/report-to) Used to specify a server endpoint for the browser to send warning and error reports to. Transfer coding --------------- [`Transfer-Encoding`](headers/transfer-encoding) Specifies the form of encoding used to safely transfer the resource to the user. [`TE`](headers/te) Specifies the transfer encodings the user agent is willing to accept. [`Trailer`](headers/trailer) Allows the sender to include additional fields at the end of chunked message. WebSockets ---------- [`Sec-WebSocket-Key`](headers/sec-websocket-key) TBD [`Sec-WebSocket-Extensions`](headers/sec-websocket-extensions) TBD [`Sec-WebSocket-Accept`](headers/sec-websocket-accept) TBD [`Sec-WebSocket-Protocol`](headers/sec-websocket-protocol) TBD [`Sec-WebSocket-Version`](headers/sec-websocket-version) TBD Other ----- [`Accept-Push-Policy`](headers/accept-push-policy) Experimental A client can express the desired push policy for a request by sending an [`Accept-Push-Policy`](https://datatracker.ietf.org/doc/html/draft-ruellan-http-accept-push-policy-00#section-3.1) header field in the request. [`Accept-Signature`](headers/accept-signature) Experimental A client can send the [`Accept-Signature`](https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#rfc.section.3.7) header field to indicate intention to take advantage of any available signatures and to indicate what kinds of signatures it supports. [`Alt-Svc`](headers/alt-svc) Used to list alternate ways to reach this service. [`Date`](headers/date) Contains the date and time at which the message was originated. [`Early-Data`](headers/early-data) Experimental Indicates that the request has been conveyed in TLS early data. [`Large-Allocation`](headers/large-allocation) Deprecated Tells the browser that the page being loaded is going to want to perform a large allocation. [`Link`](headers/link) The [`Link`](https://datatracker.ietf.org/doc/html/rfc5988#section-5) entity-header field provides a means for serializing one or more links in HTTP headers. It is semantically equivalent to the HTML [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) element. [`Push-Policy`](headers/push-policy) Experimental A [`Push-Policy`](https://datatracker.ietf.org/doc/html/draft-ruellan-http-accept-push-policy-00#section-3.2) defines the server behavior regarding push when processing a request. [`Retry-After`](headers/retry-after) Indicates how long the user agent should wait before making a follow-up request. [`Signature`](headers/signature) Experimental The [`Signature`](https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#rfc.section.3.1) header field conveys a list of signatures for an exchange, each one accompanied by information about how to determine the authority of and refresh that signature. [`Signed-Headers`](headers/signed-headers) Experimental The [`Signed-Headers`](https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#rfc.section.5.1.2) header field identifies an ordered list of response header fields to include in a signature. [`Server-Timing`](headers/server-timing) Communicates one or more metrics and descriptions for the given request-response cycle. [`Service-Worker-Allowed`](headers/service-worker-allowed) Used to remove the [path restriction](https://w3c.github.io/ServiceWorker/#path-restriction) by including this header [in the response of the Service Worker script](https://w3c.github.io/ServiceWorker/#service-worker-script-response). [`SourceMap`](headers/sourcemap) Links generated code to a [source map](https://firefox-source-docs.mozilla.org/devtools-user/debugger/how_to/use_a_source_map/index.html). [`Upgrade`](headers/upgrade) The relevant RFC document for the [Upgrade header field is RFC 9110, section 7.8](https://httpwg.org/specs/rfc9110.html#field.upgrade). The standard establishes rules for upgrading or changing to a different protocol on the current client, server, transport protocol connection. For example, this header standard allows a client to change from HTTP 1.1 to [WebSocket](https://developer.mozilla.org/en-US/docs/Glossary/WebSockets), assuming the server decides to acknowledge and implement the Upgrade header field. Neither party is required to accept the terms specified in the Upgrade header field. It can be used in both client and server headers. If the Upgrade header field is specified, then the sender MUST also send the Connection header field with the upgrade option specified. For details on the Connection header field [please see section 7.6.1 of the aforementioned RFC](https://httpwg.org/specs/rfc9110.html#field.connection). [`X-DNS-Prefetch-Control`](headers/x-dns-prefetch-control) Controls DNS prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as URLs for items referenced by the document, including images, CSS, JavaScript, and so forth. [`X-Firefox-Spdy`](headers/x-firefox-spdy) Deprecated Non-standard TBD [`X-Pingback`](headers/x-pingback) Non-standard TBD [`X-Requested-With`](headers/x-requested-with) TBD [`X-Robots-Tag`](headers/x-robots-tag) Non-standard The [`X-Robots-Tag`](https://developers.google.com/search/docs/advanced/robots/robots_meta_tag) HTTP header is used to indicate how a web page is to be indexed within public search engine results. The header is effectively equivalent to `<meta name="robots" content="…">`. [`X-UA-Compatible`](headers/x-ua-compatible) Non-standard Used by Internet Explorer to signal which document mode to use. Contributing ------------ You can help by [writing new entries](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Howto/Document_an_HTTP_header) or improving the existing ones. See also -------- * [Wikipedia page on List of HTTP headers](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields) * [IANA registry](https://www.iana.org/assignments/message-headers/message-headers.xhtml#perm-headers) * [HTTP Working Group](https://httpwg.org/specs/)
programming_docs
http Methods Methods ======= HTTP request methods ==================== HTTP defines a set of **request methods** to indicate the desired action to be performed for a given resource. Although they can also be nouns, these request methods are sometimes referred to as *HTTP verbs*. Each of them implements a different semantic, but some common features are shared by a group of them: e.g. a request method can be [safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP), [idempotent](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent), or [cacheable](https://developer.mozilla.org/en-US/docs/Glossary/cacheable). [`GET`](methods/get) The `GET` method requests a representation of the specified resource. Requests using `GET` should only retrieve data. [`HEAD`](methods/head) The `HEAD` method asks for a response identical to a `GET` request, but without the response body. [`POST`](methods/post) The `POST` method submits an entity to the specified resource, often causing a change in state or side effects on the server. [`PUT`](methods/put) The `PUT` method replaces all current representations of the target resource with the request payload. [`DELETE`](methods/delete) The `DELETE` method deletes the specified resource. [`CONNECT`](methods/connect) The `CONNECT` method establishes a tunnel to the server identified by the target resource. [`OPTIONS`](methods/options) The `OPTIONS` method describes the communication options for the target resource. [`TRACE`](methods/trace) The `TRACE` method performs a message loop-back test along the path to the target resource. [`PATCH`](methods/patch) The `PATCH` method applies partial modifications to a resource. Specifications -------------- | Specification | | --- | | [HTTP Semantics # CONNECT](https://httpwg.org/specs/rfc9110.html#CONNECT) | | [HTTP Semantics # DELETE](https://httpwg.org/specs/rfc9110.html#DELETE) | | [HTTP Semantics # GET](https://httpwg.org/specs/rfc9110.html#GET) | | [HTTP Semantics # HEAD](https://httpwg.org/specs/rfc9110.html#HEAD) | | [HTTP Semantics # OPTIONS](https://httpwg.org/specs/rfc9110.html#OPTIONS) | | [HTTP Semantics # POST](https://httpwg.org/specs/rfc9110.html#POST) | | [HTTP Semantics # PUT](https://httpwg.org/specs/rfc9110.html#PUT) | | [HTTP Semantics # TRACE](https://httpwg.org/specs/rfc9110.html#TRACE) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `CONNECT` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `DELETE` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `GET` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `HEAD` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `OPTIONS` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `POST` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `PUT` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `TRACE` | No | No | No | No | No | No | No | No | No | No | No | No | See also -------- * [HTTP headers](headers) http HTTP Caching Internet Engineering Task Force (IETF) R. Fielding, Ed. Request for Comments: 9111 Adobe STD: 98 M. Nottingham, Ed. Obsoletes: [7234](https://datatracker.ietf.org/doc/html/rfc7234) Fastly Category: Standards Track J. Reschke, Ed. ISSN: 2070-1721 greenbytes June 2022 HTTP Caching ============ Abstract The Hypertext Transfer Protocol (HTTP) is a stateless application- level protocol for distributed, collaborative, hypertext information systems. This document defines HTTP caches and the associated header fields that control cache behavior or indicate cacheable response messages. This document obsoletes [RFC 7234](https://datatracker.ietf.org/doc/html/rfc7234). Status of This Memo This is an Internet Standards Track document. This document is a product of the Internet Engineering Task Force (IETF). It represents the consensus of the IETF community. It has received public review and has been approved for publication by the Internet Engineering Steering Group (IESG). Further information on Internet Standards is available in [Section 2 of RFC 7841](https://datatracker.ietf.org/doc/html/rfc7841#section-2). Information about the current status of this document, any errata, and how to provide feedback on it may be obtained at <https://www.rfc-editor.org/info/rfc9111>. Copyright Notice Copyright (c) 2022 IETF Trust and the persons identified as the document authors. All rights reserved. This document is subject to [BCP 78](https://datatracker.ietf.org/doc/html/bcp78) and the IETF Trust's Legal Provisions Relating to IETF Documents (<https://trustee.ietf.org/license-info>) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Revised BSD License text as described in [Section 4](#section-4).e of the Trust Legal Provisions and are provided without warranty as described in the Revised BSD License. This document may contain material from IETF Documents or IETF Contributions published or made publicly available before November 10, 2008. The person(s) controlling the copyright in some of this material may not have granted the IETF Trust the right to allow modifications of such material outside the IETF Standards Process. Without obtaining an adequate license from the person(s) controlling the copyright in such materials, this document may not be modified outside the IETF Standards Process, and derivative works of it may not be created outside the IETF Standards Process, except to format it for publication as an RFC or to translate it into languages other than English. Table of Contents 1. Introduction 1.1. Requirements Notation 1.2. Syntax Notation 1.2.1. Imported Rules 1.2.2. Delta Seconds 2. Overview of Cache Operation 3. Storing Responses in Caches 3.1. Storing Header and Trailer Fields 3.2. Updating Stored Header Fields 3.3. Storing Incomplete Responses 3.4. Combining Partial Content 3.5. Storing Responses to Authenticated Requests 4. Constructing Responses from Caches 4.1. Calculating Cache Keys with the Vary Header Field 4.2. Freshness 4.2.1. Calculating Freshness Lifetime 4.2.2. Calculating Heuristic Freshness 4.2.3. Calculating Age 4.2.4. Serving Stale Responses 4.3. Validation 4.3.1. Sending a Validation Request 4.3.2. Handling a Received Validation Request 4.3.3. Handling a Validation Response 4.3.4. Freshening Stored Responses upon Validation 4.3.5. Freshening Responses with HEAD 4.4. Invalidating Stored Responses 5. Field Definitions 5.1. Age 5.2. Cache-Control 5.2.1. Request Directives 5.2.1.1. max-age 5.2.1.2. max-stale 5.2.1.3. min-fresh 5.2.1.4. no-cache 5.2.1.5. no-store 5.2.1.6. no-transform 5.2.1.7. only-if-cached 5.2.2. Response Directives 5.2.2.1. max-age 5.2.2.2. must-revalidate 5.2.2.3. must-understand 5.2.2.4. no-cache 5.2.2.5. no-store 5.2.2.6. no-transform 5.2.2.7. private 5.2.2.8. proxy-revalidate 5.2.2.9. public 5.2.2.10. s-maxage 5.2.3. Extension Directives 5.2.4. Cache Directive Registry 5.3. Expires 5.4. Pragma 5.5. Warning 6. Relationship to Applications and Other Caches 7. Security Considerations 7.1. Cache Poisoning 7.2. Timing Attacks 7.3. Caching of Sensitive Information 8. IANA Considerations 8.1. Field Name Registration 8.2. Cache Directive Registration 8.3. Warn Code Registry 9. References 9.1. Normative References 9.2. Informative References [Appendix A](#appendix-A). Collected ABNF [Appendix B](#appendix-B). Changes from [RFC 7234](https://datatracker.ietf.org/doc/html/rfc7234) Acknowledgements Index Authors' Addresses 1. Introduction --------------- The Hypertext Transfer Protocol (HTTP) is a stateless application- level request/response protocol that uses extensible semantics and self-descriptive messages for flexible interaction with network-based hypertext information systems. It is typically used for distributed information systems, where the use of response caches can improve performance. This document defines aspects of HTTP related to caching and reusing response messages. An HTTP "cache" is a local store of response messages and the subsystem that controls storage, retrieval, and deletion of messages in it. A cache stores cacheable responses to reduce the response time and network bandwidth consumption on future equivalent requests. Any client or server MAY use a cache, though not when acting as a tunnel (Section 3.7 of [[HTTP](#ref-HTTP)]). A "shared cache" is a cache that stores responses for reuse by more than one user; shared caches are usually (but not always) deployed as a part of an intermediary. A "private cache", in contrast, is dedicated to a single user; often, they are deployed as a component of a user agent. The goal of HTTP caching is significantly improving performance by reusing a prior response message to satisfy a current request. A cache considers a stored response "fresh", as defined in [Section 4.2](#section-4.2), if it can be reused without "validation" (checking with the origin server to see if the cached response remains valid for this request). A fresh response can therefore reduce both latency and network overhead each time the cache reuses it. When a cached response is not fresh, it might still be reusable if validation can freshen it ([Section 4.3](#section-4.3)) or if the origin is unavailable ([Section 4.2.4](#section-4.2.4)). This document obsoletes [RFC 7234](https://datatracker.ietf.org/doc/html/rfc7234), with the changes being summarized in [Appendix B](#appendix-B). ### 1.1. Requirements Notation The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://datatracker.ietf.org/doc/html/bcp14) [[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)] [[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when, and only when, they appear in all capitals, as shown here. Section 2 of [[HTTP](#ref-HTTP)] defines conformance criteria and contains considerations regarding error handling. ### 1.2. Syntax Notation This specification uses the Augmented Backus-Naur Form (ABNF) notation of [[RFC5234](https://datatracker.ietf.org/doc/html/rfc5234)], extended with the notation for case- sensitivity in strings defined in [[RFC7405](https://datatracker.ietf.org/doc/html/rfc7405)]. It also uses a list extension, defined in Section 5.6.1 of [[HTTP](#ref-HTTP)], that allows for compact definition of comma-separated lists using a "#" operator (similar to how the "\*" operator indicates repetition). [Appendix A](#appendix-A) shows the collected grammar with all list operators expanded to standard ABNF notation. #### 1.2.1. Imported Rules The following core rule is included by reference, as defined in [[RFC5234], Appendix B.1](https://datatracker.ietf.org/doc/html/rfc5234#appendix-B.1): DIGIT (decimal 0-9). [HTTP] defines the following rules: HTTP-date = <HTTP-date, see [[HTTP](#ref-HTTP)], Section 5.6.7> OWS = <OWS, see [[HTTP](#ref-HTTP)], Section 5.6.3> field-name = <field-name, see [[HTTP](#ref-HTTP)], Section 5.1> quoted-string = <quoted-string, see [[HTTP](#ref-HTTP)], Section 5.6.4> token = <token, see [[HTTP](#ref-HTTP)], Section 5.6.2> #### 1.2.2. Delta Seconds The delta-seconds rule specifies a non-negative integer, representing time in seconds. delta-seconds = 1\*DIGIT A recipient parsing a delta-seconds value and converting it to binary form ought to use an arithmetic type of at least 31 bits of non- negative integer range. If a cache receives a delta-seconds value greater than the greatest integer it can represent, or if any of its subsequent calculations overflows, the cache MUST consider the value to be 2147483648 (2^31) or the greatest positive integer it can conveniently represent. | \*Note:\* The value 2147483648 is here for historical reasons, | represents infinity (over 68 years), and does not need to be | stored in binary form; an implementation could produce it as a | string if any overflow occurs, even if the calculations are | performed with an arithmetic type incapable of directly | representing that number. What matters here is that an | overflow be detected and not treated as a negative value in | later calculations. 2. Overview of Cache Operation ------------------------------ Proper cache operation preserves the semantics of HTTP transfers while reducing the transmission of information already held in the cache. See Section 3 of [[HTTP](#ref-HTTP)] for the general terminology and core concepts of HTTP. Although caching is an entirely OPTIONAL feature of HTTP, it can be assumed that reusing a cached response is desirable and that such reuse is the default behavior when no requirement or local configuration prevents it. Therefore, HTTP cache requirements are focused on preventing a cache from either storing a non-reusable response or reusing a stored response inappropriately, rather than mandating that caches always store and reuse particular responses. The "cache key" is the information a cache uses to choose a response and is composed from, at a minimum, the request method and target URI used to retrieve the stored response; the method determines under which circumstances that response can be used to satisfy a subsequent request. However, many HTTP caches in common use today only cache GET responses and therefore only use the URI as the cache key. A cache might store multiple responses for a request target that is subject to content negotiation. Caches differentiate these responses by incorporating some of the original request's header fields into the cache key as well, using information in the Vary response header field, as per [Section 4.1](#section-4.1). Caches might incorporate additional material into the cache key. For example, user agent caches might include the referring site's identity, thereby "double keying" the cache to avoid some privacy risks (see [Section 7.2](#section-7.2)). Most commonly, caches store the successful result of a retrieval request: i.e., a 200 (OK) response to a GET request, which contains a representation of the target resource (Section 9.3.1 of [[HTTP](#ref-HTTP)]). However, it is also possible to store redirects, negative results (e.g., 404 (Not Found)), incomplete results (e.g., 206 (Partial Content)), and responses to methods other than GET if the method's definition allows such caching and defines something suitable for use as a cache key. A cache is "disconnected" when it cannot contact the origin server or otherwise find a forward path for a request. A disconnected cache can serve stale responses in some circumstances ([Section 4.2.4](#section-4.2.4)). 3. Storing Responses in Caches ------------------------------ A cache MUST NOT store a response to a request unless: \* the request method is understood by the cache; \* the response status code is final (see Section 15 of [[HTTP](#ref-HTTP)]); \* if the response status code is 206 or 304, or the must-understand cache directive (see [Section 5.2.2.3](#section-5.2.2.3)) is present: the cache understands the response status code; \* the no-store cache directive is not present in the response (see [Section 5.2.2.5](#section-5.2.2.5)); \* if the cache is shared: the private response directive is either not present or allows a shared cache to store a modified response; see [Section 5.2.2.7](#section-5.2.2.7)); \* if the cache is shared: the Authorization header field is not present in the request (see Section 11.6.2 of [[HTTP](#ref-HTTP)]) or a response directive is present that explicitly allows shared caching (see [Section 3.5](#section-3.5)); and \* the response contains at least one of the following: - a public response directive (see [Section 5.2.2.9](#section-5.2.2.9)); - a private response directive, if the cache is not shared (see [Section 5.2.2.7](#section-5.2.2.7)); - an Expires header field (see [Section 5.3](#section-5.3)); - a max-age response directive (see [Section 5.2.2.1](#section-5.2.2.1)); - if the cache is shared: an s-maxage response directive (see [Section 5.2.2.10](#section-5.2.2.10)); - a cache extension that allows it to be cached (see [Section 5.2.3](#section-5.2.3)); or - a status code that is defined as heuristically cacheable (see [Section 4.2.2](#section-4.2.2)). Note that a cache extension can override any of the requirements listed; see [Section 5.2.3](#section-5.2.3). In this context, a cache has "understood" a request method or a response status code if it recognizes it and implements all specified caching-related behavior. Note that, in normal operation, some caches will not store a response that has neither a cache validator nor an explicit expiration time, as such responses are not usually useful to store. However, caches are not prohibited from storing such responses. ### 3.1. Storing Header and Trailer Fields Caches MUST include all received response header fields -- including unrecognized ones -- when storing a response; this assures that new HTTP header fields can be successfully deployed. However, the following exceptions are made: \* The Connection header field and fields whose names are listed in it are required by Section 7.6.1 of [[HTTP](#ref-HTTP)] to be removed before forwarding the message. This MAY be implemented by doing so before storage. \* Likewise, some fields' semantics require them to be removed before forwarding the message, and this MAY be implemented by doing so before storage; see Section 7.6.1 of [[HTTP](#ref-HTTP)] for some examples. \* The no-cache ([Section 5.2.2.4](#section-5.2.2.4)) and private ([Section 5.2.2.7](#section-5.2.2.7)) cache directives can have arguments that prevent storage of header fields by all caches and shared caches, respectively. \* Header fields that are specific to the proxy that a cache uses when forwarding a request MUST NOT be stored, unless the cache incorporates the identity of the proxy into the cache key. Effectively, this is limited to Proxy-Authenticate (Section 11.7.1 of [[HTTP](#ref-HTTP)]), Proxy-Authentication-Info ([Section 11.7.3](#section-11.7.3) of [[HTTP](#ref-HTTP)]), and Proxy-Authorization (Section 11.7.2 of [[HTTP](#ref-HTTP)]). Caches MAY either store trailer fields separate from header fields or discard them. Caches MUST NOT combine trailer fields with header fields. ### 3.2. Updating Stored Header Fields Caches are required to update a stored response's header fields from another (typically newer) response in several situations; for example, see Sections [3.4](#section-3.4), [4.3.4](#section-4.3.4), and [4.3.5](#section-4.3.5). When doing so, the cache MUST add each header field in the provided response to the stored response, replacing field values that are already present, with the following exceptions: \* Header fields excepted from storage in [Section 3.1](#section-3.1), \* Header fields that the cache's stored response depends upon, as described below, \* Header fields that are automatically processed and removed by the recipient, as described below, and \* The Content-Length header field. In some cases, caches (especially in user agents) store the results of processing the received response, rather than the response itself, and updating header fields that affect that processing can result in inconsistent behavior and security issues. Caches in this situation MAY omit these header fields from updating stored responses on an exceptional basis but SHOULD limit such omission to those fields necessary to assure integrity of the stored response. For example, a browser might decode the content coding of a response while it is being received, creating a disconnect between the data it has stored and the response's original metadata. Updating that stored metadata with a different Content-Encoding header field would be problematic. Likewise, a browser might store a post-parse HTML tree rather than the content received in the response; updating the Content-Type header field would not be workable in this case because any assumptions about the format made in parsing would now be invalid. Furthermore, some fields are automatically processed and removed by the HTTP implementation, such as the Content-Range header field. Implementations MAY automatically omit such header fields from updates, even when the processing does not actually occur. Note that the Content-\* prefix is not a signal that a header field is omitted from update; it is a convention for MIME header fields, not HTTP. ### 3.3. Storing Incomplete Responses If the request method is GET, the response status code is 200 (OK), and the entire response header section has been received, a cache MAY store a response that is not complete (Section 6.1 of [[HTTP](#ref-HTTP)]) provided that the stored response is recorded as being incomplete. Likewise, a 206 (Partial Content) response MAY be stored as if it were an incomplete 200 (OK) response. However, a cache MUST NOT store incomplete or partial-content responses if it does not support the Range and Content-Range header fields or if it does not understand the range units used in those fields. A cache MAY complete a stored incomplete response by making a subsequent range request (Section 14.2 of [[HTTP](#ref-HTTP)]) and combining the successful response with the stored response, as defined in [Section 3.4](#section-3.4). A cache MUST NOT use an incomplete response to answer requests unless the response has been made complete, or the request is partial and specifies a range wholly within the incomplete response. A cache MUST NOT send a partial response to a client without explicitly marking it using the 206 (Partial Content) status code. ### 3.4. Combining Partial Content A response might transfer only a partial representation if the connection closed prematurely or if the request used one or more Range specifiers (Section 14.2 of [[HTTP](#ref-HTTP)]). After several such transfers, a cache might have received several ranges of the same representation. A cache MAY combine these ranges into a single stored response, and reuse that response to satisfy later requests, if they all share the same strong validator and the cache complies with the client requirements in Section 15.3.7.3 of [[HTTP](#ref-HTTP)]. When combining the new response with one or more stored responses, a cache MUST update the stored response header fields using the header fields provided in the new response, as per [Section 3.2](#section-3.2). ### 3.5. Storing Responses to Authenticated Requests A shared cache MUST NOT use a cached response to a request with an Authorization header field (Section 11.6.2 of [[HTTP](#ref-HTTP)]) to satisfy any subsequent request unless the response contains a Cache-Control field with a response directive ([Section 5.2.2](#section-5.2.2)) that allows it to be stored by a shared cache, and the cache conforms to the requirements of that directive for that response. In this specification, the following response directives have such an effect: must-revalidate ([Section 5.2.2.2](#section-5.2.2.2)), public ([Section 5.2.2.9](#section-5.2.2.9)), and s-maxage ([Section 5.2.2.10](#section-5.2.2.10)). 4. Constructing Responses from Caches ------------------------------------- When presented with a request, a cache MUST NOT reuse a stored response unless: \* the presented target URI (Section 7.1 of [[HTTP](#ref-HTTP)]) and that of the stored response match, and \* the request method associated with the stored response allows it to be used for the presented request, and \* request header fields nominated by the stored response (if any) match those presented (see [Section 4.1](#section-4.1)), and \* the stored response does not contain the no-cache directive ([Section 5.2.2.4](#section-5.2.2.4)), unless it is successfully validated ([Section 4.3](#section-4.3)), and \* the stored response is one of the following: - fresh (see [Section 4.2](#section-4.2)), or - allowed to be served stale (see [Section 4.2.4](#section-4.2.4)), or - successfully validated (see [Section 4.3](#section-4.3)). Note that a cache extension can override any of the requirements listed; see [Section 5.2.3](#section-5.2.3). When a stored response is used to satisfy a request without validation, a cache MUST generate an Age header field ([Section 5.1](#section-5.1)), replacing any present in the response with a value equal to the stored response's current\_age; see [Section 4.2.3](#section-4.2.3). A cache MUST write through requests with methods that are unsafe (Section 9.2.1 of [[HTTP](#ref-HTTP)]) to the origin server; i.e., a cache is not allowed to generate a reply to such a request before having forwarded the request and having received a corresponding response. Also, note that unsafe requests might invalidate already-stored responses; see [Section 4.4](#section-4.4). A cache can use a response that is stored or storable to satisfy multiple requests, provided that it is allowed to reuse that response for the requests in question. This enables a cache to "collapse requests" -- or combine multiple incoming requests into a single forward request upon a cache miss -- thereby reducing load on the origin server and network. Note, however, that if the cache cannot use the returned response for some or all of the collapsed requests, it will need to forward the requests in order to satisfy them, potentially introducing additional latency. When more than one suitable response is stored, a cache MUST use the most recent one (as determined by the Date header field). It can also forward the request with "Cache-Control: max-age=0" or "Cache- Control: no-cache" to disambiguate which response to use. A cache without a clock (Section 5.6.7 of [[HTTP](#ref-HTTP)]) MUST revalidate stored responses upon every use. ### 4.1. Calculating Cache Keys with the Vary Header Field When a cache receives a request that can be satisfied by a stored response and that stored response contains a Vary header field (Section 12.5.5 of [[HTTP](#ref-HTTP)]), the cache MUST NOT use that stored response without revalidation unless all the presented request header fields nominated by that Vary field value match those fields in the original request (i.e., the request that caused the cached response to be stored). The header fields from two requests are defined to match if and only if those in the first request can be transformed to those in the second request by applying any of the following: \* adding or removing whitespace, where allowed in the header field's syntax \* combining multiple header field lines with the same field name (see Section 5.2 of [[HTTP](#ref-HTTP)]) \* normalizing both header field values in a way that is known to have identical semantics, according to the header field's specification (e.g., reordering field values when order is not significant; case-normalization, where values are defined to be case-insensitive) If (after any normalization that might take place) a header field is absent from a request, it can only match another request if it is also absent there. A stored response with a Vary header field value containing a member "\*" always fails to match. If multiple stored responses match, the cache will need to choose one to use. When a nominated request header field has a known mechanism for ranking preference (e.g., qvalues on Accept and similar request header fields), that mechanism MAY be used to choose a preferred response. If such a mechanism is not available, or leads to equally preferred responses, the most recent response (as determined by the Date header field) is chosen, as per [Section 4](#section-4). Some resources mistakenly omit the Vary header field from their default response (i.e., the one sent when the request does not express any preferences), with the effect of choosing it for subsequent requests to that resource even when more preferable responses are available. When a cache has multiple stored responses for a target URI and one or more omits the Vary header field, the cache SHOULD choose the most recent (see [Section 4.2.3](#section-4.2.3)) stored response with a valid Vary field value. If no stored response matches, the cache cannot satisfy the presented request. Typically, the request is forwarded to the origin server, potentially with preconditions added to describe what responses the cache has already stored ([Section 4.3](#section-4.3)). ### 4.2. Freshness A "fresh" response is one whose age has not yet exceeded its freshness lifetime. Conversely, a "stale" response is one where it has. A response's "freshness lifetime" is the length of time between its generation by the origin server and its expiration time. An "explicit expiration time" is the time at which the origin server intends that a stored response can no longer be used by a cache without further validation, whereas a "heuristic expiration time" is assigned by a cache when no explicit expiration time is available. A response's "age" is the time that has passed since it was generated by, or successfully validated with, the origin server. When a response is fresh, it can be used to satisfy subsequent requests without contacting the origin server, thereby improving efficiency. The primary mechanism for determining freshness is for an origin server to provide an explicit expiration time in the future, using either the Expires header field ([Section 5.3](#section-5.3)) or the max-age response directive ([Section 5.2.2.1](#section-5.2.2.1)). Generally, origin servers will assign future explicit expiration times to responses in the belief that the representation is not likely to change in a semantically significant way before the expiration time is reached. If an origin server wishes to force a cache to validate every request, it can assign an explicit expiration time in the past to indicate that the response is already stale. Compliant caches will normally validate a stale cached response before reusing it for subsequent requests (see [Section 4.2.4](#section-4.2.4)). Since origin servers do not always provide explicit expiration times, caches are also allowed to use a heuristic to determine an expiration time under certain circumstances (see [Section 4.2.2](#section-4.2.2)). The calculation to determine if a response is fresh is: response\_is\_fresh = (freshness\_lifetime > current\_age) freshness\_lifetime is defined in [Section 4.2.1](#section-4.2.1); current\_age is defined in [Section 4.2.3](#section-4.2.3). Clients can send the max-age or min-fresh request directives ([Section 5.2.1](#section-5.2.1)) to suggest limits on the freshness calculations for the corresponding response. However, caches are not required to honor them. When calculating freshness, to avoid common problems in date parsing: \* Although all date formats are specified to be case-sensitive, a cache recipient SHOULD match the field value case-insensitively. \* If a cache recipient's internal implementation of time has less resolution than the value of an HTTP-date, the recipient MUST internally represent a parsed Expires date as the nearest time equal to or earlier than the received value. \* A cache recipient MUST NOT allow local time zones to influence the calculation or comparison of an age or expiration time. \* A cache recipient SHOULD consider a date with a zone abbreviation other than "GMT" to be invalid for calculating expiration. Note that freshness applies only to cache operation; it cannot be used to force a user agent to refresh its display or reload a resource. See [Section 6](#section-6) for an explanation of the difference between caches and history mechanisms. #### 4.2.1. Calculating Freshness Lifetime A cache can calculate the freshness lifetime (denoted as freshness\_lifetime) of a response by evaluating the following rules and using the first match: \* If the cache is shared and the s-maxage response directive ([Section 5.2.2.10](#section-5.2.2.10)) is present, use its value, or \* If the max-age response directive ([Section 5.2.2.1](#section-5.2.2.1)) is present, use its value, or \* If the Expires response header field ([Section 5.3](#section-5.3)) is present, use its value minus the value of the Date response header field (using the time the message was received if it is not present, as per Section 6.6.1 of [[HTTP](#ref-HTTP)]), or \* Otherwise, no explicit expiration time is present in the response. A heuristic freshness lifetime might be applicable; see [Section 4.2.2](#section-4.2.2). Note that this calculation is intended to reduce clock skew by using the clock information provided by the origin server whenever possible. When there is more than one value present for a given directive (e.g., two Expires header field lines or multiple Cache-Control: max- age directives), either the first occurrence should be used or the response should be considered stale. If directives conflict (e.g., both max-age and no-cache are present), the most restrictive directive should be honored. Caches are encouraged to consider responses that have invalid freshness information (e.g., a max-age directive with non-integer content) to be stale. #### 4.2.2. Calculating Heuristic Freshness Since origin servers do not always provide explicit expiration times, a cache MAY assign a heuristic expiration time when an explicit time is not specified, employing algorithms that use other field values (such as the Last-Modified time) to estimate a plausible expiration time. This specification does not provide specific algorithms, but it does impose worst-case constraints on their results. A cache MUST NOT use heuristics to determine freshness when an explicit expiration time is present in the stored response. Because of the requirements in [Section 3](#section-3), heuristics can only be used on responses without explicit freshness whose status codes are defined as "heuristically cacheable" (e.g., see Section 15.1 of [[HTTP](#ref-HTTP)]) and on responses without explicit freshness that have been marked as explicitly cacheable (e.g., with a public response directive). Note that in previous specifications, heuristically cacheable response status codes were called "cacheable by default". If the response has a Last-Modified header field (Section 8.8.2 of [[HTTP](#ref-HTTP)]), caches are encouraged to use a heuristic expiration value that is no more than some fraction of the interval since that time. A typical setting of this fraction might be 10%. | \*Note:\* A previous version of the HTTP specification | ([Section 13.9 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-13.9)) prohibited caches from calculating | heuristic freshness for URIs with query components (i.e., those | containing "?"). In practice, this has not been widely | implemented. Therefore, origin servers are encouraged to send | explicit directives (e.g., Cache-Control: no-cache) if they | wish to prevent caching. #### 4.2.3. Calculating Age The Age header field is used to convey an estimated age of the response message when obtained from a cache. The Age field value is the cache's estimate of the number of seconds since the origin server generated or validated the response. The Age value is therefore the sum of the time that the response has been resident in each of the caches along the path from the origin server, plus the time it has been in transit along network paths. Age calculation uses the following data: "age\_value" The term "age\_value" denotes the value of the Age header field ([Section 5.1](#section-5.1)), in a form appropriate for arithmetic operation; or 0, if not available. "date\_value" The term "date\_value" denotes the value of the Date header field, in a form appropriate for arithmetic operations. See Section 6.6.1 of [[HTTP](#ref-HTTP)] for the definition of the Date header field and for requirements regarding responses without it. "now" The term "now" means the current value of this implementation's clock (Section 5.6.7 of [[HTTP](#ref-HTTP)]). "request\_time" The value of the clock at the time of the request that resulted in the stored response. "response\_time" The value of the clock at the time the response was received. A response's age can be calculated in two entirely independent ways: 1. the "apparent\_age": response\_time minus date\_value, if the implementation's clock is reasonably well synchronized to the origin server's clock. If the result is negative, the result is replaced by zero. 2. the "corrected\_age\_value", if all of the caches along the response path implement HTTP/1.1 or greater. A cache MUST interpret this value relative to the time the request was initiated, not the time that the response was received. apparent\_age = max(0, response\_time - date\_value); response\_delay = response\_time - request\_time; corrected\_age\_value = age\_value + response\_delay; The corrected\_age\_value MAY be used as the corrected\_initial\_age. In circumstances where very old cache implementations that might not correctly insert Age are present, corrected\_initial\_age can be calculated more conservatively as corrected\_initial\_age = max(apparent\_age, corrected\_age\_value); The current\_age of a stored response can then be calculated by adding the time (in seconds) since the stored response was last validated by the origin server to the corrected\_initial\_age. resident\_time = now - response\_time; current\_age = corrected\_initial\_age + resident\_time; #### 4.2.4. Serving Stale Responses A "stale" response is one that either has explicit expiry information or is allowed to have heuristic expiry calculated, but is not fresh according to the calculations in [Section 4.2](#section-4.2). A cache MUST NOT generate a stale response if it is prohibited by an explicit in-protocol directive (e.g., by a no-cache response directive, a must-revalidate response directive, or an applicable s-maxage or proxy-revalidate response directive; see [Section 5.2.2](#section-5.2.2)). A cache MUST NOT generate a stale response unless it is disconnected or doing so is explicitly permitted by the client or origin server (e.g., by the max-stale request directive in [Section 5.2.1](#section-5.2.1), extension directives such as those defined in [[RFC5861](https://datatracker.ietf.org/doc/html/rfc5861)], or configuration in accordance with an out-of-band contract). ### 4.3. Validation When a cache has one or more stored responses for a requested URI, but cannot serve any of them (e.g., because they are not fresh, or one cannot be chosen; see [Section 4.1](#section-4.1)), it can use the conditional request mechanism (Section 13 of [[HTTP](#ref-HTTP)]) in the forwarded request to give the next inbound server an opportunity to choose a valid stored response to use, updating the stored metadata in the process, or to replace the stored response(s) with a new response. This process is known as "validating" or "revalidating" the stored response. #### 4.3.1. Sending a Validation Request When generating a conditional request for validation, a cache either starts with a request it is attempting to satisfy or -- if it is initiating the request independently -- synthesizes a request using a stored response by copying the method, target URI, and request header fields identified by the Vary header field ([Section 4.1](#section-4.1)). It then updates that request with one or more precondition header fields. These contain validator metadata sourced from a stored response(s) that has the same URI. Typically, this will include only the stored response(s) that has the same cache key, although a cache is allowed to validate a response that it cannot choose with the request header fields it is sending (see [Section 4.1](#section-4.1)). The precondition header fields are then compared by recipients to determine whether any stored response is equivalent to a current representation of the resource. One such validator is the timestamp given in a Last-Modified header field (Section 8.8.2 of [[HTTP](#ref-HTTP)]), which can be used in an If-Modified- Since header field for response validation, or in an If-Unmodified- Since or If-Range header field for representation selection (i.e., the client is referring specifically to a previously obtained representation with that timestamp). Another validator is the entity tag given in an ETag field (Section 8.8.3 of [[HTTP](#ref-HTTP)]). One or more entity tags, indicating one or more stored responses, can be used in an If-None-Match header field for response validation, or in an If-Match or If-Range header field for representation selection (i.e., the client is referring specifically to one or more previously obtained representations with the listed entity tags). When generating a conditional request for validation, a cache: \* MUST send the relevant entity tags (using If-Match, If-None-Match, or If-Range) if the entity tags were provided in the stored response(s) being validated. \* SHOULD send the Last-Modified value (using If-Modified-Since) if the request is not for a subrange, a single stored response is being validated, and that response contains a Last-Modified value. \* MAY send the Last-Modified value (using If-Unmodified-Since or If- Range) if the request is for a subrange, a single stored response is being validated, and that response contains only a Last- Modified value (not an entity tag). In most cases, both validators are generated in cache validation requests, even when entity tags are clearly superior, to allow old intermediaries that do not understand entity tag preconditions to respond appropriately. #### 4.3.2. Handling a Received Validation Request Each client in the request chain may have its own cache, so it is common for a cache at an intermediary to receive conditional requests from other (outbound) caches. Likewise, some user agents make use of conditional requests to limit data transfers to recently modified representations or to complete the transfer of a partially retrieved representation. If a cache receives a request that can be satisfied by reusing a stored 200 (OK) or 206 (Partial Content) response, as per [Section 4](#section-4), the cache SHOULD evaluate any applicable conditional header field preconditions received in that request with respect to the corresponding validators contained within the stored response. A cache MUST NOT evaluate conditional header fields that only apply to an origin server, occur in a request with semantics that cannot be satisfied with a cached response, or occur in a request with a target resource for which it has no stored responses; such preconditions are likely intended for some other (inbound) server. The proper evaluation of conditional requests by a cache depends on the received precondition header fields and their precedence. In summary, the If-Match and If-Unmodified-Since conditional header fields are not applicable to a cache, and If-None-Match takes precedence over If-Modified-Since. See Section 13.2.2 of [[HTTP](#ref-HTTP)] for a complete specification of precondition precedence. A request containing an If-None-Match header field (Section 13.1.2 of [[HTTP](#ref-HTTP)]) indicates that the client wants to validate one or more of its own stored responses in comparison to the stored response chosen by the cache (as per [Section 4](#section-4)). If an If-None-Match header field is not present, a request containing an If-Modified-Since header field (Section 13.1.3 of [[HTTP](#ref-HTTP)]) indicates that the client wants to validate one or more of its own stored responses by modification date. If a request contains an If-Modified-Since header field and the Last- Modified header field is not present in a stored response, a cache SHOULD use the stored response's Date field value (or, if no Date field is present, the time that the stored response was received) to evaluate the conditional. A cache that implements partial responses to range requests, as defined in Section 14.2 of [[HTTP](#ref-HTTP)], also needs to evaluate a received If-Range header field (Section 13.1.5 of [[HTTP](#ref-HTTP)]) with respect to the cache's chosen response. When a cache decides to forward a request to revalidate its own stored responses for a request that contains an If-None-Match list of entity tags, the cache MAY combine the received list with a list of entity tags from its own stored set of responses (fresh or stale) and send the union of the two lists as a replacement If-None-Match header field value in the forwarded request. If a stored response contains only partial content, the cache MUST NOT include its entity tag in the union unless the request is for a range that would be fully satisfied by that partial stored response. If the response to the forwarded request is 304 (Not Modified) and has an ETag field value with an entity tag that is not in the client's list, the cache MUST generate a 200 (OK) response for the client by reusing its corresponding stored response, as updated by the 304 response metadata ([Section 4.3.4](#section-4.3.4)). #### 4.3.3. Handling a Validation Response Cache handling of a response to a conditional request depends upon its status code: \* A 304 (Not Modified) response status code indicates that the stored response can be updated and reused; see [Section 4.3.4](#section-4.3.4). \* A full response (i.e., one containing content) indicates that none of the stored responses nominated in the conditional request are suitable. Instead, the cache MUST use the full response to satisfy the request. The cache MAY store such a full response, subject to its constraints (see [Section 3](#section-3)). \* However, if a cache receives a 5xx (Server Error) response while attempting to validate a response, it can either forward this response to the requesting client or act as if the server failed to respond. In the latter case, the cache can send a previously stored response, subject to its constraints on doing so (see [Section 4.2.4](#section-4.2.4)), or retry the validation request. #### 4.3.4. Freshening Stored Responses upon Validation When a cache receives a 304 (Not Modified) response, it needs to identify stored responses that are suitable for updating with the new information provided, and then do so. The initial set of stored responses to update are those that could have been chosen for that request -- i.e., those that meet the requirements in [Section 4](#section-4), except the last requirement to be fresh, able to be served stale, or just validated. Then, that initial set of stored responses is further filtered by the first match of: \* If the new response contains one or more "strong validators" (see Section 8.8.1 of [[HTTP](#ref-HTTP)]), then each of those strong validators identifies a selected representation for update. All the stored responses in the initial set with one of those same strong validators are identified for update. If none of the initial set contains at least one of the same strong validators, then the cache MUST NOT use the new response to update any stored responses. \* If the new response contains no strong validators but does contain one or more "weak validators", and those validators correspond to one of the initial set's stored responses, then the most recent of those matching stored responses is identified for update. \* If the new response does not include any form of validator (such as where a client generates an If-Modified-Since request from a source other than the Last-Modified response header field), and there is only one stored response in the initial set, and that stored response also lacks a validator, then that stored response is identified for update. For each stored response identified, the cache MUST update its header fields with the header fields provided in the 304 (Not Modified) response, as per [Section 3.2](#section-3.2). #### 4.3.5. Freshening Responses with HEAD A response to the HEAD method is identical to what an equivalent request made with a GET would have been, without sending the content. This property of HEAD responses can be used to invalidate or update a cached GET response if the more efficient conditional GET request mechanism is not available (due to no validators being present in the stored response) or if transmission of the content is not desired even if it has changed. When a cache makes an inbound HEAD request for a target URI and receives a 200 (OK) response, the cache SHOULD update or invalidate each of its stored GET responses that could have been chosen for that request (see [Section 4.1](#section-4.1)). For each of the stored responses that could have been chosen, if the stored response and HEAD response have matching values for any received validator fields (ETag and Last-Modified) and, if the HEAD response has a Content-Length header field, the value of Content- Length matches that of the stored response, the cache SHOULD update the stored response as described below; otherwise, the cache SHOULD consider the stored response to be stale. If a cache updates a stored response with the metadata provided in a HEAD response, the cache MUST use the header fields provided in the HEAD response to update the stored response (see [Section 3.2](#section-3.2)). ### 4.4. Invalidating Stored Responses Because unsafe request methods (Section 9.2.1 of [[HTTP](#ref-HTTP)]) such as PUT, POST, or DELETE have the potential for changing state on the origin server, intervening caches are required to invalidate stored responses to keep their contents up to date. A cache MUST invalidate the target URI (Section 7.1 of [[HTTP](#ref-HTTP)]) when it receives a non-error status code in response to an unsafe request method (including methods whose safety is unknown). A cache MAY invalidate other URIs when it receives a non-error status code in response to an unsafe request method (including methods whose safety is unknown). In particular, the URI(s) in the Location and Content-Location response header fields (if present) are candidates for invalidation; other URIs might be discovered through mechanisms not specified in this document. However, a cache MUST NOT trigger an invalidation under these conditions if the origin (Section 4.3.1 of [[HTTP](#ref-HTTP)]) of the URI to be invalidated differs from that of the target URI (Section 7.1 of [[HTTP](#ref-HTTP)]). This helps prevent denial-of-service attacks. "Invalidate" means that the cache will either remove all stored responses whose target URI matches the given URI or mark them as "invalid" and in need of a mandatory validation before they can be sent in response to a subsequent request. A "non-error response" is one with a 2xx (Successful) or 3xx (Redirection) status code. Note that this does not guarantee that all appropriate responses are invalidated globally; a state-changing request would only invalidate responses in the caches it travels through. 5. Field Definitions -------------------- This section defines the syntax and semantics of HTTP fields related to caching. ### 5.1. Age The "Age" response header field conveys the sender's estimate of the time since the response was generated or successfully validated at the origin server. Age values are calculated as specified in [Section 4.2.3](#section-4.2.3). Age = delta-seconds The Age field value is a non-negative integer, representing time in seconds (see [Section 1.2.2](#section-1.2.2)). Although it is defined as a singleton header field, a cache encountering a message with a list-based Age field value SHOULD use the first member of the field value, discarding subsequent ones. If the field value (after discarding additional members, as per above) is invalid (e.g., it contains something other than a non- negative integer), a cache SHOULD ignore the field. The presence of an Age header field implies that the response was not generated or validated by the origin server for this request. However, lack of an Age header field does not imply the origin was contacted. ### 5.2. Cache-Control The "Cache-Control" header field is used to list directives for caches along the request/response chain. Cache directives are unidirectional, in that the presence of a directive in a request does not imply that the same directive is present or copied in the response. See [Section 5.2.3](#section-5.2.3) for information about how Cache-Control directives defined elsewhere are handled. A proxy, whether or not it implements a cache, MUST pass cache directives through in forwarded messages, regardless of their significance to that application, since the directives might apply to all recipients along the request/response chain. It is not possible to target a directive to a specific cache. Cache directives are identified by a token, to be compared case- insensitively, and have an optional argument that can use both token and quoted-string syntax. For the directives defined below that define arguments, recipients ought to accept both forms, even if a specific form is required for generation. Cache-Control = #cache-directive cache-directive = token [ "=" ( token / quoted-string ) ] For the cache directives defined below, no argument is defined (nor allowed) unless stated otherwise. #### 5.2.1. Request Directives This section defines cache request directives. They are advisory; caches MAY implement them, but are not required to. ##### 5.2.1.1. max-age Argument syntax: delta-seconds (see [Section 1.2.2](#section-1.2.2)) The max-age request directive indicates that the client prefers a response whose age is less than or equal to the specified number of seconds. Unless the max-stale request directive is also present, the client does not wish to receive a stale response. This directive uses the token form of the argument syntax: e.g., 'max-age=5' not 'max-age="5"'. A sender MUST NOT generate the quoted-string form. ##### 5.2.1.2. max-stale Argument syntax: delta-seconds (see [Section 1.2.2](#section-1.2.2)) The max-stale request directive indicates that the client will accept a response that has exceeded its freshness lifetime. If a value is present, then the client is willing to accept a response that has exceeded its freshness lifetime by no more than the specified number of seconds. If no value is assigned to max-stale, then the client will accept a stale response of any age. This directive uses the token form of the argument syntax: e.g., 'max-stale=10' not 'max-stale="10"'. A sender MUST NOT generate the quoted-string form. ##### 5.2.1.3. min-fresh Argument syntax: delta-seconds (see [Section 1.2.2](#section-1.2.2)) The min-fresh request directive indicates that the client prefers a response whose freshness lifetime is no less than its current age plus the specified time in seconds. That is, the client wants a response that will still be fresh for at least the specified number of seconds. This directive uses the token form of the argument syntax: e.g., 'min-fresh=20' not 'min-fresh="20"'. A sender MUST NOT generate the quoted-string form. ##### 5.2.1.4. no-cache The no-cache request directive indicates that the client prefers a stored response not be used to satisfy the request without successful validation on the origin server. ##### 5.2.1.5. no-store The no-store request directive indicates that a cache MUST NOT store any part of either this request or any response to it. This directive applies to both private and shared caches. "MUST NOT store" in this context means that the cache MUST NOT intentionally store the information in non-volatile storage and MUST make a best- effort attempt to remove the information from volatile storage as promptly as possible after forwarding it. This directive is not a reliable or sufficient mechanism for ensuring privacy. In particular, malicious or compromised caches might not recognize or obey this directive, and communications networks might be vulnerable to eavesdropping. Note that if a request containing this directive is satisfied from a cache, the no-store request directive does not apply to the already stored response. ##### 5.2.1.6. no-transform The no-transform request directive indicates that the client is asking for intermediaries to avoid transforming the content, as defined in Section 7.7 of [[HTTP](#ref-HTTP)]. ##### 5.2.1.7. only-if-cached The only-if-cached request directive indicates that the client only wishes to obtain a stored response. Caches that honor this request directive SHOULD, upon receiving it, respond with either a stored response consistent with the other constraints of the request or a 504 (Gateway Timeout) status code. #### 5.2.2. Response Directives This section defines cache response directives. A cache MUST obey the Cache-Control directives defined in this section. ##### 5.2.2.1. max-age Argument syntax: delta-seconds (see [Section 1.2.2](#section-1.2.2)) The max-age response directive indicates that the response is to be considered stale after its age is greater than the specified number of seconds. This directive uses the token form of the argument syntax: e.g., 'max-age=5' not 'max-age="5"'. A sender MUST NOT generate the quoted-string form. ##### 5.2.2.2. must-revalidate The must-revalidate response directive indicates that once the response has become stale, a cache MUST NOT reuse that response to satisfy another request until it has been successfully validated by the origin, as defined by [Section 4.3](#section-4.3). The must-revalidate directive is necessary to support reliable operation for certain protocol features. In all circumstances, a cache MUST NOT ignore the must-revalidate directive; in particular, if a cache is disconnected, the cache MUST generate an error response rather than reuse the stale response. The generated status code SHOULD be 504 (Gateway Timeout) unless another error status code is more applicable. The must-revalidate directive ought to be used by servers if and only if failure to validate a request could cause incorrect operation, such as a silently unexecuted financial transaction. The must-revalidate directive also permits a shared cache to reuse a response to a request containing an Authorization header field (Section 11.6.2 of [[HTTP](#ref-HTTP)]), subject to the above requirement on revalidation ([Section 3.5](#section-3.5)). ##### 5.2.2.3. must-understand The must-understand response directive limits caching of the response to a cache that understands and conforms to the requirements for that response's status code. A response that contains the must-understand directive SHOULD also contain the no-store directive. When a cache that implements the must-understand directive receives a response that includes it, the cache SHOULD ignore the no-store directive if it understands and implements the status code's caching requirements. ##### 5.2.2.4. no-cache Argument syntax: #field-name The no-cache response directive, in its unqualified form (without an argument), indicates that the response MUST NOT be used to satisfy any other request without forwarding it for validation and receiving a successful response; see [Section 4.3](#section-4.3). This allows an origin server to prevent a cache from using the response to satisfy a request without contacting it, even by caches that have been configured to send stale responses. The qualified form of the no-cache response directive, with an argument that lists one or more field names, indicates that a cache MAY use the response to satisfy a subsequent request, subject to any other restrictions on caching, if the listed header fields are excluded from the subsequent response or the subsequent response has been successfully revalidated with the origin server (updating or removing those fields). This allows an origin server to prevent the reuse of certain header fields in a response, while still allowing caching of the rest of the response. The field names given are not limited to the set of header fields defined by this specification. Field names are case-insensitive. This directive uses the quoted-string form of the argument syntax. A sender SHOULD NOT generate the token form (even if quoting appears not to be needed for single-entry lists). | \*Note:\* The qualified form of the directive is often handled by | caches as if an unqualified no-cache directive was received; | that is, the special handling for the qualified form is not | widely implemented. ##### 5.2.2.5. no-store The no-store response directive indicates that a cache MUST NOT store any part of either the immediate request or the response and MUST NOT use the response to satisfy any other request. This directive applies to both private and shared caches. "MUST NOT store" in this context means that the cache MUST NOT intentionally store the information in non-volatile storage and MUST make a best- effort attempt to remove the information from volatile storage as promptly as possible after forwarding it. This directive is not a reliable or sufficient mechanism for ensuring privacy. In particular, malicious or compromised caches might not recognize or obey this directive, and communications networks might be vulnerable to eavesdropping. Note that the must-understand cache directive overrides no-store in certain circumstances; see [Section 5.2.2.3](#section-5.2.2.3). ##### 5.2.2.6. no-transform The no-transform response directive indicates that an intermediary (regardless of whether it implements a cache) MUST NOT transform the content, as defined in Section 7.7 of [[HTTP](#ref-HTTP)]. ##### 5.2.2.7. private Argument syntax: #field-name The unqualified private response directive indicates that a shared cache MUST NOT store the response (i.e., the response is intended for a single user). It also indicates that a private cache MAY store the response, subject to the constraints defined in [Section 3](#section-3), even if the response would not otherwise be heuristically cacheable by a private cache. If a qualified private response directive is present, with an argument that lists one or more field names, then only the listed header fields are limited to a single user: a shared cache MUST NOT store the listed header fields if they are present in the original response but MAY store the remainder of the response message without those header fields, subject the constraints defined in [Section 3](#section-3). The field names given are not limited to the set of header fields defined by this specification. Field names are case-insensitive. This directive uses the quoted-string form of the argument syntax. A sender SHOULD NOT generate the token form (even if quoting appears not to be needed for single-entry lists). | \*Note:\* This usage of the word "private" only controls where | the response can be stored; it cannot ensure the privacy of the | message content. Also, the qualified form of the directive is | often handled by caches as if an unqualified private directive | was received; that is, the special handling for the qualified | form is not widely implemented. ##### 5.2.2.8. proxy-revalidate The proxy-revalidate response directive indicates that once the response has become stale, a shared cache MUST NOT reuse that response to satisfy another request until it has been successfully validated by the origin, as defined by [Section 4.3](#section-4.3). This is analogous to must-revalidate ([Section 5.2.2.2](#section-5.2.2.2)), except that proxy- revalidate does not apply to private caches. Note that proxy-revalidate on its own does not imply that a response is cacheable. For example, it might be combined with the public directive ([Section 5.2.2.9](#section-5.2.2.9)), allowing the response to be cached while requiring only a shared cache to revalidate when stale. ##### 5.2.2.9. public The public response directive indicates that a cache MAY store the response even if it would otherwise be prohibited, subject to the constraints defined in [Section 3](#section-3). In other words, public explicitly marks the response as cacheable. For example, public permits a shared cache to reuse a response to a request containing an Authorization header field ([Section 3.5](#section-3.5)). Note that it is unnecessary to add the public directive to a response that is already cacheable according to [Section 3](#section-3). If a response with the public directive has no explicit freshness information, it is heuristically cacheable ([Section 4.2.2](#section-4.2.2)). ##### 5.2.2.10. s-maxage Argument syntax: delta-seconds (see [Section 1.2.2](#section-1.2.2)) The s-maxage response directive indicates that, for a shared cache, the maximum age specified by this directive overrides the maximum age specified by either the max-age directive or the Expires header field. The s-maxage directive incorporates the semantics of the proxy-revalidate response directive ([Section 5.2.2.8](#section-5.2.2.8)) for a shared cache. A shared cache MUST NOT reuse a stale response with s-maxage to satisfy another request until it has been successfully validated by the origin, as defined by [Section 4.3](#section-4.3). This directive also permits a shared cache to reuse a response to a request containing an Authorization header field, subject to the above requirements on maximum age and revalidation ([Section 3.5](#section-3.5)). This directive uses the token form of the argument syntax: e.g., 's-maxage=10' not 's-maxage="10"'. A sender MUST NOT generate the quoted-string form. #### 5.2.3. Extension Directives The Cache-Control header field can be extended through the use of one or more extension cache directives. A cache MUST ignore unrecognized cache directives. Informational extensions (those that do not require a change in cache behavior) can be added without changing the semantics of other directives. Behavioral extensions are designed to work by acting as modifiers to the existing base of cache directives. Both the new directive and the old directive are supplied, such that applications that do not understand the new directive will default to the behavior specified by the old directive, and those that understand the new directive will recognize it as modifying the requirements associated with the old directive. In this way, extensions to the existing cache directives can be made without breaking deployed caches. For example, consider a hypothetical new response directive called "community" that acts as a modifier to the private directive: in addition to private caches, only a cache that is shared by members of the named community is allowed to cache the response. An origin server wishing to allow the UCI community to use an otherwise private response in their shared cache(s) could do so by including Cache-Control: private, community="UCI" A cache that recognizes such a community cache directive could broaden its behavior in accordance with that extension. A cache that does not recognize the community cache directive would ignore it and adhere to the private directive. New extension directives ought to consider defining: \* What it means for a directive to be specified multiple times, \* When the directive does not take an argument, what it means when an argument is present, \* When the directive requires an argument, what it means when it is missing, and \* Whether the directive is specific to requests, specific to responses, or able to be used in either. #### 5.2.4. Cache Directive Registry The "Hypertext Transfer Protocol (HTTP) Cache Directive Registry" defines the namespace for the cache directives. It has been created and is now maintained at <[https://www.iana.org/assignments/http-](https://www.iana.org/assignments/http-cache-directives) [cache-directives](https://www.iana.org/assignments/http-cache-directives)>. A registration MUST include the following fields: \* Cache Directive Name \* Pointer to specification text Values to be added to this namespace require IETF Review (see [[RFC8126], Section 4.8](https://datatracker.ietf.org/doc/html/rfc8126#section-4.8)). ### 5.3. Expires The "Expires" response header field gives the date/time after which the response is considered stale. See [Section 4.2](#section-4.2) for further discussion of the freshness model. The presence of an Expires header field does not imply that the original resource will change or cease to exist at, before, or after that time. The Expires field value is an HTTP-date timestamp, as defined in Section 5.6.7 of [[HTTP](#ref-HTTP)]. See also [Section 4.2](#section-4.2) for parsing requirements specific to caches. Expires = HTTP-date For example Expires: Thu, 01 Dec 1994 16:00:00 GMT A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired"). If a response includes a Cache-Control header field with the max-age directive ([Section 5.2.2.1](#section-5.2.2.1)), a recipient MUST ignore the Expires header field. Likewise, if a response includes the s-maxage directive ([Section 5.2.2.10](#section-5.2.2.10)), a shared cache recipient MUST ignore the Expires header field. In both these cases, the value in Expires is only intended for recipients that have not yet implemented the Cache-Control header field. An origin server without a clock (Section 5.6.7 of [[HTTP](#ref-HTTP)]) MUST NOT generate an Expires header field unless its value represents a fixed time in the past (always expired) or its value has been associated with the resource by a system with a clock. Historically, HTTP required the Expires field value to be no more than a year in the future. While longer freshness lifetimes are no longer prohibited, extremely large values have been demonstrated to cause problems (e.g., clock overflows due to use of 32-bit integers for time values), and many caches will evict a response far sooner than that. ### 5.4. Pragma The "Pragma" request header field was defined for HTTP/1.0 caches, so that clients could specify a "no-cache" request (as Cache-Control was not defined until HTTP/1.1). However, support for Cache-Control is now widespread. As a result, this specification deprecates Pragma. | \*Note:\* Because the meaning of "Pragma: no-cache" in responses | was never specified, it does not provide a reliable replacement | for "Cache-Control: no-cache" in them. ### 5.5. Warning The "Warning" header field was used to carry additional information about the status or transformation of a message that might not be reflected in the status code. This specification obsoletes it, as it is not widely generated or surfaced to users. The information it carried can be gleaned from examining other header fields, such as Age. 6. Relationship to Applications and Other Caches ------------------------------------------------ Applications using HTTP often specify additional forms of caching. For example, Web browsers often have history mechanisms such as "Back" buttons that can be used to redisplay a representation retrieved earlier in a session. Likewise, some Web browsers implement caching of images and other assets within a page view; they may or may not honor HTTP caching semantics. The requirements in this specification do not necessarily apply to how applications use data after it is retrieved from an HTTP cache. For example, a history mechanism can display a previous representation even if it has expired, and an application can use cached data in other ways beyond its freshness lifetime. This specification does not prohibit the application from taking HTTP caching into account; for example, a history mechanism might tell the user that a view is stale, or it might honor cache directives (e.g., Cache-Control: no-store). However, when an application caches data and does not make this apparent to or easily controllable by the user, it is strongly encouraged to define its operation with respect to HTTP cache directives so as not to surprise authors who expect caching semantics to be honored. For example, while it might be reasonable to define an application cache "above" HTTP that allows a response containing Cache-Control: no-store to be reused for requests that are directly related to the request that fetched it (such as those created during the same page load), it would likely be surprising and confusing to users and authors if it were allowed to be reused for requests unrelated in any way to the one from which it was obtained. 7. Security Considerations -------------------------- This section is meant to inform developers, information providers, and users of known security concerns specific to HTTP caching. More general security considerations are addressed in "HTTP/1.1" ([Section 11](#section-11) of [HTTP/1.1]) and "HTTP Semantics" (Section 17 of [[HTTP](#ref-HTTP)]). Caches expose an additional attack surface because the contents of the cache represent an attractive target for malicious exploitation. Since cache contents persist after an HTTP request is complete, an attack on the cache can reveal information long after a user believes that the information has been removed from the network. Therefore, cache contents need to be protected as sensitive information. In particular, because private caches are restricted to a single user, they can be used to reconstruct a user's activity. As a result, it is important for user agents to allow end users to control them, for example, by allowing stored responses to be removed for some or all origin servers. ### 7.1. Cache Poisoning Storing malicious content in a cache can extend the reach of an attacker to affect multiple users. Such "cache poisoning" attacks happen when an attacker uses implementation flaws, elevated privileges, or other techniques to insert a response into a cache. This is especially effective when shared caches are used to distribute malicious content to many clients. One common attack vector for cache poisoning is to exploit differences in message parsing on proxies and in user agents; see [Section 6.3](#section-6.3) of [HTTP/1.1] for the relevant requirements regarding HTTP/1.1. ### 7.2. Timing Attacks Because one of the primary uses of a cache is to optimize performance, its use can "leak" information about which resources have been previously requested. For example, if a user visits a site and their browser caches some of its responses and then navigates to a second site, that site can attempt to load responses it knows exist on the first site. If they load quickly, it can be assumed that the user has visited that site, or even a specific page on it. Such "timing attacks" can be mitigated by adding more information to the cache key, such as the identity of the referring site (to prevent the attack described above). This is sometimes called "double keying". ### 7.3. Caching of Sensitive Information Implementation and deployment flaws (often led to by the misunderstanding of cache operation) might lead to the caching of sensitive information (e.g., authentication credentials) that is thought to be private, exposing it to unauthorized parties. Note that the Set-Cookie response header field [[COOKIE](#ref-COOKIE)] does not inhibit caching; a cacheable response with a Set-Cookie header field can be (and often is) used to satisfy subsequent requests to caches. Servers that wish to control caching of these responses are encouraged to emit appropriate Cache-Control response header fields. 8. IANA Considerations ---------------------- The change controller for the following registrations is: "IETF ([email protected]) - Internet Engineering Task Force". ### 8.1. Field Name Registration IANA has updated the "Hypertext Transfer Protocol (HTTP) Field Name Registry" at <<https://www.iana.org/assignments/http-fields>>, as described in Section 18.4 of [[HTTP](#ref-HTTP)], with the field names listed in the table below: +===============+============+=========+==========+ | Field Name | Status | Section | Comments | +===============+============+=========+==========+ | Age | permanent | 5.1 | | +---------------+------------+---------+----------+ | Cache-Control | permanent | 5.2 | | +---------------+------------+---------+----------+ | Expires | permanent | 5.3 | | +---------------+------------+---------+----------+ | Pragma | deprecated | 5.4 | | +---------------+------------+---------+----------+ | Warning | obsoleted | 5.5 | | +---------------+------------+---------+----------+ Table 1 ### 8.2. Cache Directive Registration IANA has updated the "Hypertext Transfer Protocol (HTTP) Cache Directive Registry" at <[https://www.iana.org/assignments/http-cache-](https://www.iana.org/assignments/http-cache-directives) [directives](https://www.iana.org/assignments/http-cache-directives)> with the registration procedure per [Section 5.2.4](#section-5.2.4) and the cache directive names summarized in the table below. +==================+==================+ | Cache Directive | Section | +==================+==================+ | max-age | 5.2.1.1, 5.2.2.1 | +------------------+------------------+ | max-stale | 5.2.1.2 | +------------------+------------------+ | min-fresh | 5.2.1.3 | +------------------+------------------+ | must-revalidate | 5.2.2.2 | +------------------+------------------+ | must-understand | 5.2.2.3 | +------------------+------------------+ | no-cache | 5.2.1.4, 5.2.2.4 | +------------------+------------------+ | no-store | 5.2.1.5, 5.2.2.5 | +------------------+------------------+ | no-transform | 5.2.1.6, 5.2.2.6 | +------------------+------------------+ | only-if-cached | 5.2.1.7 | +------------------+------------------+ | private | 5.2.2.7 | +------------------+------------------+ | proxy-revalidate | 5.2.2.8 | +------------------+------------------+ | public | 5.2.2.9 | +------------------+------------------+ | s-maxage | 5.2.2.10 | +------------------+------------------+ Table 2 ### 8.3. Warn Code Registry IANA has added the following note to the "Hypertext Transfer Protocol (HTTP) Warn Codes" registry at <[https://www.iana.org/assignments/](https://www.iana.org/assignments/http-warn-codes) [http-warn-codes](https://www.iana.org/assignments/http-warn-codes)> stating that "Warning" has been obsoleted: | The Warning header field (and the warn codes that it uses) has | been obsoleted for HTTP per [[RFC9111](https://datatracker.ietf.org/doc/html/rfc9111)]. 9. References ------------- ### 9.1. Normative References [HTTP] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP Semantics", STD 97, [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110), DOI 10.17487/RFC9110, June 2022, <<https://www.rfc-editor.org/info/rfc9110>>. [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", [BCP 14](https://datatracker.ietf.org/doc/html/bcp14), [RFC 2119](https://datatracker.ietf.org/doc/html/rfc2119), DOI 10.17487/RFC2119, March 1997, <<https://www.rfc-editor.org/info/rfc2119>>. [RFC5234] Crocker, D., Ed. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, [RFC 5234](https://datatracker.ietf.org/doc/html/rfc5234), DOI 10.17487/RFC5234, January 2008, <<https://www.rfc-editor.org/info/rfc5234>>. [RFC7405] Kyzivat, P., "Case-Sensitive String Support in ABNF", [RFC 7405](https://datatracker.ietf.org/doc/html/rfc7405), DOI 10.17487/RFC7405, December 2014, <<https://www.rfc-editor.org/info/rfc7405>>. [RFC8174] Leiba, B., "Ambiguity of Uppercase vs Lowercase in [RFC](https://datatracker.ietf.org/doc/html/rfc2119) [2119](https://datatracker.ietf.org/doc/html/rfc2119) Key Words", [BCP 14](https://datatracker.ietf.org/doc/html/bcp14), [RFC 8174](https://datatracker.ietf.org/doc/html/rfc8174), DOI 10.17487/RFC8174, May 2017, <<https://www.rfc-editor.org/info/rfc8174>>. ### 9.2. Informative References [COOKIE] Barth, A., "HTTP State Management Mechanism", [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265), DOI 10.17487/RFC6265, April 2011, <<https://www.rfc-editor.org/info/rfc6265>>. [HTTP/1.1] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP/1.1", STD 99, [RFC 9112](https://datatracker.ietf.org/doc/html/rfc9112), DOI 10.17487/RFC9112, June 2022, <<https://www.rfc-editor.org/info/rfc9112>>. [RFC2616] Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, "Hypertext Transfer Protocol -- HTTP/1.1", [RFC 2616](https://datatracker.ietf.org/doc/html/rfc2616), DOI 10.17487/RFC2616, June 1999, <<https://www.rfc-editor.org/info/rfc2616>>. [RFC5861] Nottingham, M., "HTTP Cache-Control Extensions for Stale Content", [RFC 5861](https://datatracker.ietf.org/doc/html/rfc5861), DOI 10.17487/RFC5861, May 2010, <<https://www.rfc-editor.org/info/rfc5861>>. [RFC7234] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "Hypertext Transfer Protocol (HTTP/1.1): Caching", [RFC 7234](https://datatracker.ietf.org/doc/html/rfc7234), DOI 10.17487/RFC7234, June 2014, <<https://www.rfc-editor.org/info/rfc7234>>. [RFC8126] Cotton, M., Leiba, B., and T. Narten, "Guidelines for Writing an IANA Considerations Section in RFCs", [BCP 26](https://datatracker.ietf.org/doc/html/bcp26), [RFC 8126](https://datatracker.ietf.org/doc/html/rfc8126), DOI 10.17487/RFC8126, June 2017, <<https://www.rfc-editor.org/info/rfc8126>>. Appendix A. Collected ABNF -------------------------- In the collected ABNF below, list rules are expanded per Section 5.6.1 of [[HTTP](#ref-HTTP)]. Age = delta-seconds Cache-Control = [ cache-directive \*( OWS "," OWS cache-directive ) ] Expires = HTTP-date HTTP-date = <HTTP-date, see [[HTTP](#ref-HTTP)], Section 5.6.7> OWS = <OWS, see [[HTTP](#ref-HTTP)], Section 5.6.3> cache-directive = token [ "=" ( token / quoted-string ) ] delta-seconds = 1\*DIGIT field-name = <field-name, see [[HTTP](#ref-HTTP)], Section 5.1> quoted-string = <quoted-string, see [[HTTP](#ref-HTTP)], Section 5.6.4> token = <token, see [[HTTP](#ref-HTTP)], Section 5.6.2> Appendix B. Changes from [RFC 7234](https://datatracker.ietf.org/doc/html/rfc7234) ---------------------------------------------------------------------------------- Handling of duplicate and conflicting cache directives has been clarified. ([Section 4.2.1](#section-4.2.1)) Cache invalidation of the URIs in the Location and Content-Location header fields is no longer required but is still allowed. ([Section 4.4](#section-4.4)) Cache invalidation of the URIs in the Location and Content-Location header fields is disallowed when the origin is different; previously, it was the host. ([Section 4.4](#section-4.4)) Handling invalid and multiple Age header field values has been clarified. ([Section 5.1](#section-5.1)) Some cache directives defined by this specification now have stronger prohibitions against generating the quoted form of their values, since this has been found to create interoperability problems. Consumers of extension cache directives are no longer required to accept both token and quoted-string forms, but they still need to parse them properly for unknown extensions. ([Section 5.2](#section-5.2)) The public and private cache directives were clarified, so that they do not make responses reusable under any condition. ([Section 5.2.2](#section-5.2.2)) The must-understand cache directive was introduced; caches are no longer required to understand the semantics of new response status codes unless it is present. ([Section 5.2.2.3](#section-5.2.2.3)) The Warning response header was obsoleted. Much of the information supported by Warning could be gleaned by examining the response, and the remaining information -- although potentially useful -- was entirely advisory. In practice, Warning was not added by caches or intermediaries. ([Section 5.5](#section-5.5)) Acknowledgements See Appendix "Acknowledgements" of [[HTTP](#ref-HTTP)], which applies to this document as well. Index A C E F G H M N O P S V W A age [Section 4.2](#section-4.2) Age header field \*\_[Section 5.1](#section-5.1)\_\* C cache [Section 1](#section-1) cache key [Section 2](#section-2); [Section 2](#section-2) Cache-Control header field \*\_[Section 5.2](#section-5.2)\_\* collapsed requests [Section 4](#section-4) E Expires header field \*\_[Section 5.3](#section-5.3)\_\* explicit expiration time [Section 4.2](#section-4.2) F Fields Age \*\_[Section 5.1](#section-5.1)\_\*; \*\_[Section 5.1](#section-5.1)\_\* Cache-Control \*\_[Section 5.2](#section-5.2)\_\* Expires \*\_[Section 5.3](#section-5.3)\_\*; \*\_[Section 5.3](#section-5.3)\_\* Pragma \*\_[Section 5.4](#section-5.4)\_\*; \*\_[Section 5.4](#section-5.4)\_\* Warning \*\_[Section 5.5](#section-5.5)\_\* fresh [Section 4.2](#section-4.2) freshness lifetime [Section 4.2](#section-4.2) G Grammar Age \*\_[Section 5.1](#section-5.1)\_\* Cache-Control \*\_[Section 5.2](#section-5.2)\_\* DIGIT \*\_[Section 1.2](#section-1.2)\_\* Expires \*\_[Section 5.3](#section-5.3)\_\* cache-directive \*\_[Section 5.2](#section-5.2)\_\* delta-seconds \*\_[Section 1.2.2](#section-1.2.2)\_\* H Header Fields Age \*\_[Section 5.1](#section-5.1)\_\*; \*\_[Section 5.1](#section-5.1)\_\* Cache-Control \*\_[Section 5.2](#section-5.2)\_\* Expires \*\_[Section 5.3](#section-5.3)\_\*; \*\_[Section 5.3](#section-5.3)\_\* Pragma \*\_[Section 5.4](#section-5.4)\_\*; \*\_[Section 5.4](#section-5.4)\_\* Warning \*\_[Section 5.5](#section-5.5)\_\* heuristic expiration time [Section 4.2](#section-4.2) heuristically cacheable [Section 4.2.2](#section-4.2.2) M max-age (cache directive) \*\_[Section 5.2.1.1](#section-5.2.1.1)\_\*; \*\_[Section 5.2.2.1](#section-5.2.2.1)\_\* max-stale (cache directive) \*\_[Section 5.2.1.2](#section-5.2.1.2)\_\* min-fresh (cache directive) \*\_[Section 5.2.1.3](#section-5.2.1.3)\_\* must-revalidate (cache directive) \*\_[Section 5.2.2.2](#section-5.2.2.2)\_\* must-understand (cache directive) \*\_[Section 5.2.2.3](#section-5.2.2.3)\_\* N no-cache (cache directive) \*\_[Section 5.2.1.4](#section-5.2.1.4)\_\*; \*\_[Section 5.2.2.4](#section-5.2.2.4)\_\* no-store (cache directive) \*\_[Section 5.2.1.5](#section-5.2.1.5)\_\*; \*\_[Section 5.2.2.5](#section-5.2.2.5)\_\* no-transform (cache directive) \*\_[Section 5.2.1.6](#section-5.2.1.6)\_\*; \*\_[Section 5.2.2.6](#section-5.2.2.6)\_\* O only-if-cached (cache directive) \*\_[Section 5.2.1.7](#section-5.2.1.7)\_\* P Pragma header field \*\_[Section 5.4](#section-5.4)\_\* private (cache directive) \*\_[Section 5.2.2.7](#section-5.2.2.7)\_\* private cache [Section 1](#section-1) proxy-revalidate (cache directive) \*\_[Section 5.2.2.8](#section-5.2.2.8)\_\* public (cache directive) \*\_[Section 5.2.2.9](#section-5.2.2.9)\_\* S s-maxage (cache directive) \*\_[Section 5.2.2.10](#section-5.2.2.10)\_\* shared cache [Section 1](#section-1) stale [Section 4.2](#section-4.2) V validator [Section 4.3.1](#section-4.3.1) W Warning header field \*\_[Section 5.5](#section-5.5)\_\* Authors' Addresses Roy T. Fielding (editor) Adobe 345 Park Ave San Jose, CA 95110 United States of America Email: [email protected] URI: <https://roy.gbiv.com/> Mark Nottingham (editor) Fastly Prahran Australia Email: [email protected] URI: <https://www.mnot.net/> Julian Reschke (editor) greenbytes GmbH Hafenweg 16 48155 Münster Germany Email: [email protected] URI: <https://greenbytes.de/tech/webdav/>
programming_docs
http Overview Overview ======== An overview of HTTP =================== **HTTP** is a [protocol](https://developer.mozilla.org/en-US/docs/Glossary/Protocol) for fetching resources such as HTML documents. It is the foundation of any data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually the Web browser. A complete document is reconstructed from the different sub-documents fetched, for instance, text, layout description, images, videos, scripts, and more. Clients and servers communicate by exchanging individual messages (as opposed to a stream of data). The messages sent by the client, usually a Web browser, are called *requests* and the messages sent by the server as an answer are called *responses*. Designed in the early 1990s, HTTP is an extensible protocol which has evolved over time. It is an application layer protocol that is sent over [TCP](https://developer.mozilla.org/en-US/docs/Glossary/TCP), or over a [TLS](https://developer.mozilla.org/en-US/docs/Glossary/TLS)-encrypted TCP connection, though any reliable transport protocol could theoretically be used. Due to its extensibility, it is used to not only fetch hypertext documents, but also images and videos or to post content to servers, like with HTML form results. HTTP can also be used to fetch parts of documents to update Web pages on demand. Components of HTTP-based systems -------------------------------- HTTP is a client-server protocol: requests are sent by one entity, the user-agent (or a proxy on behalf of it). Most of the time the user-agent is a Web browser, but it can be anything, for example, a robot that crawls the Web to populate and maintain a search engine index. Each individual request is sent to a server, which handles it and provides an answer called the *response*. Between the client and the server there are numerous entities, collectively called [proxies](https://developer.mozilla.org/en-US/docs/Glossary/Proxy_server), which perform different operations and act as gateways or [caches](https://developer.mozilla.org/en-US/docs/Glossary/Cache), for example. In reality, there are more computers between a browser and the server handling the request: there are routers, modems, and more. Thanks to the layered design of the Web, these are hidden in the network and transport layers. HTTP is on top, at the application layer. Although important for diagnosing network problems, the underlying layers are mostly irrelevant to the description of HTTP. ### Client: the user-agent The *user-agent* is any tool that acts on behalf of the user. This role is primarily performed by the Web browser, but it may also be performed by programs used by engineers and Web developers to debug their applications. The browser is **always** the entity initiating the request. It is never the server (though some mechanisms have been added over the years to simulate server-initiated messages). To display a Web page, the browser sends an original request to fetch the HTML document that represents the page. It then parses this file, making additional requests corresponding to execution scripts, layout information (CSS) to display, and sub-resources contained within the page (usually images and videos). The Web browser then combines these resources to present the complete document, the Web page. Scripts executed by the browser can fetch more resources in later phases and the browser updates the Web page accordingly. A Web page is a hypertext document. This means some parts of the displayed content are links, which can be activated (usually by a click of the mouse) to fetch a new Web page, allowing the user to direct their user-agent and navigate through the Web. The browser translates these directions into HTTP requests, and further interprets the HTTP responses to present the user with a clear response. ### The Web server On the opposite side of the communication channel is the server, which *serves* the document as requested by the client. A server appears as only a single machine virtually; but it may actually be a collection of servers sharing the load (load balancing), or a complex piece of software interrogating other computers (like cache, a DB server, or e-commerce servers), totally or partially generating the document on demand. A server is not necessarily a single machine, but several server software instances can be hosted on the same machine. With HTTP/1.1 and the [`Host`](headers/host) header, they may even share the same IP address. ### Proxies Between the Web browser and the server, numerous computers and machines relay the HTTP messages. Due to the layered structure of the Web stack, most of these operate at the transport, network or physical levels, becoming transparent at the HTTP layer and potentially having a significant impact on performance. Those operating at the application layers are generally called **proxies**. These can be transparent, forwarding on the requests they receive without altering them in any way, or non-transparent, in which case they will change the request in some way before passing it along to the server. Proxies may perform numerous functions: * caching (the cache can be public or private, like the browser cache) * filtering (like an antivirus scan or parental controls) * load balancing (to allow multiple servers to serve different requests) * authentication (to control access to different resources) * logging (allowing the storage of historical information) Basic aspects of HTTP --------------------- ### HTTP is simple HTTP is generally designed to be simple and human readable, even with the added complexity introduced in HTTP/2 by encapsulating HTTP messages into frames. HTTP messages can be read and understood by humans, providing easier testing for developers, and reduced complexity for newcomers. ### HTTP is extensible Introduced in HTTP/1.0, [HTTP headers](headers) make this protocol easy to extend and experiment with. New functionality can even be introduced by a simple agreement between a client and a server about a new header's semantics. ### HTTP is stateless, but not sessionless HTTP is stateless: there is no link between two requests being successively carried out on the same connection. This immediately has the prospect of being problematic for users attempting to interact with certain pages coherently, for example, using e-commerce shopping baskets. But while the core of HTTP itself is stateless, HTTP cookies allow the use of stateful sessions. Using header extensibility, HTTP Cookies are added to the workflow, allowing session creation on each HTTP request to share the same context, or the same state. ### HTTP and connections A connection is controlled at the transport layer, and therefore fundamentally out of scope for HTTP. HTTP doesn't require the underlying transport protocol to be connection-based; it only requires it to be *reliable*, or not lose messages (at minimum, presenting an error in such cases). Among the two most common transport protocols on the Internet, TCP is reliable and UDP isn't. HTTP therefore relies on the TCP standard, which is connection-based. Before a client and server can exchange an HTTP request/response pair, they must establish a TCP connection, a process which requires several round-trips. The default behavior of HTTP/1.0 is to open a separate TCP connection for each HTTP request/response pair. This is less efficient than sharing a single TCP connection when multiple requests are sent in close succession. In order to mitigate this flaw, HTTP/1.1 introduced *pipelining* (which proved difficult to implement) and *persistent connections*: the underlying TCP connection can be partially controlled using the [`Connection`](headers/connection) header. HTTP/2 went a step further by multiplexing messages over a single connection, helping keep the connection warm and more efficient. Experiments are in progress to design a better transport protocol more suited to HTTP. For example, Google is experimenting with [QUIC](https://en.wikipedia.org/wiki/QUIC) which builds on UDP to provide a more reliable and efficient transport protocol. What can be controlled by HTTP ------------------------------ This extensible nature of HTTP has, over time, allowed for more control and functionality of the Web. Cache and authentication methods were functions handled early in HTTP history. The ability to relax the *origin constraint*, by contrast, was only added in the 2010s. Here is a list of common features controllable with HTTP: * *[Caching](caching)* How documents are cached can be controlled by HTTP. The server can instruct proxies and clients about what to cache and for how long. The client can instruct intermediate cache proxies to ignore the stored document. * *Relaxing the origin constraint* To prevent snooping and other privacy invasions, Web browsers enforce strict separation between Web sites. Only pages from the **same origin** can access all the information of a Web page. Though such a constraint is a burden to the server, HTTP headers can relax this strict separation on the server side, allowing a document to become a patchwork of information sourced from different domains; there could even be security-related reasons to do so. * *Authentication* Some pages may be protected so that only specific users can access them. Basic authentication may be provided by HTTP, either using the [`WWW-Authenticate`](headers/www-authenticate) and similar headers, or by setting a specific session using [HTTP cookies](cookies). * *[Proxy and tunneling](proxy_servers_and_tunneling)* Servers or clients are often located on intranets and hide their true IP address from other computers. HTTP requests then go through proxies to cross this network barrier. Not all proxies are HTTP proxies. The SOCKS protocol, for example, operates at a lower level. Other protocols, like ftp, can be handled by these proxies. * *Sessions* Using HTTP cookies allows you to link requests with the state of the server. This creates sessions, despite basic HTTP being a state-less protocol. This is useful not only for e-commerce shopping baskets, but also for any site allowing user configuration of the output. HTTP flow --------- When a client wants to communicate with a server, either the final server or an intermediate proxy, it performs the following steps: 1. Open a TCP connection: The TCP connection is used to send a request, or several, and receive an answer. The client may open a new connection, reuse an existing connection, or open several TCP connections to the servers. 2. Send an HTTP message: HTTP messages (before HTTP/2) are human-readable. With HTTP/2, these simple messages are encapsulated in frames, making them impossible to read directly, but the principle remains the same. For example: ``` GET / HTTP/1.1 Host: developer.mozilla.org Accept-Language: fr ``` 3. Read the response sent by the server, such as: ``` HTTP/1.1 200 OK Date: Sat, 09 Oct 2010 14:28:02 GMT Server: Apache Last-Modified: Tue, 01 Dec 2009 20:18:22 GMT ETag: "51142bc1-7449-479b075b2891b" Accept-Ranges: bytes Content-Length: 29769 Content-Type: text/html <!DOCTYPE html>… (here come the 29769 bytes of the requested web page) ``` 4. Close or reuse the connection for further requests. If HTTP pipelining is activated, several requests can be sent without waiting for the first response to be fully received. HTTP pipelining has proven difficult to implement in existing networks, where old pieces of software coexist with modern versions. HTTP pipelining has been superseded in HTTP/2 with more robust multiplexing requests within a frame. HTTP Messages ------------- HTTP messages, as defined in HTTP/1.1 and earlier, are human-readable. In HTTP/2, these messages are embedded into a binary structure, a *frame*, allowing optimizations like compression of headers and multiplexing. Even if only part of the original HTTP message is sent in this version of HTTP, the semantics of each message is unchanged and the client reconstitutes (virtually) the original HTTP/1.1 request. It is therefore useful to comprehend HTTP/2 messages in the HTTP/1.1 format. There are two types of HTTP messages, requests and responses, each with its own format. ### Requests An example HTTP request: Requests consist of the following elements: * An HTTP [method](methods), usually a verb like [`GET`](methods/get), [`POST`](methods/post), or a noun like [`OPTIONS`](methods/options) or [`HEAD`](methods/head) that defines the operation the client wants to perform. Typically, a client wants to fetch a resource (using `GET`) or post the value of an [HTML form](https://developer.mozilla.org/en-US/docs/Learn/Forms) (using `POST`), though more operations may be needed in other cases. * The path of the resource to fetch; the URL of the resource stripped from elements that are obvious from the context, for example without the [protocol](https://developer.mozilla.org/en-US/docs/Glossary/Protocol) (`http://`), the [domain](https://developer.mozilla.org/en-US/docs/Glossary/Domain) (here, `developer.mozilla.org`), or the TCP [port](https://developer.mozilla.org/en-US/docs/Glossary/Port) (here, `80`). * The version of the HTTP protocol. * Optional <headers> that convey additional information for the servers. * A body, for some methods like `POST`, similar to those in responses, which contain the resource sent. ### Responses An example response: Responses consist of the following elements: * The version of the HTTP protocol they follow. * A [status code](status), indicating if the request was successful or not, and why. * A status message, a non-authoritative short description of the status code. * HTTP <headers>, like those for requests. * Optionally, a body containing the fetched resource. APIs based on HTTP ------------------ The most commonly used API based on HTTP is the [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) API, which can be used to exchange data between a [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) and a server. The modern [`Fetch API`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provides the same features with a more powerful and flexible feature set. Another API, [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events), is a one-way service that allows a server to send events to the client, using HTTP as a transport mechanism. Using the [`EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) interface, the client opens a connection and establishes event handlers. The client browser automatically converts the messages that arrive on the HTTP stream into appropriate [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) objects. Then it delivers them to the event handlers that have been registered for the events' [`type`](https://developer.mozilla.org/en-US/docs/Web/API/Event/type) if known, or to the [`onmessage`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource/message_event) event handler if no type-specific event handler was established. Conclusion ---------- HTTP is an extensible protocol that is easy to use. The client-server structure, combined with the ability to add headers, allows HTTP to advance along with the extended capabilities of the Web. Though HTTP/2 adds some complexity by embedding HTTP messages in frames to improve performance, the basic structure of messages has stayed the same since HTTP/1.0. Session flow remains simple, allowing it to be investigated and debugged with a simple [HTTP message monitor](https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/index.html). http HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) Network Working Group L. Dusseault, Ed. Request for Comments: 4918 CommerceNet Obsoletes: [2518](https://datatracker.ietf.org/doc/html/rfc2518) June 2007 Category: Standards Track HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) ===================================================================== Status of This Memo This document specifies an Internet standards track protocol for the Internet community, and requests discussion and suggestions for improvements. Please refer to the current edition of the "Internet Official Protocol Standards" (STD 1) for the standardization state and status of this protocol. Distribution of this memo is unlimited. Copyright Notice Copyright (C) The IETF Trust (2007). Abstract Web Distributed Authoring and Versioning (WebDAV) consists of a set of methods, headers, and content-types ancillary to HTTP/1.1 for the management of resource properties, creation and management of resource collections, URL namespace manipulation, and resource locking (collision avoidance). [RFC 2518](https://datatracker.ietf.org/doc/html/rfc2518) was published in February 1999, and this specification obsoletes [RFC 2518](https://datatracker.ietf.org/doc/html/rfc2518) with minor revisions mostly due to interoperability experience. Table of Contents [1](#section-1). Introduction [2](#section-2). Notational Conventions [3](#section-3). Terminology [4](#section-4). Data Model for Resource Properties [4.1](#section-4.1). The Resource Property Model [4.2](#section-4.2). Properties and HTTP Headers [4.3](#section-4.3). Property Values [4.3.1](#section-4.3.1). Example - Property with Mixed Content [4.4](#section-4.4). Property Names [4.5](#section-4.5). Source Resources and Output Resources [5](#section-5). Collections of Web Resources [5.1](#section-5.1). HTTP URL Namespace Model [5.2](#section-5.2). Collection Resources [6](#section-6). Locking [6.1](#section-6.1). Lock Model [6.2](#section-6.2). Exclusive vs. Shared Locks [6.3](#section-6.3). Required Support [6.4](#section-6.4). Lock Creator and Privileges [6.5](#section-6.5). Lock Tokens [6.6](#section-6.6). Lock Timeout [6.7](#section-6.7). Lock Capability Discovery [6.8](#section-6.8). Active Lock Discovery [7](#section-7). Write Lock [7.1](#section-7.1). Write Locks and Properties [7.2](#section-7.2). Avoiding Lost Updates [7.3](#section-7.3). Write Locks and Unmapped URLs [7.4](#section-7.4). Write Locks and Collections [7.5](#section-7.5). Write Locks and the If Request Header [7.5.1](#section-7.5.1). Example - Write Lock and COPY 7.5.2. Example - Deleting a Member of a Locked Collection [7.6](#section-7.6). Write Locks and COPY/MOVE [7.7](#section-7.7). Refreshing Write Locks [8](#section-8). General Request and Response Handling [8.1](#section-8.1). Precedence in Error Handling [8.2](#section-8.2). Use of XML [8.3](#section-8.3). URL Handling [8.3.1](#section-8.3.1). Example - Correct URL Handling [8.4](#section-8.4). Required Bodies in Requests [8.5](#section-8.5). HTTP Headers for Use in WebDAV [8.6](#section-8.6). ETag [8.7](#section-8.7). Including Error Response Bodies [8.8](#section-8.8). Impact of Namespace Operations on Cache Validators [9](#section-9). HTTP Methods for Distributed Authoring [9.1](#section-9.1). PROPFIND Method [9.1.1](#section-9.1.1). PROPFIND Status Codes .............................. [9.1.2](#section-9.1.2). Status Codes for Use in 'propstat' Element [9.1.3](#section-9.1.3). Example - Retrieving Named Properties 9.1.4. Example - Using 'propname' to Retrieve All Property Names [9.1.5](#section-9.1.5). Example - Using So-called 'allprop' [9.1.6](#section-9.1.6). Example - Using 'allprop' with 'include' [9.2](#section-9.2). PROPPATCH Method [9.2.1](#section-9.2.1). Status Codes for Use in 'propstat' Element [9.2.2](#section-9.2.2). Example - PROPPATCH [9.3](#section-9.3). MKCOL Method [9.3.1](#section-9.3.1). MKCOL Status Codes [9.3.2](#section-9.3.2). Example - MKCOL [9.4](#section-9.4). GET, HEAD for Collections [9.5](#section-9.5). POST for Collections [9.6](#section-9.6). DELETE Requirements [9.6.1](#section-9.6.1). DELETE for Collections [9.6.2](#section-9.6.2). Example - DELETE [9.7](#section-9.7). PUT Requirements [9.7.1](#section-9.7.1). PUT for Non-Collection Resources [9.7.2](#section-9.7.2). PUT for Collections [9.8](#section-9.8). COPY Method [9.8.1](#section-9.8.1). COPY for Non-collection Resources [9.8.2](#section-9.8.2). COPY for Properties [9.8.3](#section-9.8.3). COPY for Collections [9.8.4](#section-9.8.4). COPY and Overwriting Destination Resources [9.8.5](#section-9.8.5). Status Codes [9.8.6](#section-9.8.6). Example - COPY with Overwrite [9.8.7](#section-9.8.7). Example - COPY with No Overwrite [9.8.8](#section-9.8.8). Example - COPY of a Collection [9.9](#section-9.9). MOVE Method [9.9.1](#section-9.9.1). MOVE for Properties [9.9.2](#section-9.9.2). MOVE for Collections [9.9.3](#section-9.9.3). MOVE and the Overwrite Header [9.9.4](#section-9.9.4). Status Codes [9.9.5](#section-9.9.5). Example - MOVE of a Non-Collection [9.9.6](#section-9.9.6). Example - MOVE of a Collection [9.10](#section-9.10). LOCK Method [9.10.1](#section-9.10.1). Creating a Lock on an Existing Resource [9.10.2](#section-9.10.2). Refreshing Locks [9.10.3](#section-9.10.3). Depth and Locking [9.10.4](#section-9.10.4). Locking Unmapped URLs [9.10.5](#section-9.10.5). Lock Compatibility Table [9.10.6](#section-9.10.6). LOCK Responses [9.10.7](#section-9.10.7). Example - Simple Lock Request [9.10.8](#section-9.10.8). Example - Refreshing a Write Lock [9.10.9](#section-9.10.9). Example - Multi-Resource Lock Request [9.11](#section-9.11). UNLOCK Method [9.11.1](#section-9.11.1). Status Codes ...................................... [9.11.2](#section-9.11.2). Example - UNLOCK [10](#section-10). HTTP Headers for Distributed Authoring [10.1](#section-10.1). DAV Header [10.2](#section-10.2). Depth Header [10.3](#section-10.3). Destination Header [10.4](#section-10.4). If Header [10.4.1](#section-10.4.1). Purpose [10.4.2](#section-10.4.2). Syntax [10.4.3](#section-10.4.3). List Evaluation [10.4.4](#section-10.4.4). Matching State Tokens and ETags [10.4.5](#section-10.4.5). If Header and Non-DAV-Aware Proxies [10.4.6](#section-10.4.6). Example - No-tag Production [10.4.7](#section-10.4.7). Example - Using "Not" with No-tag Production 10.4.8. Example - Causing a Condition to Always Evaluate to True [10.4.9](#section-10.4.9). Example - Tagged List If Header in COPY 10.4.10. Example - Matching Lock Tokens with Collection Locks [10.4.11](#section-10.4.11). Example - Matching ETags on Unmapped URLs [10.5](#section-10.5). Lock-Token Header [10.6](#section-10.6). Overwrite Header [10.7](#section-10.7). Timeout Request Header [11](#section-11). Status Code Extensions to HTTP/1.1 [11.1](#section-11.1). 207 Multi-Status [11.2](#section-11.2). 422 Unprocessable Entity [11.3](#section-11.3). 423 Locked [11.4](#section-11.4). 424 Failed Dependency [11.5](#section-11.5). 507 Insufficient Storage [12](#section-12). Use of HTTP Status Codes [12.1](#section-12.1). 412 Precondition Failed [12.2](#section-12.2). 414 Request-URI Too Long [13](#section-13). Multi-Status Response [13.1](#section-13.1). Response Headers [13.2](#section-13.2). Handling Redirected Child Resources [13.3](#section-13.3). Internal Status Codes [14](#section-14). XML Element Definitions [14.1](#section-14.1). activelock XML Element [14.2](#section-14.2). allprop XML Element [14.3](#section-14.3). collection XML Element [14.4](#section-14.4). depth XML Element [14.5](#section-14.5). error XML Element [14.6](#section-14.6). exclusive XML Element [14.7](#section-14.7). href XML Element [14.8](#section-14.8). include XML Element [14.9](#section-14.9). location XML Element [14.10](#section-14.10). lockentry XML Element [14.11](#section-14.11). lockinfo XML Element [14.12](#section-14.12). lockroot XML Element .................................... [14.13](#section-14.13). lockscope XML Element [14.14](#section-14.14). locktoken XML Element [14.15](#section-14.15). locktype XML Element [14.16](#section-14.16). multistatus XML Element [14.17](#section-14.17). owner XML Element [14.18](#section-14.18). prop XML Element [14.19](#section-14.19). propertyupdate XML Element [14.20](#section-14.20). propfind XML Element [14.21](#section-14.21). propname XML Element [14.22](#section-14.22). propstat XML Element [14.23](#section-14.23). remove XML Element [14.24](#section-14.24). response XML Element [14.25](#section-14.25). responsedescription XML Element [14.26](#section-14.26). set XML Element [14.27](#section-14.27). shared XML Element [14.28](#section-14.28). status XML Element [14.29](#section-14.29). timeout XML Element [14.30](#section-14.30). write XML Element [15](#section-15). DAV Properties [16](#section-16). Precondition/Postcondition XML Elements [17](#section-17). XML Extensibility in DAV [18](#section-18). DAV Compliance Classes [18.1](#section-18.1). Class 1 [18.2](#section-18.2). Class 2 [18.3](#section-18.3). Class 3 [19](#section-19). Internationalization Considerations [20](#section-20). Security Considerations [20.1](#section-20.1). Authentication of Clients [20.2](#section-20.2). Denial of Service [20.3](#section-20.3). Security through Obscurity [20.4](#section-20.4). Privacy Issues Connected to Locks [20.5](#section-20.5). Privacy Issues Connected to Properties [20.6](#section-20.6). Implications of XML Entities [20.7](#section-20.7). Risks Connected with Lock Tokens [20.8](#section-20.8). Hosting Malicious Content [21](#section-21). IANA Considerations [21.1](#section-21.1). New URI Schemes [21.2](#section-21.2). XML Namespaces [21.3](#section-21.3). Message Header Fields [21.3.1](#section-21.3.1). DAV [21.3.2](#section-21.3.2). Depth [21.3.3](#section-21.3.3). Destination [21.3.4](#section-21.3.4). If [21.3.5](#section-21.3.5). Lock-Token [21.3.6](#section-21.3.6). Overwrite [21.3.7](#section-21.3.7). Timeout [21.4](#section-21.4). HTTP Status Codes [22](#section-22). Acknowledgements ............................................. [23](#section-23). Contributors to This Specification [24](#section-24). Authors of [RFC 2518](https://datatracker.ietf.org/doc/html/rfc2518) [25](#section-25). References [25.1](#section-25.1). Normative References [25.2](#section-25.2). Informative References [Appendix A](#appendix-A). Notes on Processing XML Elements [A.1](#appendix-A.1). Notes on Empty XML Elements [A.2](#appendix-A.2). Notes on Illegal XML Processing [A.3](#appendix-A.3). Example - XML Syntax Error [A.4](#appendix-A.4). Example - Unexpected XML Element [Appendix B](#appendix-B). Notes on HTTP Client Compatibility [Appendix C](#appendix-C). The 'opaquelocktoken' Scheme and URIs [Appendix D](#appendix-D). Lock-null Resources [D.1](#appendix-D.1). Guidance for Clients Using LOCK to Create Resources [Appendix E](#appendix-E). Guidance for Clients Desiring to Authenticate [Appendix F](#appendix-F). Summary of Changes from [RFC 2518](https://datatracker.ietf.org/doc/html/rfc2518) [F.1](#appendix-F.1). Changes for Both Client and Server Implementations [F.2](#appendix-F.2). Changes for Server Implementations [F.3](#appendix-F.3). Other Changes ............................................ 1. Introduction --------------- This document describes an extension to the HTTP/1.1 protocol that allows clients to perform remote Web content authoring operations. This extension provides a coherent set of methods, headers, request entity body formats, and response entity body formats that provide operations for: Properties: The ability to create, remove, and query information about Web pages, such as their authors, creation dates, etc. Collections: The ability to create sets of documents and to retrieve a hierarchical membership listing (like a directory listing in a file system). Locking: The ability to keep more than one person from working on a document at the same time. This prevents the "lost update problem", in which modifications are lost as first one author, then another, writes changes without merging the other author's changes. Namespace Operations: The ability to instruct the server to copy and move Web resources, operations that change the mapping from URLs to resources. Requirements and rationale for these operations are described in a companion document, "Requirements for a Distributed Authoring and Versioning Protocol for the World Wide Web" [[RFC2291](https://datatracker.ietf.org/doc/html/rfc2291)]. This document does not specify the versioning operations suggested by [[RFC2291](https://datatracker.ietf.org/doc/html/rfc2291)]. That work was done in a separate document, "Versioning Extensions to WebDAV" [[RFC3253](https://datatracker.ietf.org/doc/html/rfc3253)]. The sections below provide a detailed introduction to various WebDAV abstractions: resource properties ([Section 4](#section-4)), collections of resources ([Section 5](#section-5)), locks ([Section 6](#section-6)) in general, and write locks ([Section 7](#section-7)) specifically. These abstractions are manipulated by the WebDAV-specific HTTP methods ([Section 9](#section-9)) and the extra HTTP headers ([Section 10](#section-10)) used with WebDAV methods. General considerations for handling HTTP requests and responses in WebDAV are found in [Section 8](#section-8). While the status codes provided by HTTP/1.1 are sufficient to describe most error conditions encountered by WebDAV methods, there are some errors that do not fall neatly into the existing categories. This specification defines extra status codes developed for WebDAV methods ([Section 11](#section-11)) and describes existing HTTP status codes ([Section 12](#section-12)) as used in WebDAV. Since some WebDAV methods may operate over many resources, the Multi-Status response ([Section 13](#section-13)) has been introduced to return status information for multiple resources. Finally, this version of WebDAV introduces precondition and postcondition ([Section 16](#section-16)) XML elements in error response bodies. WebDAV uses XML ([[REC-XML](#ref-REC-XML)]) for property names and some values, and also uses XML to marshal complicated requests and responses. This specification contains DTD and text definitions of all properties ([Section 15](#section-15)) and all other XML elements ([Section 14](#section-14)) used in marshalling. WebDAV includes a few special rules on extending WebDAV XML marshalling in backwards-compatible ways ([Section 17](#section-17)). Finishing off the specification are sections on what it means for a resource to be compliant with this specification ([Section 18](#section-18)), on internationalization support ([Section 19](#section-19)), and on security ([Section 20](#section-20)). 2. Notational Conventions ------------------------- Since this document describes a set of extensions to the HTTP/1.1 protocol, the augmented BNF used herein to describe protocol elements is exactly the same as described in [Section 2.1 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-2.1), including the rules about implied linear whitespace. Since this augmented BNF uses the basic production rules provided in [Section 2.2 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-2.2), these rules apply to this document as well. Note this is not the standard BNF syntax used in other RFCs. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)]. Note that in natural language, a property like the "creationdate" property in the "DAV:" XML namespace is sometimes referred to as "DAV:creationdate" for brevity. 3. Terminology -------------- URI/URL - A Uniform Resource Identifier and Uniform Resource Locator, respectively. These terms (and the distinction between them) are defined in [[RFC3986](https://datatracker.ietf.org/doc/html/rfc3986)]. URI/URL Mapping - A relation between an absolute URI and a resource. Since a resource can represent items that are not network retrievable, as well as those that are, it is possible for a resource to have zero, one, or many URI mappings. Mapping a resource to an "http" scheme URI makes it possible to submit HTTP protocol requests to the resource using the URI. Path Segment - Informally, the characters found between slashes ("/") in a URI. Formally, as defined in [Section 3.3 of [RFC3986]](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3). Collection - Informally, a resource that also acts as a container of references to child resources. Formally, a resource that contains a set of mappings between path segments and resources and meets the requirements defined in [Section 5](#section-5). Internal Member (of a Collection) - Informally, a child resource of a collection. Formally, a resource referenced by a path segment mapping contained in the collection. Internal Member URL (of a Collection) - A URL of an internal member, consisting of the URL of the collection (including trailing slash) plus the path segment identifying the internal member. Member (of a Collection) - Informally, a "descendant" of a collection. Formally, an internal member of the collection, or, recursively, a member of an internal member. Member URL (of a Collection) - A URL that is either an internal member URL of the collection itself, or is an internal member URL of a member of that collection. Property - A name/value pair that contains descriptive information about a resource. Live Property - A property whose semantics and syntax are enforced by the server. For example, the live property DAV:getcontentlength has its value, the length of the entity returned by a GET request, automatically calculated by the server. Dead Property - A property whose semantics and syntax are not enforced by the server. The server only records the value of a dead property; the client is responsible for maintaining the consistency of the syntax and semantics of a dead property. Principal - A distinct human or computational actor that initiates access to network resources. State Token - A URI that represents a state of a resource. Lock tokens are the only state tokens defined in this specification. 4. Data Model for Resource Properties ------------------------------------- ### 4.1. The Resource Property Model Properties are pieces of data that describe the state of a resource. Properties are data about data. Properties are used in distributed authoring environments to provide for efficient discovery and management of resources. For example, a 'subject' property might allow for the indexing of all resources by their subject, and an 'author' property might allow for the discovery of what authors have written which documents. The DAV property model consists of name/value pairs. The name of a property identifies the property's syntax and semantics, and provides an address by which to refer to its syntax and semantics. There are two categories of properties: "live" and "dead". A live property has its syntax and semantics enforced by the server. Live properties include cases where a) the value of a property is protected and maintained by the server, and b) the value of the property is maintained by the client, but the server performs syntax checking on submitted values. All instances of a given live property MUST comply with the definition associated with that property name. A dead property has its syntax and semantics enforced by the client; the server merely records the value of the property verbatim. ### 4.2. Properties and HTTP Headers Properties already exist, in a limited sense, in HTTP message headers. However, in distributed authoring environments, a relatively large number of properties are needed to describe the state of a resource, and setting/returning them all through HTTP headers is inefficient. Thus, a mechanism is needed that allows a principal to identify a set of properties in which the principal is interested and to set or retrieve just those properties. ### 4.3. Property Values The value of a property is always a (well-formed) XML fragment. XML has been chosen because it is a flexible, self-describing, structured data format that supports rich schema definitions, and because of its support for multiple character sets. XML's self- describing nature allows any property's value to be extended by adding elements. Clients will not break when they encounter extensions because they will still have the data specified in the original schema and MUST ignore elements they do not understand. XML's support for multiple character sets allows any human-readable property to be encoded and read in a character set familiar to the user. XML's support for multiple human languages, using the "xml: lang" attribute, handles cases where the same character set is employed by multiple human languages. Note that xml:lang scope is recursive, so an xml:lang attribute on any element containing a property name element applies to the property value unless it has been overridden by a more locally scoped attribute. Note that a property only has one value, in one language (or language MAY be left undefined); a property does not have multiple values in different languages or a single value in multiple languages. A property is always represented with an XML element consisting of the property name, called the "property name element". The simplest example is an empty property, which is different from a property that does not exist: <R:title xmlns:R="http://www.example.com/ns/"></R:title> The value of the property appears inside the property name element. The value may be any kind of well-formed XML content, including both text-only and mixed content. Servers MUST preserve the following XML Information Items (using the terminology from [[REC-XML-INFOSET](#ref-REC-XML-INFOSET)]) in storage and transmission of dead properties: For the property name Element Information Item itself: [namespace name] [local name] [attributes] named "xml:lang" or any such attribute in scope [children] of type element or character On all Element Information Items in the property value: [namespace name] [local name] [attributes] [[children](#ref-children)] of type element or character On Attribute Information Items in the property value: [namespace name] [local name] [normalized value] On Character Information Items in the property value: [character code] Since prefixes are used in some XML vocabularies (XPath and XML Schema, for example), servers SHOULD preserve, for any Information Item in the value: [prefix] XML Infoset attributes not listed above MAY be preserved by the server, but clients MUST NOT rely on them being preserved. The above rules would also apply by default to live properties, unless defined otherwise. Servers MUST ignore the XML attribute xml:space if present and never use it to change whitespace handling. Whitespace in property values is significant. #### 4.3.1. Example - Property with Mixed Content Consider a dead property 'author' created by the client as follows: <D:prop xml:lang="en" xmlns:D="DAV:"> <x:author xmlns:x='http://example.com/ns'> <x:name>Jane Doe</x:name> <!-- Jane's contact info --> <x:uri type='email' added='2005-11-26'>mailto:[email protected]</x:uri> <x:uri type='web' added='2005-11-27'>http://www.example.com</x:uri> <x:notes xmlns:h='http://www.w3.org/1999/xhtml'> Jane has been working way <h:em>too</h:em> long on the long-awaited revision of <![CDATA[<[RFC2518](https://datatracker.ietf.org/doc/html/rfc2518)>]]>. </x:notes> </x:author> </D:prop> When this property is requested, a server might return: <D:prop xmlns:D='DAV:'><author xml:lang='en' xmlns:x='http://example.com/ns' xmlns='http://example.com/ns' xmlns:h='http://www.w3.org/1999/xhtml'> <x:name>Jane Doe</x:name> <x:uri added="2005-11-26" type="email" >mailto:[email protected]</x:uri> <x:uri added="2005-11-27" type="web" >http://www.example.com</x:uri> <x:notes> Jane has been working way <h:em>too</h:em> long on the long-awaited revision of &lt;[RFC2518](https://datatracker.ietf.org/doc/html/rfc2518)&gt;. </x:notes> </author> </D:prop> Note in this example: o The [[prefix](#ref-prefix)] for the property name itself was not preserved, being non-significant, whereas all other [[prefix](#ref-prefix)] values have been preserved, o attribute values have been rewritten with double quotes instead of single quotes (quoting style is not significant), and attribute order has not been preserved, o the xml:lang attribute has been returned on the property name element itself (it was in scope when the property was set, but the exact position in the response is not considered significant as long as it is in scope), o whitespace between tags has been preserved everywhere (whitespace between attributes not so), o CDATA encapsulation was replaced with character escaping (the reverse would also be legal), o the comment item was stripped (as would have been a processing instruction item). Implementation note: there are cases such as editing scenarios where clients may require that XML content is preserved character by character (such as attribute ordering or quoting style). In this case, clients should consider using a text-only property value by escaping all characters that have a special meaning in XML parsing. ### 4.4. Property Names A property name is a universally unique identifier that is associated with a schema that provides information about the syntax and semantics of the property. Because a property's name is universally unique, clients can depend upon consistent behavior for a particular property across multiple resources, on the same and across different servers, so long as that property is "live" on the resources in question, and the implementation of the live property is faithful to its definition. The XML namespace mechanism, which is based on URIs ([[RFC3986](https://datatracker.ietf.org/doc/html/rfc3986)]), is used to name properties because it prevents namespace collisions and provides for varying degrees of administrative control. The property namespace is flat; that is, no hierarchy of properties is explicitly recognized. Thus, if a property A and a property A/B exist on a resource, there is no recognition of any relationship between the two properties. It is expected that a separate specification will eventually be produced that will address issues relating to hierarchical properties. Finally, it is not possible to define the same property twice on a single resource, as this would cause a collision in the resource's property namespace. ### 4.5. Source Resources and Output Resources Some HTTP resources are dynamically generated by the server. For these resources, there presumably exists source code somewhere governing how that resource is generated. The relationship of source files to output HTTP resources may be one to one, one to many, many to one, or many to many. There is no mechanism in HTTP to determine whether a resource is even dynamic, let alone where its source files exist or how to author them. Although this problem would usefully be solved, interoperable WebDAV implementations have been widely deployed without actually solving this problem, by dealing only with static resources. Thus, the source vs. output problem is not solved in this specification and has been deferred to a separate document. 5. Collections of Web Resources ------------------------------- This section provides a description of a type of Web resource, the collection, and discusses its interactions with the HTTP URL namespace and with HTTP methods. The purpose of a collection resource is to model collection-like objects (e.g., file system directories) within a server's namespace. All DAV-compliant resources MUST support the HTTP URL namespace model specified herein. ### 5.1. HTTP URL Namespace Model The HTTP URL namespace is a hierarchical namespace where the hierarchy is delimited with the "/" character. An HTTP URL namespace is said to be consistent if it meets the following conditions: for every URL in the HTTP hierarchy there exists a collection that contains that URL as an internal member URL. The root, or top-level collection of the namespace under consideration, is exempt from the previous rule. The top-level collection of the namespace under consideration is not necessarily the collection identified by the absolute path '/' -- it may be identified by one or more path segments (e.g., /servlets/webdav/...) Neither HTTP/1.1 nor WebDAV requires that the entire HTTP URL namespace be consistent -- a WebDAV-compatible resource may not have a parent collection. However, certain WebDAV methods are prohibited from producing results that cause namespace inconsistencies. As is implicit in [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)] and [[RFC3986](https://datatracker.ietf.org/doc/html/rfc3986)], any resource, including collection resources, MAY be identified by more than one URI. For example, a resource could be identified by multiple HTTP URLs. ### 5.2. Collection Resources Collection resources differ from other resources in that they also act as containers. Some HTTP methods apply only to a collection, but some apply to some or all of the resources inside the container defined by the collection. When the scope of a method is not clear, the client can specify what depth to apply. Depth can be either zero levels (only the collection), one level (the collection and directly contained resources), or infinite levels (the collection and all contained resources recursively). A collection's state consists of at least a set of mappings between path segments and resources, and a set of properties on the collection itself. In this document, a resource B will be said to be contained in the collection resource A if there is a path segment mapping that maps to B and that is contained in A. A collection MUST contain at most one mapping for a given path segment, i.e., it is illegal to have the same path segment mapped to more than one resource. Properties defined on collections behave exactly as do properties on non-collection resources. A collection MAY have additional state such as entity bodies returned by GET. For all WebDAV-compliant resources A and B, identified by URLs "U" and "V", respectively, such that "V" is equal to "U/SEGMENT", A MUST be a collection that contains a mapping from "SEGMENT" to B. So, if resource B with URL "http://example.com/bar/blah" is WebDAV compliant and if resource A with URL "http://example.com/bar/" is WebDAV compliant, then resource A must be a collection and must contain exactly one mapping from "blah" to B. Although commonly a mapping consists of a single segment and a resource, in general, a mapping consists of a set of segments and a resource. This allows a server to treat a set of segments as equivalent (i.e., either all of the segments are mapped to the same resource, or none of the segments are mapped to a resource). For example, a server that performs case-folding on segments will treat the segments "ab", "Ab", "aB", and "AB" as equivalent. A client can then use any of these segments to identify the resource. Note that a PROPFIND result will select one of these equivalent segments to identify the mapping, so there will be one PROPFIND response element per mapping, not one per segment in the mapping. Collection resources MAY have mappings to non-WebDAV-compliant resources in the HTTP URL namespace hierarchy but are not required to do so. For example, if resource X with URL "http://example.com/bar/blah" is not WebDAV compliant and resource A with "URL http://example.com/bar/" identifies a WebDAV collection, then A may or may not have a mapping from "blah" to X. If a WebDAV-compliant resource has no WebDAV-compliant internal members in the HTTP URL namespace hierarchy, then the WebDAV- compliant resource is not required to be a collection. There is a standing convention that when a collection is referred to by its name without a trailing slash, the server MAY handle the request as if the trailing slash were present. In this case, it SHOULD return a Content-Location header in the response, pointing to the URL ending with the "/". For example, if a client invokes a method on http://example.com/blah (no trailing slash), the server may respond as if the operation were invoked on http://example.com/blah/ (trailing slash), and should return a Content-Location header with the value http://example.com/blah/. Wherever a server produces a URL referring to a collection, the server SHOULD include the trailing slash. In general, clients SHOULD use the trailing slash form of collection names. If clients do not use the trailing slash form the client needs to be prepared to see a redirect response. Clients will find the DAV:resourcetype property more reliable than the URL to find out if a resource is a collection. Clients MUST be able to support the case where WebDAV resources are contained inside non-WebDAV resources. For example, if an OPTIONS response from "http://example.com/servlet/dav/collection" indicates WebDAV support, the client cannot assume that "http://example.com/servlet/dav/" or its parent necessarily are WebDAV collections. A typical scenario in which mapped URLs do not appear as members of their parent collection is the case where a server allows links or redirects to non-WebDAV resources. For instance, "/col/link" might not appear as a member of "/col/", although the server would respond with a 302 status to a GET request to "/col/link"; thus, the URL "/col/link" would indeed be mapped. Similarly, a dynamically- generated page might have a URL mapping from "/col/index.html", thus this resource might respond with a 200 OK to a GET request yet not appear as a member of "/col/". Some mappings to even WebDAV-compliant resources might not appear in the parent collection. An example for this case are servers that support multiple alias URLs for each WebDAV-compliant resource. A server may implement case-insensitive URLs, thus "/col/a" and "/col/A" identify the same resource, yet only either "a" or "A" is reported upon listing the members of "/col". In cases where a server treats a set of segments as equivalent, the server MUST expose only one preferred segment per mapping, consistently chosen, in PROPFIND responses. 6. Locking ---------- The ability to lock a resource provides a mechanism for serializing access to that resource. Using a lock, an authoring client can provide a reasonable guarantee that another principal will not modify a resource while it is being edited. In this way, a client can prevent the "lost update" problem. This specification allows locks to vary over two client-specified parameters, the number of principals involved (exclusive vs. shared) and the type of access to be granted. This document defines locking for only one access type, write. However, the syntax is extensible, and permits the eventual specification of locking for other access types. ### 6.1. Lock Model This section provides a concise model for how locking behaves. Later sections will provide more detail on some of the concepts and refer back to these model statements. Normative statements related to LOCK and UNLOCK method handling can be found in the sections on those methods, whereas normative statements that cover any method are gathered here. 1. A lock either directly or indirectly locks a resource. 2. A resource becomes directly locked when a LOCK request to a URL of that resource creates a new lock. The "lock-root" of the new lock is that URL. If at the time of the request, the URL is not mapped to a resource, a new empty resource is created and directly locked. 3. An exclusive lock ([Section 6.2](#section-6.2)) conflicts with any other kind of lock on the same resource, whether either lock is direct or indirect. A server MUST NOT create conflicting locks on a resource. 4. For a collection that is locked with a depth-infinity lock L, all member resources are indirectly locked. Changes in membership of such a collection affect the set of indirectly locked resources: \* If a member resource is added to the collection, the new member resource MUST NOT already have a conflicting lock, because the new resource MUST become indirectly locked by L. \* If a member resource stops being a member of the collection, then the resource MUST no longer be indirectly locked by L. 5. Each lock is identified by a single globally unique lock token ([Section 6.5](#section-6.5)). 6. An UNLOCK request deletes the lock with the specified lock token. After a lock is deleted, no resource is locked by that lock. 7. A lock token is "submitted" in a request when it appears in an "If" header ([Section 7](#section-7), "Write Lock", discusses when token submission is required for write locks). 8. If a request causes the lock-root of any lock to become an unmapped URL, then the lock MUST also be deleted by that request. ### 6.2. Exclusive vs. Shared Locks The most basic form of lock is an exclusive lock. Exclusive locks avoid having to deal with content change conflicts, without requiring any coordination other than the methods described in this specification. However, there are times when the goal of a lock is not to exclude others from exercising an access right but rather to provide a mechanism for principals to indicate that they intend to exercise their access rights. Shared locks are provided for this case. A shared lock allows multiple principals to receive a lock. Hence any principal that has both access privileges and a valid lock can use the locked resource. With shared locks, there are two trust sets that affect a resource. The first trust set is created by access permissions. Principals who are trusted, for example, may have permission to write to the resource. Among those who have access permission to write to the resource, the set of principals who have taken out a shared lock also must trust each other, creating a (typically) smaller trust set within the access permission write set. Starting with every possible principal on the Internet, in most situations the vast majority of these principals will not have write access to a given resource. Of the small number who do have write access, some principals may decide to guarantee their edits are free from overwrite conflicts by using exclusive write locks. Others may decide they trust their collaborators will not overwrite their work (the potential set of collaborators being the set of principals who have write permission) and use a shared lock, which informs their collaborators that a principal may be working on the resource. The WebDAV extensions to HTTP do not need to provide all of the communications paths necessary for principals to coordinate their activities. When using shared locks, principals may use any out-of- band communication channel to coordinate their work (e.g., face-to- face interaction, written notes, post-it notes on the screen, telephone conversation, email, etc.) The intent of a shared lock is to let collaborators know who else may be working on a resource. Shared locks are included because experience from Web-distributed authoring systems has indicated that exclusive locks are often too rigid. An exclusive lock is used to enforce a particular editing process: take out an exclusive lock, read the resource, perform edits, write the resource, release the lock. This editing process has the problem that locks are not always properly released, for example, when a program crashes or when a lock creator leaves without unlocking a resource. While both timeouts ([Section 6.6](#section-6.6)) and administrative action can be used to remove an offending lock, neither mechanism may be available when needed; the timeout may be long or the administrator may not be available. A successful request for a new shared lock MUST result in the generation of a unique lock associated with the requesting principal. Thus, if five principals have taken out shared write locks on the same resource, there will be five locks and five lock tokens, one for each principal. ### 6.3. Required Support A WebDAV-compliant resource is not required to support locking in any form. If the resource does support locking, it may choose to support any combination of exclusive and shared locks for any access types. The reason for this flexibility is that locking policy strikes to the very heart of the resource management and versioning systems employed by various storage repositories. These repositories require control over what sort of locking will be made available. For example, some repositories only support shared write locks, while others only provide support for exclusive write locks, while yet others use no locking at all. As each system is sufficiently different to merit exclusion of certain locking features, this specification leaves locking as the sole axis of negotiation within WebDAV. ### 6.4. Lock Creator and Privileges The creator of a lock has special privileges to use the lock to modify the resource. When a locked resource is modified, a server MUST check that the authenticated principal matches the lock creator (in addition to checking for valid lock token submission). The server MAY allow privileged users other than the lock creator to destroy a lock (for example, the resource owner or an administrator). The 'unlock' privilege in [[RFC3744](https://datatracker.ietf.org/doc/html/rfc3744)] was defined to provide that permission. There is no requirement for servers to accept LOCK requests from all users or from anonymous users. Note that having a lock does not confer full privilege to modify the locked resource. Write access and other privileges MUST be enforced through normal privilege or authentication mechanisms, not based on the possible obscurity of lock token values. ### 6.5. Lock Tokens A lock token is a type of state token that identifies a particular lock. Each lock has exactly one unique lock token generated by the server. Clients MUST NOT attempt to interpret lock tokens in any way. Lock token URIs MUST be unique across all resources for all time. This uniqueness constraint allows lock tokens to be submitted across resources and servers without fear of confusion. Since lock tokens are unique, a client MAY submit a lock token in an If header on a resource other than the one that returned it. When a LOCK operation creates a new lock, the new lock token is returned in the Lock-Token response header defined in [Section 10.5](#section-10.5), and also in the body of the response. Servers MAY make lock tokens publicly readable (e.g., in the DAV: lockdiscovery property). One use case for making lock tokens readable is so that a long-lived lock can be removed by the resource owner (the client that obtained the lock might have crashed or disconnected before cleaning up the lock). Except for the case of using UNLOCK under user guidance, a client SHOULD NOT use a lock token created by another client instance. This specification encourages servers to create Universally Unique Identifiers (UUIDs) for lock tokens, and to use the URI form defined by "A Universally Unique Identifier (UUID) URN Namespace" ([[RFC4122](https://datatracker.ietf.org/doc/html/rfc4122)]). However, servers are free to use any URI (e.g., from another scheme) so long as it meets the uniqueness requirements. For example, a valid lock token might be constructed using the "opaquelocktoken" scheme defined in [Appendix C](#appendix-C). Example: "urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6" ### 6.6. Lock Timeout A lock MAY have a limited lifetime. The lifetime is suggested by the client when creating or refreshing the lock, but the server ultimately chooses the timeout value. Timeout is measured in seconds remaining until lock expiration. The timeout counter MUST be restarted if a refresh lock request is successful (see [Section 9.10.2](#section-9.10.2)). The timeout counter SHOULD NOT be restarted at any other time. If the timeout expires, then the lock SHOULD be removed. In this case the server SHOULD act as if an UNLOCK method was executed by the server on the resource using the lock token of the timed-out lock, performed with its override authority. Servers are advised to pay close attention to the values submitted by clients, as they will be indicative of the type of activity the client intends to perform. For example, an applet running in a browser may need to lock a resource, but because of the instability of the environment within which the applet is running, the applet may be turned off without warning. As a result, the applet is likely to ask for a relatively small timeout value so that if the applet dies, the lock can be quickly harvested. However, a document management system is likely to ask for an extremely long timeout because its user may be planning on going offline. A client MUST NOT assume that just because the timeout has expired, the lock has immediately been removed. Likewise, a client MUST NOT assume that just because the timeout has not expired, the lock still exists. Clients MUST assume that locks can arbitrarily disappear at any time, regardless of the value given in the Timeout header. The Timeout header only indicates the behavior of the server if extraordinary circumstances do not occur. For example, a sufficiently privileged user may remove a lock at any time, or the system may crash in such a way that it loses the record of the lock's existence. ### 6.7. Lock Capability Discovery Since server lock support is optional, a client trying to lock a resource on a server can either try the lock and hope for the best, or perform some form of discovery to determine what lock capabilities the server supports. This is known as lock capability discovery. A client can determine what lock types the server supports by retrieving the DAV:supportedlock property. Any DAV-compliant resource that supports the LOCK method MUST support the DAV:supportedlock property. ### 6.8. Active Lock Discovery If another principal locks a resource that a principal wishes to access, it is useful for the second principal to be able to find out who the first principal is. For this purpose the DAV:lockdiscovery property is provided. This property lists all outstanding locks, describes their type, and MAY even provide the lock tokens. Any DAV-compliant resource that supports the LOCK method MUST support the DAV:lockdiscovery property. 7. Write Lock ------------- This section describes the semantics specific to the write lock type. The write lock is a specific instance of a lock type, and is the only lock type described in this specification. An exclusive write lock protects a resource: it prevents changes by any principal other than the lock creator and in any case where the lock token is not submitted (e.g., by a client process other than the one holding the lock). Clients MUST submit a lock-token they are authorized to use in any request that modifies a write-locked resource. The list of modifications covered by a write-lock include: 1. A change to any of the following aspects of any write-locked resource: \* any variant, \* any dead property, \* any live property that is lockable (a live property is lockable unless otherwise defined.) 2. For collections, any modification of an internal member URI. An internal member URI of a collection is considered to be modified if it is added, removed, or identifies a different resource. More discussion on write locks and collections is found in [Section 7.4](#section-7.4). 3. A modification of the mapping of the root of the write lock, either to another resource or to no resource (e.g., DELETE). Of the methods defined in HTTP and WebDAV, PUT, POST, PROPPATCH, LOCK, UNLOCK, MOVE, COPY (for the destination resource), DELETE, and MKCOL are affected by write locks. All other HTTP/WebDAV methods defined so far -- GET in particular -- function independently of a write lock. The next few sections describe in more specific terms how write locks interact with various operations. ### 7.1. Write Locks and Properties While those without a write lock may not alter a property on a resource it is still possible for the values of live properties to change, even while locked, due to the requirements of their schemas. Only dead properties and live properties defined as lockable are guaranteed not to change while write locked. ### 7.2. Avoiding Lost Updates Although the write locks provide some help in preventing lost updates, they cannot guarantee that updates will never be lost. Consider the following scenario: Two clients A and B are interested in editing the resource 'index.html'. Client A is an HTTP client rather than a WebDAV client, and so does not know how to perform locking. Client A doesn't lock the document, but does a GET, and begins editing. Client B does LOCK, performs a GET and begins editing. Client B finishes editing, performs a PUT, then an UNLOCK. Client A performs a PUT, overwriting and losing all of B's changes. There are several reasons why the WebDAV protocol itself cannot prevent this situation. First, it cannot force all clients to use locking because it must be compatible with HTTP clients that do not comprehend locking. Second, it cannot require servers to support locking because of the variety of repository implementations, some of which rely on reservations and merging rather than on locking. Finally, being stateless, it cannot enforce a sequence of operations like LOCK / GET / PUT / UNLOCK. WebDAV servers that support locking can reduce the likelihood that clients will accidentally overwrite each other's changes by requiring clients to lock resources before modifying them. Such servers would effectively prevent HTTP 1.0 and HTTP 1.1 clients from modifying resources. WebDAV clients can be good citizens by using a lock / retrieve / write /unlock sequence of operations (at least by default) whenever they interact with a WebDAV server that supports locking. HTTP 1.1 clients can be good citizens, avoiding overwriting other clients' changes, by using entity tags in If-Match headers with any requests that would modify resources. Information managers may attempt to prevent overwrites by implementing client-side procedures requiring locking before modifying WebDAV resources. ### 7.3. Write Locks and Unmapped URLs WebDAV provides the ability to send a LOCK request to an unmapped URL in order to reserve the name for use. This is a simple way to avoid the lost-update problem on the creation of a new resource (another way is to use If-None-Match header specified in [Section 14.26 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-14.26)). It has the side benefit of locking the new resource immediately for use of the creator. Note that the lost-update problem is not an issue for collections because MKCOL can only be used to create a collection, not to overwrite an existing collection. When trying to lock a collection upon creation, clients can attempt to increase the likelihood of getting the lock by pipelining the MKCOL and LOCK requests together (but because this doesn't convert two separate operations into one atomic operation, there's no guarantee this will work). A successful lock request to an unmapped URL MUST result in the creation of a locked (non-collection) resource with empty content. Subsequently, a successful PUT request (with the correct lock token) provides the content for the resource. Note that the LOCK request has no mechanism for the client to provide Content-Type or Content- Language, thus the server will use defaults or empty values and rely on the subsequent PUT request for correct values. A resource created with a LOCK is empty but otherwise behaves in every way as a normal resource. It behaves the same way as a resource created by a PUT request with an empty body (and where a Content-Type and Content-Language was not specified), followed by a LOCK request to the same resource. Following from this model, a locked empty resource: o Can be read, deleted, moved, and copied, and in all ways behaves as a regular non-collection resource. o Appears as a member of its parent collection. o SHOULD NOT disappear when its lock goes away (clients must therefore be responsible for cleaning up their own mess, as with any other operation or any non-empty resource). o MAY NOT have values for properties like DAV:getcontentlanguage that haven't been specified yet by the client. o Can be updated (have content added) with a PUT request. o MUST NOT be converted into a collection. The server MUST fail a MKCOL request (as it would with a MKCOL request to any existing non-collection resource). o MUST have defined values for DAV:lockdiscovery and DAV: supportedlock properties. o The response MUST indicate that a resource was created, by use of the "201 Created" response code (a LOCK request to an existing resource instead will result in 200 OK). The body must still include the DAV:lockdiscovery property, as with a LOCK request to an existing resource. The client is expected to update the locked empty resource shortly after locking it, using PUT and possibly PROPPATCH. Alternatively and for backwards compatibility to [[RFC2518](https://datatracker.ietf.org/doc/html/rfc2518)], servers MAY implement Lock-Null Resources (LNRs) instead (see definition in [Appendix D](#appendix-D)). Clients can easily interoperate both with servers that support the old model LNRs and the recommended model of "locked empty resources" by only attempting PUT after a LOCK to an unmapped URL, not MKCOL or GET, and by not relying on specific properties of LNRs. ### 7.4. Write Locks and Collections There are two kinds of collection write locks. A depth-0 write lock on a collection protects the collection properties plus the internal member URLs of that one collection, while not protecting the content or properties of member resources (if the collection itself has any entity bodies, those are also protected). A depth-infinity write lock on a collection provides the same protection on that collection and also provides write lock protection on every member resource. Expressed otherwise, a write lock of either kind protects any request that would create a new resource in a write locked collection, any request that would remove an internal member URL of a write locked collection, and any request that would change the segment name of any internal member. Thus, a collection write lock protects all the following actions: o DELETE a collection's direct internal member, o MOVE an internal member out of the collection, o MOVE an internal member into the collection, o MOVE to rename an internal member within a collection, o COPY an internal member into a collection, and o PUT or MKCOL request that would create a new internal member. The collection's lock token is required in addition to the lock token on the internal member itself, if it is locked separately. In addition, a depth-infinity lock affects all write operations to all members of the locked collection. With a depth-infinity lock, the resource identified by the root of the lock is directly locked, and all its members are indirectly locked. o Any new resource added as a descendant of a depth-infinity locked collection becomes indirectly locked. o Any indirectly locked resource moved out of the locked collection into an unlocked collection is thereafter unlocked. o Any indirectly locked resource moved out of a locked source collection into a depth-infinity locked target collection remains indirectly locked but is now protected by the lock on the target collection (the target collection's lock token will thereafter be required to make further changes). If a depth-infinity write LOCK request is issued to a collection containing member URLs identifying resources that are currently locked in a manner that conflicts with the new lock (see [Section 6.1](#section-6.1), point 3), the request MUST fail with a 423 (Locked) status code, and the response SHOULD contain the 'no-conflicting-lock' precondition. If a lock request causes the URL of a resource to be added as an internal member URL of a depth-infinity locked collection, then the new resource MUST be automatically protected by the lock. For example, if the collection /a/b/ is write locked and the resource /c is moved to /a/b/c, then resource /a/b/c will be added to the write lock. ### 7.5. Write Locks and the If Request Header A user agent has to demonstrate knowledge of a lock when requesting an operation on a locked resource. Otherwise, the following scenario might occur. In the scenario, program A, run by User A, takes out a write lock on a resource. Program B, also run by User A, has no knowledge of the lock taken out by program A, yet performs a PUT to the locked resource. In this scenario, the PUT succeeds because locks are associated with a principal, not a program, and thus program B, because it is acting with principal A's credential, is allowed to perform the PUT. However, had program B known about the lock, it would not have overwritten the resource, preferring instead to present a dialog box describing the conflict to the user. Due to this scenario, a mechanism is needed to prevent different programs from accidentally ignoring locks taken out by other programs with the same authorization. In order to prevent these collisions, a lock token MUST be submitted by an authorized principal for all locked resources that a method may change or the method MUST fail. A lock token is submitted when it appears in an If header. For example, if a resource is to be moved and both the source and destination are locked, then two lock tokens must be submitted in the If header, one for the source and the other for the destination. #### 7.5.1. Example - Write Lock and COPY >>Request COPY /~fielding/index.html HTTP/1.1 Host: www.example.com Destination: http://www.example.com/users/f/fielding/index.html If: <http://www.example.com/users/f/fielding/index.html> (<urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6>) >>Response HTTP/1.1 204 No Content In this example, even though both the source and destination are locked, only one lock token must be submitted (the one for the lock on the destination). This is because the source resource is not modified by a COPY, and hence unaffected by the write lock. In this example, user agent authentication has previously occurred via a mechanism outside the scope of the HTTP protocol, in the underlying transport layer. #### 7.5.2. Example - Deleting a Member of a Locked Collection Consider a collection "/locked" with an exclusive, depth-infinity write lock, and an attempt to delete an internal member "/locked/ member": >>Request DELETE /locked/member HTTP/1.1 Host: example.com >>Response HTTP/1.1 423 Locked Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:error xmlns:D="DAV:"> <D:lock-token-submitted> <D:href>/locked/</D:href> </D:lock-token-submitted> </D:error> Thus, the client would need to submit the lock token with the request to make it succeed. To do that, various forms of the If header (see [Section 10.4](#section-10.4)) could be used. "No-Tag-List" format: If: (<urn:uuid:150852e2-3847-42d5-8cbe-0f4f296f26cf>) "Tagged-List" format, for "http://example.com/locked/": If: <http://example.com/locked/> (<urn:uuid:150852e2-3847-42d5-8cbe-0f4f296f26cf>) "Tagged-List" format, for "http://example.com/locked/member": If: <http://example.com/locked/member> (<urn:uuid:150852e2-3847-42d5-8cbe-0f4f296f26cf>) Note that, for the purpose of submitting the lock token, the actual form doesn't matter; what's relevant is that the lock token appears in the If header, and that the If header itself evaluates to true. ### 7.6. Write Locks and COPY/MOVE A COPY method invocation MUST NOT duplicate any write locks active on the source. However, as previously noted, if the COPY copies the resource into a collection that is locked with a depth-infinity lock, then the resource will be added to the lock. A successful MOVE request on a write locked resource MUST NOT move the write lock with the resource. However, if there is an existing lock at the destination, the server MUST add the moved resource to the destination lock scope. For example, if the MOVE makes the resource a child of a collection that has a depth-infinity lock, then the resource will be added to that collection's lock. Additionally, if a resource with a depth-infinity lock is moved to a destination that is within the scope of the same lock (e.g., within the URL namespace tree covered by the lock), the moved resource will again be added to the lock. In both these examples, as specified in [Section 7.5](#section-7.5), an If header must be submitted containing a lock token for both the source and destination. ### 7.7. Refreshing Write Locks A client MUST NOT submit the same write lock request twice. Note that a client is always aware it is resubmitting the same lock request because it must include the lock token in the If header in order to make the request for a resource that is already locked. However, a client may submit a LOCK request with an If header but without a body. A server receiving a LOCK request with no body MUST NOT create a new lock -- this form of the LOCK request is only to be used to "refresh" an existing lock (meaning, at minimum, that any timers associated with the lock MUST be reset). Clients may submit Timeout headers of arbitrary value with their lock refresh requests. Servers, as always, may ignore Timeout headers submitted by the client, and a server MAY refresh a lock with a timeout period that is different than the previous timeout period used for the lock, provided it advertises the new value in the LOCK refresh response. If an error is received in response to a refresh LOCK request, the client MUST NOT assume that the lock was refreshed. 8. General Request and Response Handling ---------------------------------------- ### 8.1. Precedence in Error Handling Servers MUST return authorization errors in preference to other errors. This avoids leaking information about protected resources (e.g., a client that finds that a hidden resource exists by seeing a 423 Locked response to an anonymous request to the resource). ### 8.2. Use of XML In HTTP/1.1, method parameter information was exclusively encoded in HTTP headers. Unlike HTTP/1.1, WebDAV encodes method parameter information either in an XML ([[REC-XML](#ref-REC-XML)]) request entity body, or in an HTTP header. The use of XML to encode method parameters was motivated by the ability to add extra XML elements to existing structures, providing extensibility; and by XML's ability to encode information in ISO 10646 character sets, providing internationalization support. In addition to encoding method parameters, XML is used in WebDAV to encode the responses from methods, providing the extensibility and internationalization advantages of XML for method output, as well as input. When XML is used for a request or response body, the Content-Type type SHOULD be application/xml. Implementations MUST accept both text/xml and application/xml in request and response bodies. Use of text/xml is deprecated. All DAV-compliant clients and resources MUST use XML parsers that are compliant with [[REC-XML](#ref-REC-XML)] and [[REC-XML-NAMES](#ref-REC-XML-NAMES)]. All XML used in either requests or responses MUST be, at minimum, well formed and use namespaces correctly. If a server receives XML that is not well- formed, then the server MUST reject the entire request with a 400 (Bad Request). If a client receives XML that is not well-formed in a response, then the client MUST NOT assume anything about the outcome of the executed method and SHOULD treat the server as malfunctioning. Note that processing XML submitted by an untrusted source may cause risks connected to privacy, security, and service quality (see [Section 20](#section-20)). Servers MAY reject questionable requests (even though they consist of well-formed XML), for instance, with a 400 (Bad Request) status code and an optional response body explaining the problem. ### 8.3. URL Handling URLs appear in many places in requests and responses. Interoperability experience with [[RFC2518](https://datatracker.ietf.org/doc/html/rfc2518)] showed that many clients parsing Multi-Status responses did not fully implement the full Reference Resolution defined in [Section 5 of [RFC3986]](https://datatracker.ietf.org/doc/html/rfc3986#section-5). Thus, servers in particular need to be careful in handling URLs in responses, to ensure that clients have enough context to be able to interpret all the URLs. The rules in this section apply not only to resource URLs in the 'href' element in Multi-Status responses, but also to the Destination and If header resource URLs. The sender has a choice between two approaches: using a relative reference, which is resolved against the Request-URI, or a full URI. A server MUST ensure that every 'href' value within a Multi-Status response uses the same format. WebDAV only uses one form of relative reference in its extensions, the absolute path. Simple-ref = absolute-URI | ( path-absolute [ "?" query ] ) The absolute-URI, path-absolute and query productions are defined in Sections [4.3](#section-4.3), [3.3](#section-3.3), and [3.4](#section-3.4) of [[RFC3986](https://datatracker.ietf.org/doc/html/rfc3986)]. Within Simple-ref productions, senders MUST NOT: o use dot-segments ("." or ".."), or o have prefixes that do not match the Request-URI (using the comparison rules defined in [Section 3.2.3 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-3.2.3)). Identifiers for collections SHOULD end in a '/' character. #### 8.3.1. Example - Correct URL Handling Consider the collection http://example.com/sample/ with the internal member URL http://example.com/sample/a%20test and the PROPFIND request below: >>Request: PROPFIND /sample/ HTTP/1.1 Host: example.com Depth: 1 In this case, the server should return two 'href' elements containing either o 'http://example.com/sample/' and 'http://example.com/sample/a%20test', or o '/sample/' and '/sample/a%20test' Note that even though the server may be storing the member resource internally as 'a test', it has to be percent-encoded when used inside a URI reference (see [Section 2.1 of [RFC3986]](https://datatracker.ietf.org/doc/html/rfc3986#section-2.1)). Also note that a legal URI may still contain characters that need to be escaped within XML character data, such as the ampersand character. ### 8.4. Required Bodies in Requests Some of these new methods do not define bodies. Servers MUST examine all requests for a body, even when a body was not expected. In cases where a request body is present but would be ignored by a server, the server MUST reject the request with 415 (Unsupported Media Type). This informs the client (which may have been attempting to use an extension) that the body could not be processed as the client intended. ### 8.5. HTTP Headers for Use in WebDAV HTTP defines many headers that can be used in WebDAV requests and responses. Not all of these are appropriate in all situations and some interactions may be undefined. Note that HTTP 1.1 requires the Date header in all responses if possible (see [Section 14.18](#section-14.18), [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]). The server MUST do authorization checks before checking any HTTP conditional header. ### 8.6. ETag HTTP 1.1 recommends the use of ETags rather than modification dates, for cache control, and there are even stronger reasons to prefer ETags for authoring. Correct use of ETags is even more important in a distributed authoring environment, because ETags are necessary along with locks to avoid the lost-update problem. A client might fail to renew a lock, for example, when the lock times out and the client is accidentally offline or in the middle of a long upload. When a client fails to renew the lock, it's quite possible the resource can still be relocked and the user can go on editing, as long as no changes were made in the meantime. ETags are required for the client to be able to distinguish this case. Otherwise, the client is forced to ask the user whether to overwrite the resource on the server without even being able to tell the user if it has changed. Timestamps do not solve this problem nearly as well as ETags. Strong ETags are much more useful for authoring use cases than weak ETags (see [Section 13.3.3 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-13.3.3)). Semantic equivalence can be a useful concept but that depends on the document type and the application type, and interoperability might require some agreement or standard outside the scope of this specification and HTTP. Note also that weak ETags have certain restrictions in HTTP, e.g., these cannot be used in If-Match headers. Note that the meaning of an ETag in a PUT response is not clearly defined either in this document or in [RFC 2616](https://datatracker.ietf.org/doc/html/rfc2616) (i.e., whether the ETag means that the resource is octet-for-octet equivalent to the body of the PUT request, or whether the server could have made minor changes in the formatting or content of the document upon storage). This is an HTTP issue, not purely a WebDAV issue. Because clients may be forced to prompt users or throw away changed content if the ETag changes, a WebDAV server SHOULD NOT change the ETag (or the Last-Modified time) for a resource that has an unchanged body and location. The ETag represents the state of the body or contents of the resource. There is no similar way to tell if properties have changed. ### 8.7. Including Error Response Bodies HTTP and WebDAV did not use the bodies of most error responses for machine-parsable information until the specification for Versioning Extensions to WebDAV introduced a mechanism to include more specific information in the body of an error response ([Section 1.6 of [RFC3253]](https://datatracker.ietf.org/doc/html/rfc3253#section-1.6)). The error body mechanism is appropriate to use with any error response that may take a body but does not already have a body defined. The mechanism is particularly appropriate when a status code can mean many things (for example, 400 Bad Request can mean required headers are missing, headers are incorrectly formatted, or much more). This error body mechanism is covered in [Section 16](#section-16). ### 8.8. Impact of Namespace Operations on Cache Validators Note that the HTTP response headers "Etag" and "Last-Modified" (see [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)], Sections [14.19](#section-14.19) and [14.29](#section-14.29)) are defined per URL (not per resource), and are used by clients for caching. Therefore servers must ensure that executing any operation that affects the URL namespace (such as COPY, MOVE, DELETE, PUT, or MKCOL) does preserve their semantics, in particular: o For any given URL, the "Last-Modified" value MUST increment every time the representation returned upon GET changes (within the limits of timestamp resolution). o For any given URL, an "ETag" value MUST NOT be reused for different representations returned by GET. In practice this means that servers o might have to increment "Last-Modified" timestamps for every resource inside the destination namespace of a namespace operation unless it can do so more selectively, and o similarly, might have to re-assign "ETag" values for these resources (unless the server allocates entity tags in a way so that they are unique across the whole URL namespace managed by the server). Note that these considerations also apply to specific use cases, such as using PUT to create a new resource at a URL that has been mapped before, but has been deleted since then. Finally, WebDAV properties (such as DAV:getetag and DAV: getlastmodified) that inherit their semantics from HTTP headers must behave accordingly. 9. HTTP Methods for Distributed Authoring ----------------------------------------- ### 9.1. PROPFIND Method The PROPFIND method retrieves properties defined on the resource identified by the Request-URI, if the resource does not have any internal members, or on the resource identified by the Request-URI and potentially its member resources, if the resource is a collection that has internal member URLs. All DAV-compliant resources MUST support the PROPFIND method and the propfind XML element ([Section 14.20](#section-14.20)) along with all XML elements defined for use with that element. A client MUST submit a Depth header with a value of "0", "1", or "infinity" with a PROPFIND request. Servers MUST support "0" and "1" depth requests on WebDAV-compliant resources and SHOULD support "infinity" requests. In practice, support for infinite-depth requests MAY be disabled, due to the performance and security concerns associated with this behavior. Servers SHOULD treat a request without a Depth header as if a "Depth: infinity" header was included. A client may submit a 'propfind' XML element in the body of the request method describing what information is being requested. It is possible to: o Request particular property values, by naming the properties desired within the 'prop' element (the ordering of properties in here MAY be ignored by the server), o Request property values for those properties defined in this specification (at a minimum) plus dead properties, by using the 'allprop' element (the 'include' element can be used with 'allprop' to instruct the server to also include additional live properties that may not have been returned otherwise), o Request a list of names of all the properties defined on the resource, by using the 'propname' element. A client may choose not to submit a request body. An empty PROPFIND request body MUST be treated as if it were an 'allprop' request. Note that 'allprop' does not return values for all live properties. WebDAV servers increasingly have expensively-calculated or lengthy properties (see [[RFC3253](https://datatracker.ietf.org/doc/html/rfc3253)] and [[RFC3744](https://datatracker.ietf.org/doc/html/rfc3744)]) and do not return all properties already. Instead, WebDAV clients can use propname requests to discover what live properties exist, and request named properties when retrieving values. For a live property defined elsewhere, that definition can specify whether or not that live property would be returned in 'allprop' requests. All servers MUST support returning a response of content type text/ xml or application/xml that contains a multistatus XML element that describes the results of the attempts to retrieve the various properties. If there is an error retrieving a property, then a proper error result MUST be included in the response. A request to retrieve the value of a property that does not exist is an error and MUST be noted with a 'response' XML element that contains a 404 (Not Found) status value. Consequently, the 'multistatus' XML element for a collection resource MUST include a 'response' XML element for each member URL of the collection, to whatever depth was requested. It SHOULD NOT include any 'response' elements for resources that are not WebDAV-compliant. Each 'response' element MUST contain an 'href' element that contains the URL of the resource on which the properties in the prop XML element are defined. Results for a PROPFIND on a collection resource are returned as a flat list whose order of entries is not significant. Note that a resource may have only one value for a property of a given name, so the property may only show up once in PROPFIND responses. Properties may be subject to access control. In the case of 'allprop' and 'propname' requests, if a principal does not have the right to know whether a particular property exists, then the property MAY be silently excluded from the response. Some PROPFIND results MAY be cached, with care, as there is no cache validation mechanism for most properties. This method is both safe and idempotent (see [Section 9.1 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-9.1)). #### 9.1.1. PROPFIND Status Codes This section, as with similar sections for other methods, provides some guidance on error codes and preconditions or postconditions (defined in [Section 16](#section-16)) that might be particularly useful with PROPFIND. 403 Forbidden - A server MAY reject PROPFIND requests on collections with depth header of "Infinity", in which case it SHOULD use this error with the precondition code 'propfind-finite-depth' inside the error body. #### 9.1.2. Status Codes for Use in 'propstat' Element In PROPFIND responses, information about individual properties is returned inside 'propstat' elements (see [Section 14.22](#section-14.22)), each containing an individual 'status' element containing information about the properties appearing in it. The list below summarizes the most common status codes used inside 'propstat'; however, clients should be prepared to handle other 2/3/4/5xx series status codes as well. 200 OK - A property exists and/or its value is successfully returned. 401 Unauthorized - The property cannot be viewed without appropriate authorization. 403 Forbidden - The property cannot be viewed regardless of authentication. 404 Not Found - The property does not exist. #### 9.1.3. Example - Retrieving Named Properties >>Request PROPFIND /file HTTP/1.1 Host: www.example.com Content-type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:"> <D:prop xmlns:R="http://ns.example.com/boxschema/"> <R:bigbox/> <R:author/> <R:DingALing/> <R:Random/> </D:prop> </D:propfind> >>Response HTTP/1.1 207 Multi-Status Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:multistatus xmlns:D="DAV:"> <D:response xmlns:R="http://ns.example.com/boxschema/"> <D:href>http://www.example.com/file</D:href> <D:propstat> <D:prop> <R:bigbox> <R:BoxType>Box type A</R:BoxType> </R:bigbox> <R:author> <R:Name>J.J. Johnson</R:Name> </R:author> </D:prop> <D:status>HTTP/1.1 200 OK</D:status> </D:propstat> <D:propstat> <D:prop><R:DingALing/><R:Random/></D:prop> <D:status>HTTP/1.1 403 Forbidden</D:status> <D:responsedescription> The user does not have access to the DingALing property. </D:responsedescription> </D:propstat> </D:response> <D:responsedescription> There has been an access violation error. </D:responsedescription> </D:multistatus> In this example, PROPFIND is executed on a non-collection resource http://www.example.com/file. The propfind XML element specifies the name of four properties whose values are being requested. In this case, only two properties were returned, since the principal issuing the request did not have sufficient access rights to see the third and fourth properties. #### 9.1.4. Example - Using 'propname' to Retrieve All Property Names >>Request PROPFIND /container/ HTTP/1.1 Host: www.example.com Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <propfind xmlns="DAV:"> <propname/> </propfind> >>Response HTTP/1.1 207 Multi-Status Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <multistatus xmlns="DAV:"> <response> <href>http://www.example.com/container/</href> <propstat> <prop xmlns:R="http://ns.example.com/boxschema/"> <R:bigbox/> <R:author/> <creationdate/> <displayname/> <resourcetype/> <supportedlock/> </prop> <status>HTTP/1.1 200 OK</status> </propstat> </response> <response> <href>http://www.example.com/container/front.html</href> <propstat> <prop xmlns:R="http://ns.example.com/boxschema/"> <R:bigbox/> <creationdate/> <displayname/> <getcontentlength/> <getcontenttype/> <getetag/> <getlastmodified/> <resourcetype/> <supportedlock/> </prop> <status>HTTP/1.1 200 OK</status> </propstat> </response> </multistatus> In this example, PROPFIND is invoked on the collection resource http://www.example.com/container/, with a propfind XML element containing the propname XML element, meaning the name of all properties should be returned. Since no Depth header is present, it assumes its default value of "infinity", meaning the name of the properties on the collection and all its descendants should be returned. Consistent with the previous example, resource http://www.example.com/container/ has six properties defined on it: bigbox and author in the "http://ns.example.com/boxschema/" namespace, and creationdate, displayname, resourcetype, and supportedlock in the "DAV:" namespace. The resource http://www.example.com/container/index.html, a member of the "container" collection, has nine properties defined on it, bigbox in the "http://ns.example.com/boxschema/" namespace and creationdate, displayname, getcontentlength, getcontenttype, getetag, getlastmodified, resourcetype, and supportedlock in the "DAV:" namespace. This example also demonstrates the use of XML namespace scoping and the default namespace. Since the "xmlns" attribute does not contain a prefix, the namespace applies by default to all enclosed elements. Hence, all elements that do not explicitly state the namespace to which they belong are members of the "DAV:" namespace. #### 9.1.5. Example - Using So-called 'allprop' Note that 'allprop', despite its name, which remains for backward- compatibility, does not return every property, but only dead properties and the live properties defined in this specification. >>Request PROPFIND /container/ HTTP/1.1 Host: www.example.com Depth: 1 Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:"> <D:allprop/> </D:propfind> >>Response HTTP/1.1 207 Multi-Status Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:multistatus xmlns:D="DAV:"> <D:response> <D:href>/container/</D:href> <D:propstat> <D:prop xmlns:R="http://ns.example.com/boxschema/"> <R:bigbox><R:BoxType>Box type A</R:BoxType></R:bigbox> <R:author><R:Name>Hadrian</R:Name></R:author> <D:creationdate>1997-12-01T17:42:21-08:00</D:creationdate> <D:displayname>Example collection</D:displayname> <D:resourcetype><D:collection/></D:resourcetype> <D:supportedlock> <D:lockentry> <D:lockscope><D:exclusive/></D:lockscope> <D:locktype><D:write/></D:locktype> </D:lockentry> <D:lockentry> <D:lockscope><D:shared/></D:lockscope> <D:locktype><D:write/></D:locktype> </D:lockentry> </D:supportedlock> </D:prop> <D:status>HTTP/1.1 200 OK</D:status> </D:propstat> </D:response> <D:response> <D:href>/container/front.html</D:href> <D:propstat> <D:prop xmlns:R="http://ns.example.com/boxschema/"> <R:bigbox><R:BoxType>Box type B</R:BoxType> </R:bigbox> <D:creationdate>1997-12-01T18:27:21-08:00</D:creationdate> <D:displayname>Example HTML resource</D:displayname> <D:getcontentlength>4525</D:getcontentlength> <D:getcontenttype>text/html</D:getcontenttype> <D:getetag>"zzyzx"</D:getetag> <D:getlastmodified >Mon, 12 Jan 1998 09:25:56 GMT</D:getlastmodified> <D:resourcetype/> <D:supportedlock> <D:lockentry> <D:lockscope><D:exclusive/></D:lockscope> <D:locktype><D:write/></D:locktype> </D:lockentry> <D:lockentry> <D:lockscope><D:shared/></D:lockscope> <D:locktype><D:write/></D:locktype> </D:lockentry> </D:supportedlock> </D:prop> <D:status>HTTP/1.1 200 OK</D:status> </D:propstat> </D:response> </D:multistatus> In this example, PROPFIND was invoked on the resource http://www.example.com/container/ with a Depth header of 1, meaning the request applies to the resource and its children, and a propfind XML element containing the allprop XML element, meaning the request should return the name and value of all the dead properties defined on the resources, plus the name and value of all the properties defined in this specification. This example illustrates the use of relative references in the 'href' elements of the response. The resource http://www.example.com/container/ has six properties defined on it: 'bigbox' and 'author in the "http://ns.example.com/boxschema/" namespace, DAV:creationdate, DAV: displayname, DAV:resourcetype, and DAV:supportedlock. The last four properties are WebDAV-specific, defined in [Section 15](#section-15). Since GET is not supported on this resource, the get\* properties (e.g., DAV:getcontentlength) are not defined on this resource. The WebDAV-specific properties assert that "container" was created on December 1, 1997, at 5:42:21PM, in a time zone 8 hours west of GMT (DAV:creationdate), has a name of "Example collection" (DAV: displayname), a collection resource type (DAV:resourcetype), and supports exclusive write and shared write locks (DAV:supportedlock). The resource http://www.example.com/container/front.html has nine properties defined on it: 'bigbox' in the "http://ns.example.com/boxschema/" namespace (another instance of the "bigbox" property type), DAV:creationdate, DAV: displayname, DAV:getcontentlength, DAV:getcontenttype, DAV:getetag, DAV:getlastmodified, DAV:resourcetype, and DAV:supportedlock. The DAV-specific properties assert that "front.html" was created on December 1, 1997, at 6:27:21PM, in a time zone 8 hours west of GMT (DAV:creationdate), has a name of "Example HTML resource" (DAV: displayname), a content length of 4525 bytes (DAV:getcontentlength), a MIME type of "text/html" (DAV:getcontenttype), an entity tag of "zzyzx" (DAV:getetag), was last modified on Monday, January 12, 1998, at 09:25:56 GMT (DAV:getlastmodified), has an empty resource type, meaning that it is not a collection (DAV:resourcetype), and supports both exclusive write and shared write locks (DAV:supportedlock). #### 9.1.6. Example - Using 'allprop' with 'include' >>Request PROPFIND /mycol/ HTTP/1.1 Host: www.example.com Depth: 1 Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:"> <D:allprop/> <D:include> <D:supported-live-property-set/> <D:supported-report-set/> </D:include> </D:propfind> In this example, PROPFIND is executed on the resource http://www.example.com/mycol/ and its internal member resources. The client requests the values of all live properties defined in this specification, plus all dead properties, plus two more live properties defined in [[RFC3253](https://datatracker.ietf.org/doc/html/rfc3253)]. The response is not shown. ### 9.2. PROPPATCH Method The PROPPATCH method processes instructions specified in the request body to set and/or remove properties defined on the resource identified by the Request-URI. All DAV-compliant resources MUST support the PROPPATCH method and MUST process instructions that are specified using the propertyupdate, set, and remove XML elements. Execution of the directives in this method is, of course, subject to access control constraints. DAV-compliant resources SHOULD support the setting of arbitrary dead properties. The request message body of a PROPPATCH method MUST contain the propertyupdate XML element. Servers MUST process PROPPATCH instructions in document order (an exception to the normal rule that ordering is irrelevant). Instructions MUST either all be executed or none executed. Thus, if any error occurs during processing, all executed instructions MUST be undone and a proper error result returned. Instruction processing details can be found in the definition of the set and remove instructions in Sections [14.23](#section-14.23) and [14.26](#section-14.26). If a server attempts to make any of the property changes in a PROPPATCH request (i.e., the request is not rejected for high-level errors before processing the body), the response MUST be a Multi- Status response as described in [Section 9.2.1](#section-9.2.1). This method is idempotent, but not safe (see [Section 9.1 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-9.1)). Responses to this method MUST NOT be cached. #### 9.2.1. Status Codes for Use in 'propstat' Element In PROPPATCH responses, information about individual properties is returned inside 'propstat' elements (see [Section 14.22](#section-14.22)), each containing an individual 'status' element containing information about the properties appearing in it. The list below summarizes the most common status codes used inside 'propstat'; however, clients should be prepared to handle other 2/3/4/5xx series status codes as well. 200 (OK) - The property set or change succeeded. Note that if this appears for one property, it appears for every property in the response, due to the atomicity of PROPPATCH. 403 (Forbidden) - The client, for reasons the server chooses not to specify, cannot alter one of the properties. 403 (Forbidden): The client has attempted to set a protected property, such as DAV:getetag. If returning this error, the server SHOULD use the precondition code 'cannot-modify-protected-property' inside the response body. 409 (Conflict) - The client has provided a value whose semantics are not appropriate for the property. 424 (Failed Dependency) - The property change could not be made because of another property change that failed. 507 (Insufficient Storage) - The server did not have sufficient space to record the property. #### 9.2.2. Example - PROPPATCH >>Request PROPPATCH /bar.html HTTP/1.1 Host: www.example.com Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:propertyupdate xmlns:D="DAV:" xmlns:Z="http://ns.example.com/standards/z39.50/"> <D:set> <D:prop> <Z:Authors> <Z:Author>Jim Whitehead</Z:Author> <Z:Author>Roy Fielding</Z:Author> </Z:Authors> </D:prop> </D:set> <D:remove> <D:prop><Z:Copyright-Owner/></D:prop> </D:remove> </D:propertyupdate> >>Response HTTP/1.1 207 Multi-Status Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:multistatus xmlns:D="DAV:" xmlns:Z="http://ns.example.com/standards/z39.50/"> <D:response> <D:href>http://www.example.com/bar.html</D:href> <D:propstat> <D:prop><Z:Authors/></D:prop> <D:status>HTTP/1.1 424 Failed Dependency</D:status> </D:propstat> <D:propstat> <D:prop><Z:Copyright-Owner/></D:prop> <D:status>HTTP/1.1 409 Conflict</D:status> </D:propstat> <D:responsedescription> Copyright Owner cannot be deleted or altered.</D:responsedescription> </D:response> </D:multistatus> In this example, the client requests the server to set the value of the "Authors" property in the "http://ns.example.com/standards/z39.50/" namespace, and to remove the property "Copyright-Owner" in the same namespace. Since the Copyright-Owner property could not be removed, no property modifications occur. The 424 (Failed Dependency) status code for the Authors property indicates this action would have succeeded if it were not for the conflict with removing the Copyright-Owner property. ### 9.3. MKCOL Method MKCOL creates a new collection resource at the location specified by the Request-URI. If the Request-URI is already mapped to a resource, then the MKCOL MUST fail. During MKCOL processing, a server MUST make the Request-URI an internal member of its parent collection, unless the Request-URI is "/". If no such ancestor exists, the method MUST fail. When the MKCOL operation creates a new collection resource, all ancestors MUST already exist, or the method MUST fail with a 409 (Conflict) status code. For example, if a request to create collection /a/b/c/d/ is made, and /a/b/c/ does not exist, the request must fail. When MKCOL is invoked without a request body, the newly created collection SHOULD have no members. A MKCOL request message may contain a message body. The precise behavior of a MKCOL request when the body is present is undefined, but limited to creating collections, members of a collection, bodies of members, and properties on the collections or members. If the server receives a MKCOL request entity type it does not support or understand, it MUST respond with a 415 (Unsupported Media Type) status code. If the server decides to reject the request based on the presence of an entity or the type of an entity, it should use the 415 (Unsupported Media Type) status code. This method is idempotent, but not safe (see [Section 9.1 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-9.1)). Responses to this method MUST NOT be cached. #### 9.3.1. MKCOL Status Codes In addition to the general status codes possible, the following status codes have specific applicability to MKCOL: 201 (Created) - The collection was created. 403 (Forbidden) - This indicates at least one of two conditions: 1) the server does not allow the creation of collections at the given location in its URL namespace, or 2) the parent collection of the Request-URI exists but cannot accept members. 405 (Method Not Allowed) - MKCOL can only be executed on an unmapped URL. 409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate collections have been created. The server MUST NOT create those intermediate collections automatically. 415 (Unsupported Media Type) - The server does not support the request body type (although bodies are legal on MKCOL requests, since this specification doesn't define any, the server is likely not to support any given body type). 507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the resource after the execution of this method. #### 9.3.2. Example - MKCOL This example creates a collection called /webdisc/xfiles/ on the server www.example.com. >>Request MKCOL /webdisc/xfiles/ HTTP/1.1 Host: www.example.com >>Response HTTP/1.1 201 Created ### 9.4. GET, HEAD for Collections The semantics of GET are unchanged when applied to a collection, since GET is defined as, "retrieve whatever information (in the form of an entity) is identified by the Request-URI" [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]. GET, when applied to a collection, may return the contents of an "index.html" resource, a human-readable view of the contents of the collection, or something else altogether. Hence, it is possible that the result of a GET on a collection will bear no correlation to the membership of the collection. Similarly, since the definition of HEAD is a GET without a response message body, the semantics of HEAD are unmodified when applied to collection resources. ### 9.5. POST for Collections Since by definition the actual function performed by POST is determined by the server and often depends on the particular resource, the behavior of POST when applied to collections cannot be meaningfully modified because it is largely undefined. Thus, the semantics of POST are unmodified when applied to a collection. ### 9.6. DELETE Requirements DELETE is defined in [[RFC2616], Section 9.7](https://datatracker.ietf.org/doc/html/rfc2616#section-9.7), to "delete the resource identified by the Request-URI". However, WebDAV changes some DELETE handling requirements. A server processing a successful DELETE request: MUST destroy locks rooted on the deleted resource MUST remove the mapping from the Request-URI to any resource. Thus, after a successful DELETE operation (and in the absence of other actions), a subsequent GET/HEAD/PROPFIND request to the target Request-URI MUST return 404 (Not Found). #### 9.6.1. DELETE for Collections The DELETE method on a collection MUST act as if a "Depth: infinity" header was used on it. A client MUST NOT submit a Depth header with a DELETE on a collection with any value but infinity. DELETE instructs that the collection specified in the Request-URI and all resources identified by its internal member URLs are to be deleted. If any resource identified by a member URL cannot be deleted, then all of the member's ancestors MUST NOT be deleted, so as to maintain URL namespace consistency. Any headers included with DELETE MUST be applied in processing every resource to be deleted. When the DELETE method has completed processing, it MUST result in a consistent URL namespace. If an error occurs deleting a member resource (a resource other than the resource identified in the Request-URI), then the response can be a 207 (Multi-Status). Multi-Status is used here to indicate which internal resources could NOT be deleted, including an error code, which should help the client understand which resources caused the failure. For example, the Multi-Status body could include a response with status 423 (Locked) if an internal resource was locked. The server MAY return a 4xx status response, rather than a 207, if the request failed completely. 424 (Failed Dependency) status codes SHOULD NOT be in the 207 (Multi- Status) response for DELETE. They can be safely left out because the client will know that the ancestors of a resource could not be deleted when the client receives an error for the ancestor's progeny. Additionally, 204 (No Content) errors SHOULD NOT be returned in the 207 (Multi-Status). The reason for this prohibition is that 204 (No Content) is the default success code. #### 9.6.2. Example - DELETE >>Request DELETE /container/ HTTP/1.1 Host: www.example.com >>Response HTTP/1.1 207 Multi-Status Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <d:multistatus xmlns:d="DAV:"> <d:response> <d:href>http://www.example.com/container/resource3</d:href> <d:status>HTTP/1.1 423 Locked</d:status> <d:error><d:lock-token-submitted/></d:error> </d:response> </d:multistatus> In this example, the attempt to delete http://www.example.com/container/resource3 failed because it is locked, and no lock token was submitted with the request. Consequently, the attempt to delete http://www.example.com/container/ also failed. Thus, the client knows that the attempt to delete http://www.example.com/container/ must have also failed since the parent cannot be deleted unless its child has also been deleted. Even though a Depth header has not been included, a depth of infinity is assumed because the method is on a collection. ### 9.7. PUT Requirements #### 9.7.1. PUT for Non-Collection Resources A PUT performed on an existing resource replaces the GET response entity of the resource. Properties defined on the resource may be recomputed during PUT processing but are not otherwise affected. For example, if a server recognizes the content type of the request body, it may be able to automatically extract information that could be profitably exposed as properties. A PUT that would result in the creation of a resource without an appropriately scoped parent collection MUST fail with a 409 (Conflict). A PUT request allows a client to indicate what media type an entity body has, and whether it should change if overwritten. Thus, a client SHOULD provide a Content-Type for a new resource if any is known. If the client does not provide a Content-Type for a new resource, the server MAY create a resource with no Content-Type assigned, or it MAY attempt to assign a Content-Type. Note that although a recipient ought generally to treat metadata supplied with an HTTP request as authoritative, in practice there's no guarantee that a server will accept client-supplied metadata (e.g., any request header beginning with "Content-"). Many servers do not allow configuring the Content-Type on a per-resource basis in the first place. Thus, clients can't always rely on the ability to directly influence the content type by including a Content-Type request header. #### 9.7.2. PUT for Collections This specification does not define the behavior of the PUT method for existing collections. A PUT request to an existing collection MAY be treated as an error (405 Method Not Allowed). The MKCOL method is defined to create collections. ### 9.8. COPY Method The COPY method creates a duplicate of the source resource identified by the Request-URI, in the destination resource identified by the URI in the Destination header. The Destination header MUST be present. The exact behavior of the COPY method depends on the type of the source resource. All WebDAV-compliant resources MUST support the COPY method. However, support for the COPY method does not guarantee the ability to copy a resource. For example, separate programs may control resources on the same server. As a result, it may not be possible to copy a resource to a location that appears to be on the same server. This method is idempotent, but not safe (see [Section 9.1 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-9.1)). Responses to this method MUST NOT be cached. #### 9.8.1. COPY for Non-collection Resources When the source resource is not a collection, the result of the COPY method is the creation of a new resource at the destination whose state and behavior match that of the source resource as closely as possible. Since the environment at the destination may be different than at the source due to factors outside the scope of control of the server, such as the absence of resources required for correct operation, it may not be possible to completely duplicate the behavior of the resource at the destination. Subsequent alterations to the destination resource will not modify the source resource. Subsequent alterations to the source resource will not modify the destination resource. #### 9.8.2. COPY for Properties After a successful COPY invocation, all dead properties on the source resource SHOULD be duplicated on the destination resource. Live properties described in this document SHOULD be duplicated as identically behaving live properties at the destination resource, but not necessarily with the same values. Servers SHOULD NOT convert live properties into dead properties on the destination resource, because clients may then draw incorrect conclusions about the state or functionality of a resource. Note that some live properties are defined such that the absence of the property has a specific meaning (e.g., a flag with one meaning if present, and the opposite if absent), and in these cases, a successful COPY might result in the property being reported as "Not Found" in subsequent requests. When the destination is an unmapped URL, a COPY operation creates a new resource much like a PUT operation does. Live properties that are related to resource creation (such as DAV:creationdate) should have their values set accordingly. #### 9.8.3. COPY for Collections The COPY method on a collection without a Depth header MUST act as if a Depth header with value "infinity" was included. A client may submit a Depth header on a COPY on a collection with a value of "0" or "infinity". Servers MUST support the "0" and "infinity" Depth header behaviors on WebDAV-compliant resources. An infinite-depth COPY instructs that the collection resource identified by the Request-URI is to be copied to the location identified by the URI in the Destination header, and all its internal member resources are to be copied to a location relative to it, recursively through all levels of the collection hierarchy. Note that an infinite-depth COPY of /A/ into /A/B/ could lead to infinite recursion if not handled correctly. A COPY of "Depth: 0" only instructs that the collection and its properties, but not resources identified by its internal member URLs, are to be copied. Any headers included with a COPY MUST be applied in processing every resource to be copied with the exception of the Destination header. The Destination header only specifies the destination URI for the Request-URI. When applied to members of the collection identified by the Request-URI, the value of Destination is to be modified to reflect the current location in the hierarchy. So, if the Request- URI is /a/ with Host header value http://example.com/ and the Destination is http://example.com/b/, then when http://example.com/a/c/d is processed, it must use a Destination of http://example.com/b/c/d. When the COPY method has completed processing, it MUST have created a consistent URL namespace at the destination (see [Section 5.1](#section-5.1) for the definition of namespace consistency). However, if an error occurs while copying an internal collection, the server MUST NOT copy any resources identified by members of this collection (i.e., the server must skip this subtree), as this would create an inconsistent namespace. After detecting an error, the COPY operation SHOULD try to finish as much of the original copy operation as possible (i.e., the server should still attempt to copy other subtrees and their members that are not descendants of an error-causing collection). So, for example, if an infinite-depth copy operation is performed on collection /a/, which contains collections /a/b/ and /a/c/, and an error occurs copying /a/b/, an attempt should still be made to copy /a/c/. Similarly, after encountering an error copying a non- collection resource as part of an infinite-depth copy, the server SHOULD try to finish as much of the original copy operation as possible. If an error in executing the COPY method occurs with a resource other than the resource identified in the Request-URI, then the response MUST be a 207 (Multi-Status), and the URL of the resource causing the failure MUST appear with the specific error. The 424 (Failed Dependency) status code SHOULD NOT be returned in the 207 (Multi-Status) response from a COPY method. These responses can be safely omitted because the client will know that the progeny of a resource could not be copied when the client receives an error for the parent. Additionally, 201 (Created)/204 (No Content) status codes SHOULD NOT be returned as values in 207 (Multi-Status) responses from COPY methods. They, too, can be safely omitted because they are the default success codes. #### 9.8.4. COPY and Overwriting Destination Resources If a COPY request has an Overwrite header with a value of "F", and a resource exists at the Destination URL, the server MUST fail the request. When a server executes a COPY request and overwrites a destination resource, the exact behavior MAY depend on many factors, including WebDAV extension capabilities (see particularly [[RFC3253](https://datatracker.ietf.org/doc/html/rfc3253)]). For example, when an ordinary resource is overwritten, the server could delete the target resource before doing the copy, or could do an in- place overwrite to preserve live properties. When a collection is overwritten, the membership of the destination collection after the successful COPY request MUST be the same membership as the source collection immediately before the COPY. Thus, merging the membership of the source and destination collections together in the destination is not a compliant behavior. In general, if clients require the state of the destination URL to be wiped out prior to a COPY (e.g., to force live properties to be reset), then the client could send a DELETE to the destination before the COPY request to ensure this reset. #### 9.8.5. Status Codes In addition to the general status codes possible, the following status codes have specific applicability to COPY: 201 (Created) - The source resource was successfully copied. The COPY operation resulted in the creation of a new resource. 204 (No Content) - The source resource was successfully copied to a preexisting destination resource. 207 (Multi-Status) - Multiple resources were to be affected by the COPY, but errors on some of them prevented the operation from taking place. Specific error messages, together with the most appropriate of the source and destination URLs, appear in the body of the multi- status response. For example, if a destination resource was locked and could not be overwritten, then the destination resource URL appears with the 423 (Locked) status. 403 (Forbidden) - The operation is forbidden. A special case for COPY could be that the source and destination resources are the same resource. 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created. The server MUST NOT create those intermediate collections automatically. 412 (Precondition Failed) - A precondition header check failed, e.g., the Overwrite header is "F" and the destination URL is already mapped to a resource. 423 (Locked) - The destination resource, or resource within the destination collection, was locked. This response SHOULD contain the 'lock-token-submitted' precondition element. 502 (Bad Gateway) - This may occur when the destination is on another server, repository, or URL namespace. Either the source namespace does not support copying to the destination namespace, or the destination namespace refuses to accept the resource. The client may wish to try GET/PUT and PROPFIND/PROPPATCH instead. 507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the execution of this method. #### 9.8.6. Example - COPY with Overwrite This example shows resource http://www.example.com/~fielding/index.html being copied to the location http://www.example.com/users/f/fielding/index.html. The 204 (No Content) status code indicates that the existing resource at the destination was overwritten. >>Request COPY /~fielding/index.html HTTP/1.1 Host: www.example.com Destination: http://www.example.com/users/f/fielding/index.html >>Response HTTP/1.1 204 No Content #### 9.8.7. Example - COPY with No Overwrite The following example shows the same copy operation being performed, but with the Overwrite header set to "F." A response of 412 (Precondition Failed) is returned because the destination URL is already mapped to a resource. >>Request COPY /~fielding/index.html HTTP/1.1 Host: www.example.com Destination: http://www.example.com/users/f/fielding/index.html Overwrite: F >>Response HTTP/1.1 412 Precondition Failed #### 9.8.8. Example - COPY of a Collection >>Request COPY /container/ HTTP/1.1 Host: www.example.com Destination: http://www.example.com/othercontainer/ Depth: infinity >>Response HTTP/1.1 207 Multi-Status Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <d:multistatus xmlns:d="DAV:"> <d:response> <d:href>http://www.example.com/othercontainer/R2/</d:href> <d:status>HTTP/1.1 423 Locked</d:status> <d:error><d:lock-token-submitted/></d:error> </d:response> </d:multistatus> The Depth header is unnecessary as the default behavior of COPY on a collection is to act as if a "Depth: infinity" header had been submitted. In this example, most of the resources, along with the collection, were copied successfully. However, the collection R2 failed because the destination R2 is locked. Because there was an error copying R2, none of R2's members were copied. However, no errors were listed for those members due to the error minimization rules. ### 9.9. MOVE Method The MOVE operation on a non-collection resource is the logical equivalent of a copy (COPY), followed by consistency maintenance processing, followed by a delete of the source, where all three actions are performed in a single operation. The consistency maintenance step allows the server to perform updates caused by the move, such as updating all URLs, other than the Request-URI that identifies the source resource, to point to the new destination resource. The Destination header MUST be present on all MOVE methods and MUST follow all COPY requirements for the COPY part of the MOVE method. All WebDAV-compliant resources MUST support the MOVE method. Support for the MOVE method does not guarantee the ability to move a resource to a particular destination. For example, separate programs may actually control different sets of resources on the same server. Therefore, it may not be possible to move a resource within a namespace that appears to belong to the same server. If a resource exists at the destination, the destination resource will be deleted as a side-effect of the MOVE operation, subject to the restrictions of the Overwrite header. This method is idempotent, but not safe (see [Section 9.1 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-9.1)). Responses to this method MUST NOT be cached. #### 9.9.1. MOVE for Properties Live properties described in this document SHOULD be moved along with the resource, such that the resource has identically behaving live properties at the destination resource, but not necessarily with the same values. Note that some live properties are defined such that the absence of the property has a specific meaning (e.g., a flag with one meaning if present, and the opposite if absent), and in these cases, a successful MOVE might result in the property being reported as "Not Found" in subsequent requests. If the live properties will not work the same way at the destination, the server MAY fail the request. MOVE is frequently used by clients to rename a file without changing its parent collection, so it's not appropriate to reset all live properties that are set at resource creation. For example, the DAV: creationdate property value SHOULD remain the same after a MOVE. Dead properties MUST be moved along with the resource. #### 9.9.2. MOVE for Collections A MOVE with "Depth: infinity" instructs that the collection identified by the Request-URI be moved to the address specified in the Destination header, and all resources identified by its internal member URLs are to be moved to locations relative to it, recursively through all levels of the collection hierarchy. The MOVE method on a collection MUST act as if a "Depth: infinity" header was used on it. A client MUST NOT submit a Depth header on a MOVE on a collection with any value but "infinity". Any headers included with MOVE MUST be applied in processing every resource to be moved with the exception of the Destination header. The behavior of the Destination header is the same as given for COPY on collections. When the MOVE method has completed processing, it MUST have created a consistent URL namespace at both the source and destination (see [Section 5.1](#section-5.1) for the definition of namespace consistency). However, if an error occurs while moving an internal collection, the server MUST NOT move any resources identified by members of the failed collection (i.e., the server must skip the error-causing subtree), as this would create an inconsistent namespace. In this case, after detecting the error, the move operation SHOULD try to finish as much of the original move as possible (i.e., the server should still attempt to move other subtrees and the resources identified by their members that are not descendants of an error-causing collection). So, for example, if an infinite-depth move is performed on collection /a/, which contains collections /a/b/ and /a/c/, and an error occurs moving /a/b/, an attempt should still be made to try moving /a/c/. Similarly, after encountering an error moving a non-collection resource as part of an infinite-depth move, the server SHOULD try to finish as much of the original move operation as possible. If an error occurs with a resource other than the resource identified in the Request-URI, then the response MUST be a 207 (Multi-Status), and the errored resource's URL MUST appear with the specific error. The 424 (Failed Dependency) status code SHOULD NOT be returned in the 207 (Multi-Status) response from a MOVE method. These errors can be safely omitted because the client will know that the progeny of a resource could not be moved when the client receives an error for the parent. Additionally, 201 (Created)/204 (No Content) responses SHOULD NOT be returned as values in 207 (Multi-Status) responses from a MOVE. These responses can be safely omitted because they are the default success codes. #### 9.9.3. MOVE and the Overwrite Header If a resource exists at the destination and the Overwrite header is "T", then prior to performing the move, the server MUST perform a DELETE with "Depth: infinity" on the destination resource. If the Overwrite header is set to "F", then the operation will fail. #### 9.9.4. Status Codes In addition to the general status codes possible, the following status codes have specific applicability to MOVE: 201 (Created) - The source resource was successfully moved, and a new URL mapping was created at the destination. 204 (No Content) - The source resource was successfully moved to a URL that was already mapped. 207 (Multi-Status) - Multiple resources were to be affected by the MOVE, but errors on some of them prevented the operation from taking place. Specific error messages, together with the most appropriate of the source and destination URLs, appear in the body of the multi- status response. For example, if a source resource was locked and could not be moved, then the source resource URL appears with the 423 (Locked) status. 403 (Forbidden) - Among many possible reasons for forbidding a MOVE operation, this status code is recommended for use when the source and destination resources are the same. 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created. The server MUST NOT create those intermediate collections automatically. Or, the server was unable to preserve the behavior of the live properties and still move the resource to the destination (see 'preserved-live-properties' postcondition). 412 (Precondition Failed) - A condition header failed. Specific to MOVE, this could mean that the Overwrite header is "F" and the destination URL is already mapped to a resource. 423 (Locked) - The source or the destination resource, the source or destination resource parent, or some resource within the source or destination collection, was locked. This response SHOULD contain the 'lock-token-submitted' precondition element. 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource. This could also occur when the destination is on another sub-section of the same server namespace. #### 9.9.5. Example - MOVE of a Non-Collection This example shows resource http://www.example.com/~fielding/index.html being moved to the location http://www.example.com/users/f/fielding/index.html. The contents of the destination resource would have been overwritten if the destination URL was already mapped to a resource. In this case, since there was nothing at the destination resource, the response code is 201 (Created). >>Request MOVE /~fielding/index.html HTTP/1.1 Host: www.example.com Destination: http://www.example/users/f/fielding/index.html >>Response HTTP/1.1 201 Created Location: http://www.example.com/users/f/fielding/index.html #### 9.9.6. Example - MOVE of a Collection >>Request MOVE /container/ HTTP/1.1 Host: www.example.com Destination: http://www.example.com/othercontainer/ Overwrite: F If: (<urn:uuid:fe184f2e-6eec-41d0-c765-01adc56e6bb4>) (<urn:uuid:e454f3f3-acdc-452a-56c7-00a5c91e4b77>) >>Response HTTP/1.1 207 Multi-Status Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <d:multistatus xmlns:d='DAV:'> <d:response> <d:href>http://www.example.com/othercontainer/C2/</d:href> <d:status>HTTP/1.1 423 Locked</d:status> <d:error><d:lock-token-submitted/></d:error> </d:response> </d:multistatus> In this example, the client has submitted a number of lock tokens with the request. A lock token will need to be submitted for every resource, both source and destination, anywhere in the scope of the method, that is locked. In this case, the proper lock token was not submitted for the destination http://www.example.com/othercontainer/C2/. This means that the resource /container/C2/ could not be moved. Because there was an error moving /container/C2/, none of /container/C2's members were moved. However, no errors were listed for those members due to the error minimization rules. User agent authentication has previously occurred via a mechanism outside the scope of the HTTP protocol, in an underlying transport layer. ### 9.10. LOCK Method The following sections describe the LOCK method, which is used to take out a lock of any access type and to refresh an existing lock. These sections on the LOCK method describe only those semantics that are specific to the LOCK method and are independent of the access type of the lock being requested. Any resource that supports the LOCK method MUST, at minimum, support the XML request and response formats defined herein. This method is neither idempotent nor safe (see [Section 9.1 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-9.1)). Responses to this method MUST NOT be cached. #### 9.10.1. Creating a Lock on an Existing Resource A LOCK request to an existing resource will create a lock on the resource identified by the Request-URI, provided the resource is not already locked with a conflicting lock. The resource identified in the Request-URI becomes the root of the lock. LOCK method requests to create a new lock MUST have an XML request body. The server MUST preserve the information provided by the client in the 'owner' element in the LOCK request. The LOCK request MAY have a Timeout header. When a new lock is created, the LOCK response: o MUST contain a body with the value of the DAV:lockdiscovery property in a prop XML element. This MUST contain the full information about the lock just granted, while information about other (shared) locks is OPTIONAL. o MUST include the Lock-Token response header with the token associated with the new lock. #### 9.10.2. Refreshing Locks A lock is refreshed by sending a LOCK request to the URL of a resource within the scope of the lock. This request MUST NOT have a body and it MUST specify which lock to refresh by using the 'If' header with a single lock token (only one lock may be refreshed at a time). The request MAY contain a Timeout header, which a server MAY accept to change the duration remaining on the lock to the new value. A server MUST ignore the Depth header on a LOCK refresh. If the resource has other (shared) locks, those locks are unaffected by a lock refresh. Additionally, those locks do not prevent the named lock from being refreshed. The Lock-Token header is not returned in the response for a successful refresh LOCK request, but the LOCK response body MUST contain the new value for the DAV:lockdiscovery property. #### 9.10.3. Depth and Locking The Depth header may be used with the LOCK method. Values other than 0 or infinity MUST NOT be used with the Depth header on a LOCK method. All resources that support the LOCK method MUST support the Depth header. A Depth header of value 0 means to just lock the resource specified by the Request-URI. If the Depth header is set to infinity, then the resource specified in the Request-URI along with all its members, all the way down the hierarchy, are to be locked. A successful result MUST return a single lock token. Similarly, if an UNLOCK is successfully executed on this token, all associated resources are unlocked. Hence, partial success is not an option for LOCK or UNLOCK. Either the entire hierarchy is locked or no resources are locked. If the lock cannot be granted to all resources, the server MUST return a Multi-Status response with a 'response' element for at least one resource that prevented the lock from being granted, along with a suitable status code for that failure (e.g., 403 (Forbidden) or 423 (Locked)). Additionally, if the resource causing the failure was not the resource requested, then the server SHOULD include a 'response' element for the Request-URI as well, with a 'status' element containing 424 Failed Dependency. If no Depth header is submitted on a LOCK request, then the request MUST act as if a "Depth:infinity" had been submitted. #### 9.10.4. Locking Unmapped URLs A successful LOCK method MUST result in the creation of an empty resource that is locked (and that is not a collection) when a resource did not previously exist at that URL. Later on, the lock may go away but the empty resource remains. Empty resources MUST then appear in PROPFIND responses including that URL in the response scope. A server MUST respond successfully to a GET request to an empty resource, either by using a 204 No Content response, or by using 200 OK with a Content-Length header indicating zero length #### 9.10.5. Lock Compatibility Table The table below describes the behavior that occurs when a lock request is made on a resource. +--------------------------+----------------+-------------------+ | Current State | Shared Lock OK | Exclusive Lock OK | +--------------------------+----------------+-------------------+ | None | True | True | | Shared Lock | True | False | | Exclusive Lock | False | False\* | +--------------------------+----------------+-------------------+ Legend: True = lock may be granted. False = lock MUST NOT be granted. \*=It is illegal for a principal to request the same lock twice. The current lock state of a resource is given in the leftmost column, and lock requests are listed in the first row. The intersection of a row and column gives the result of a lock request. For example, if a shared lock is held on a resource, and an exclusive lock is requested, the table entry is "false", indicating that the lock must not be granted. #### 9.10.6. LOCK Responses In addition to the general status codes possible, the following status codes have specific applicability to LOCK: 200 (OK) - The LOCK request succeeded and the value of the DAV: lockdiscovery property is included in the response body. 201 (Created) - The LOCK request was to an unmapped URL, the request succeeded and resulted in the creation of a new resource, and the value of the DAV:lockdiscovery property is included in the response body. 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created. The server MUST NOT create those intermediate collections automatically. 423 (Locked), potentially with 'no-conflicting-lock' precondition code - There is already a lock on the resource that is not compatible with the requested lock (see lock compatibility table above). 412 (Precondition Failed), with 'lock-token-matches-request-uri' precondition code - The LOCK request was made with an If header, indicating that the client wishes to refresh the given lock. However, the Request-URI did not fall within the scope of the lock identified by the token. The lock may have a scope that does not include the Request-URI, or the lock could have disappeared, or the token may be invalid. #### 9.10.7. Example - Simple Lock Request >>Request LOCK /workspace/webdav/proposal.doc HTTP/1.1 Host: example.com Timeout: Infinite, Second-4100000000 Content-Type: application/xml; charset="utf-8" Content-Length: xxxx Authorization: Digest username="ejw", realm="[email protected]", nonce="...", uri="/workspace/webdav/proposal.doc", response="...", opaque="..." <?xml version="1.0" encoding="utf-8" ?> <D:lockinfo xmlns:D='DAV:'> <D:lockscope><D:exclusive/></D:lockscope> <D:locktype><D:write/></D:locktype> <D:owner> <D:href>http://example.org/~ejw/contact.html</D:href> </D:owner> </D:lockinfo> >>Response HTTP/1.1 200 OK Lock-Token: <urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4> Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:prop xmlns:D="DAV:"> <D:lockdiscovery> <D:activelock> <D:locktype><D:write/></D:locktype> <D:lockscope><D:exclusive/></D:lockscope> <D:depth>infinity</D:depth> <D:owner> <D:href>http://example.org/~ejw/contact.html</D:href> </D:owner> <D:timeout>Second-604800</D:timeout> <D:locktoken> <D:href >urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4</D:href> </D:locktoken> <D:lockroot> <D:href >http://example.com/workspace/webdav/proposal.doc</D:href> </D:lockroot> </D:activelock> </D:lockdiscovery> </D:prop> This example shows the successful creation of an exclusive write lock on resource http://example.com/workspace/webdav/proposal.doc. The resource http://example.org/~ejw/contact.html contains contact information for the creator of the lock. The server has an activity- based timeout policy in place on this resource, which causes the lock to automatically be removed after 1 week (604800 seconds). Note that the nonce, response, and opaque fields have not been calculated in the Authorization request header. #### 9.10.8. Example - Refreshing a Write Lock >>Request LOCK /workspace/webdav/proposal.doc HTTP/1.1 Host: example.com Timeout: Infinite, Second-4100000000 If: (<urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4>) Authorization: Digest username="ejw", realm="[email protected]", nonce="...", uri="/workspace/webdav/proposal.doc", response="...", opaque="..." >>Response HTTP/1.1 200 OK Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:prop xmlns:D="DAV:"> <D:lockdiscovery> <D:activelock> <D:locktype><D:write/></D:locktype> <D:lockscope><D:exclusive/></D:lockscope> <D:depth>infinity</D:depth> <D:owner> <D:href>http://example.org/~ejw/contact.html</D:href> </D:owner> <D:timeout>Second-604800</D:timeout> <D:locktoken> <D:href >urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4</D:href> </D:locktoken> <D:lockroot> <D:href >http://example.com/workspace/webdav/proposal.doc</D:href> </D:lockroot> </D:activelock> </D:lockdiscovery> </D:prop> This request would refresh the lock, attempting to reset the timeout to the new value specified in the timeout header. Notice that the client asked for an infinite time out but the server choose to ignore the request. In this example, the nonce, response, and opaque fields have not been calculated in the Authorization request header. #### 9.10.9. Example - Multi-Resource Lock Request >>Request LOCK /webdav/ HTTP/1.1 Host: example.com Timeout: Infinite, Second-4100000000 Depth: infinity Content-Type: application/xml; charset="utf-8" Content-Length: xxxx Authorization: Digest username="ejw", realm="[email protected]", nonce="...", uri="/workspace/webdav/proposal.doc", response="...", opaque="..." <?xml version="1.0" encoding="utf-8" ?> <D:lockinfo xmlns:D="DAV:"> <D:locktype><D:write/></D:locktype> <D:lockscope><D:exclusive/></D:lockscope> <D:owner> <D:href>http://example.org/~ejw/contact.html</D:href> </D:owner> </D:lockinfo> >>Response HTTP/1.1 207 Multi-Status Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:multistatus xmlns:D="DAV:"> <D:response> <D:href>http://example.com/webdav/secret</D:href> <D:status>HTTP/1.1 403 Forbidden</D:status> </D:response> <D:response> <D:href>http://example.com/webdav/</D:href> <D:status>HTTP/1.1 424 Failed Dependency</D:status> </D:response> </D:multistatus> This example shows a request for an exclusive write lock on a collection and all its children. In this request, the client has specified that it desires an infinite-length lock, if available, otherwise a timeout of 4.1 billion seconds, if available. The request entity body contains the contact information for the principal taking out the lock -- in this case, a Web page URL. The error is a 403 (Forbidden) response on the resource http://example.com/webdav/secret. Because this resource could not be locked, none of the resources were locked. Note also that the a 'response' element for the Request-URI itself has been included as required. In this example, the nonce, response, and opaque fields have not been calculated in the Authorization request header. ### 9.11. UNLOCK Method The UNLOCK method removes the lock identified by the lock token in the Lock-Token request header. The Request-URI MUST identify a resource within the scope of the lock. Note that use of the Lock-Token header to provide the lock token is not consistent with other state-changing methods, which all require an If header with the lock token. Thus, the If header is not needed to provide the lock token. Naturally, when the If header is present, it has its normal meaning as a conditional header. For a successful response to this method, the server MUST delete the lock entirely. If all resources that have been locked under the submitted lock token cannot be unlocked, then the UNLOCK request MUST fail. A successful response to an UNLOCK method does not mean that the resource is necessarily unlocked. It means that the specific lock corresponding to the specified token no longer exists. Any DAV-compliant resource that supports the LOCK method MUST support the UNLOCK method. This method is idempotent, but not safe (see [Section 9.1 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-9.1)). Responses to this method MUST NOT be cached. #### 9.11.1. Status Codes In addition to the general status codes possible, the following status codes have specific applicability to UNLOCK: 204 (No Content) - Normal success response (rather than 200 OK, since 200 OK would imply a response body, and an UNLOCK success response does not normally contain a body). 400 (Bad Request) - No lock token was provided. 403 (Forbidden) - The currently authenticated principal does not have permission to remove the lock. 409 (Conflict), with 'lock-token-matches-request-uri' precondition - The resource was not locked, or the request was made to a Request-URI that was not within the scope of the lock. #### 9.11.2. Example - UNLOCK >>Request UNLOCK /workspace/webdav/info.doc HTTP/1.1 Host: example.com Lock-Token: <urn:uuid:a515cfa4-5da4-22e1-f5b5-00a0451e6bf7> Authorization: Digest username="ejw" realm="[email protected]", nonce="...", uri="/workspace/webdav/proposal.doc", response="...", opaque="..." >>Response HTTP/1.1 204 No Content In this example, the lock identified by the lock token "urn:uuid:a515cfa4-5da4-22e1-f5b5-00a0451e6bf7" is successfully removed from the resource http://example.com/workspace/webdav/info.doc. If this lock included more than just one resource, the lock is removed from all resources included in the lock. In this example, the nonce, response, and opaque fields have not been calculated in the Authorization request header. 10. HTTP Headers for Distributed Authoring ------------------------------------------ All DAV headers follow the same basic formatting rules as HTTP headers. This includes rules like line continuation and how to combine (or separate) multiple instances of the same header using commas. WebDAV adds two new conditional headers to the set defined in HTTP: the If and Overwrite headers. ### 10.1. DAV Header DAV = "DAV" ":" #( compliance-class ) compliance-class = ( "1" | "2" | "3" | extend ) extend = Coded-URL | token ; token is defined in [RFC 2616, Section 2.2](https://datatracker.ietf.org/doc/html/rfc2616#section-2.2) Coded-URL = "<" absolute-URI ">" ; No linear whitespace (LWS) allowed in Coded-URL ; absolute-URI defined in [RFC 3986, Section 4.3](https://datatracker.ietf.org/doc/html/rfc3986#section-4.3) This general-header appearing in the response indicates that the resource supports the DAV schema and protocol as specified. All DAV- compliant resources MUST return the DAV header with compliance-class "1" on all OPTIONS responses. In cases where WebDAV is only supported in part of the server namespace, an OPTIONS request to non- WebDAV resources (including "/") SHOULD NOT advertise WebDAV support. The value is a comma-separated list of all compliance class identifiers that the resource supports. Class identifiers may be Coded-URLs or tokens (as defined by [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]). Identifiers can appear in any order. Identifiers that are standardized through the IETF RFC process are tokens, but other identifiers SHOULD be Coded- URLs to encourage uniqueness. A resource must show class 1 compliance if it shows class 2 or 3 compliance. In general, support for one compliance class does not entail support for any other, and in particular, support for compliance class 3 does not require support for compliance class 2. Please refer to [Section 18](#section-18) for more details on compliance classes defined in this specification. Note that many WebDAV servers do not advertise WebDAV support in response to "OPTIONS \*". As a request header, this header allows the client to advertise compliance with named features when the server needs that information. Clients SHOULD NOT send this header unless a standards track specification requires it. Any extension that makes use of this as a request header will need to carefully consider caching implications. ### 10.2. Depth Header Depth = "Depth" ":" ("0" | "1" | "infinity") The Depth request header is used with methods executed on resources that could potentially have internal members to indicate whether the method is to be applied only to the resource ("Depth: 0"), to the resource and its internal members only ("Depth: 1"), or the resource and all its members ("Depth: infinity"). The Depth header is only supported if a method's definition explicitly provides for such support. The following rules are the default behavior for any method that supports the Depth header. A method may override these defaults by defining different behavior in its definition. Methods that support the Depth header may choose not to support all of the header's values and may define, on a case-by-case basis, the behavior of the method if a Depth header is not present. For example, the MOVE method only supports "Depth: infinity", and if a Depth header is not present, it will act as if a "Depth: infinity" header had been applied. Clients MUST NOT rely upon methods executing on members of their hierarchies in any particular order or on the execution being atomic unless the particular method explicitly provides such guarantees. Upon execution, a method with a Depth header will perform as much of its assigned task as possible and then return a response specifying what it was able to accomplish and what it failed to do. So, for example, an attempt to COPY a hierarchy may result in some of the members being copied and some not. By default, the Depth header does not interact with other headers. That is, each header on a request with a Depth header MUST be applied only to the Request-URI if it applies to any resource, unless specific Depth behavior is defined for that header. If a source or destination resource within the scope of the Depth header is locked in such a way as to prevent the successful execution of the method, then the lock token for that resource MUST be submitted with the request in the If request header. The Depth header only specifies the behavior of the method with regards to internal members. If a resource does not have internal members, then the Depth header MUST be ignored. ### 10.3. Destination Header The Destination request header specifies the URI that identifies a destination resource for methods such as COPY and MOVE, which take two URIs as parameters. Destination = "Destination" ":" Simple-ref If the Destination value is an absolute-URI ([Section 4.3 of [RFC3986]](https://datatracker.ietf.org/doc/html/rfc3986#section-4.3)), it may name a different server (or different port or scheme). If the source server cannot attempt a copy to the remote server, it MUST fail the request. Note that copying and moving resources to remote servers is not fully defined in this specification (e.g., specific error conditions). If the Destination value is too long or otherwise unacceptable, the server SHOULD return 400 (Bad Request), ideally with helpful information in an error body. ### 10.4. If Header The If request header is intended to have similar functionality to the If-Match header defined in [Section 14.24 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-14.24). However, the If header handles any state token as well as ETags. A typical example of a state token is a lock token, and lock tokens are the only state tokens defined in this specification. #### 10.4.1. Purpose The If header has two distinct purposes: o The first purpose is to make a request conditional by supplying a series of state lists with conditions that match tokens and ETags to a specific resource. If this header is evaluated and all state lists fail, then the request MUST fail with a 412 (Precondition Failed) status. On the other hand, the request can succeed only if one of the described state lists succeeds. The success criteria for state lists and matching functions are defined in Sections [10.4.3](#section-10.4.3) and [10.4.4](#section-10.4.4). o Additionally, the mere fact that a state token appears in an If header means that it has been "submitted" with the request. In general, this is used to indicate that the client has knowledge of that state token. The semantics for submitting a state token depend on its type (for lock tokens, please refer to [Section 6](#section-6)). Note that these two purposes need to be treated distinctly: a state token counts as being submitted independently of whether the server actually has evaluated the state list it appears in, and also independently of whether or not the condition it expressed was found to be true. #### 10.4.2. Syntax If = "If" ":" ( 1\*No-tag-list | 1\*Tagged-list ) No-tag-list = List Tagged-list = Resource-Tag 1\*List List = "(" 1\*Condition ")" Condition = ["Not"] (State-token | "[" entity-tag "]") ; entity-tag: see [Section 3.11 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-3.11) ; No LWS allowed between "[", entity-tag and "]" State-token = Coded-URL Resource-Tag = "<" Simple-ref ">" ; Simple-ref: see [Section 8.3](#section-8.3) ; No LWS allowed in Resource-Tag The syntax distinguishes between untagged lists ("No-tag-list") and tagged lists ("Tagged-list"). Untagged lists apply to the resource identified by the Request-URI, while tagged lists apply to the resource identified by the preceding Resource-Tag. A Resource-Tag applies to all subsequent Lists, up to the next Resource-Tag. Note that the two list types cannot be mixed within an If header. This is not a functional restriction because the No-tag-list syntax is just a shorthand notation for a Tagged-list production with a Resource-Tag referring to the Request-URI. Each List consists of one or more Conditions. Each Condition is defined in terms of an entity-tag or state-token, potentially negated by the prefix "Not". Note that the If header syntax does not allow multiple instances of If headers in a single request. However, the HTTP header syntax allows extending single header values across multiple lines, by inserting a line break followed by whitespace (see [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)], [Section](#section-4.2) [4.2](#section-4.2)). #### 10.4.3. List Evaluation A Condition that consists of a single entity-tag or state-token evaluates to true if the resource matches the described state (where the individual matching functions are defined below in [Section 10.4.4](#section-10.4.4)). Prefixing it with "Not" reverses the result of the evaluation (thus, the "Not" applies only to the subsequent entity-tag or state-token). Each List production describes a series of conditions. The whole list evaluates to true if and only if each condition evaluates to true (that is, the list represents a logical conjunction of Conditions). Each No-tag-list and Tagged-list production may contain one or more Lists. They evaluate to true if and only if any of the contained lists evaluates to true (that is, if there's more than one List, that List sequence represents a logical disjunction of the Lists). Finally, the whole If header evaluates to true if and only if at least one of the No-tag-list or Tagged-list productions evaluates to true. If the header evaluates to false, the server MUST reject the request with a 412 (Precondition Failed) status. Otherwise, execution of the request can proceed as if the header wasn't present. #### 10.4.4. Matching State Tokens and ETags When performing If header processing, the definition of a matching state token or entity tag is as follows: Identifying a resource: The resource is identified by the URI along with the token, in tagged list production, or by the Request-URI in untagged list production. Matching entity tag: Where the entity tag matches an entity tag associated with the identified resource. Servers MUST use either the weak or the strong comparison function defined in [Section 13.3.3 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-13.3.3). Matching state token: Where there is an exact match between the state token in the If header and any state token on the identified resource. A lock state token is considered to match if the resource is anywhere in the scope of the lock. Handling unmapped URLs: For both ETags and state tokens, treat as if the URL identified a resource that exists but does not have the specified state. #### 10.4.5. If Header and Non-DAV-Aware Proxies Non-DAV-aware proxies will not honor the If header, since they will not understand the If header, and HTTP requires non-understood headers to be ignored. When communicating with HTTP/1.1 proxies, the client MUST use the "Cache-Control: no-cache" request header so as to prevent the proxy from improperly trying to service the request from its cache. When dealing with HTTP/1.0 proxies, the "Pragma: no- cache" request header MUST be used for the same reason. Because in general clients may not be able to reliably detect non- DAV-aware intermediates, they are advised to always prevent caching using the request directives mentioned above. #### 10.4.6. Example - No-tag Production If: (<urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2> ["I am an ETag"]) (["I am another ETag"]) The previous header would require that the resource identified in the Request-URI be locked with the specified lock token and be in the state identified by the "I am an ETag" ETag or in the state identified by the second ETag "I am another ETag". To put the matter more plainly one can think of the previous If header as expressing the condition below: ( is-locked-with(urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2) AND matches-etag("I am an ETag") ) OR ( matches-etag("I am another ETag") ) #### 10.4.7. Example - Using "Not" with No-tag Production If: (Not <urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2> <urn:uuid:58f202ac-22cf-11d1-b12d-002035b29092>) This If header requires that the resource must not be locked with a lock having the lock token urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2 and must be locked by a lock with the lock token urn:uuid:58f202ac-22cf-11d1-b12d-002035b29092. #### 10.4.8. Example - Causing a Condition to Always Evaluate to True There may be cases where a client wishes to submit state tokens, but doesn't want the request to fail just because the state token isn't current anymore. One simple way to do this is to include a Condition that is known to always evaluate to true, such as in: If: (<urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2>) (Not <DAV:no-lock>) "DAV:no-lock" is known to never represent a current lock token. Lock tokens are assigned by the server, following the uniqueness requirements described in [Section 6.5](#section-6.5), therefore cannot use the "DAV:" scheme. Thus, by applying "Not" to a state token that is known not to be current, the Condition always evaluates to true. Consequently, the whole If header will always evaluate to true, and the lock token urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2 will be submitted in any case. #### 10.4.9. Example - Tagged List If Header in COPY >>Request COPY /resource1 HTTP/1.1 Host: www.example.com Destination: /resource2 If: </resource1> (<urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2> [W/"A weak ETag"]) (["strong ETag"]) In this example, http://www.example.com/resource1 is being copied to http://www.example.com/resource2. When the method is first applied to http://www.example.com/resource1, resource1 must be in the state specified by "(<urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2> [W/"A weak ETag"]) (["strong ETag"])". That is, either it must be locked with a lock token of "urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2" and have a weak entity tag W/"A weak ETag" or it must have a strong entity tag "strong ETag". #### 10.4.10. Example - Matching Lock Tokens with Collection Locks DELETE /specs/rfc2518.txt HTTP/1.1 Host: www.example.com If: <http://www.example.com/specs/> (<urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2>) For this example, the lock token must be compared to the identified resource, which is the 'specs' collection identified by the URL in the tagged list production. If the 'specs' collection is not locked by a lock with the specified lock token, the request MUST fail. Otherwise, this request could succeed, because the If header evaluates to true, and because the lock token for the lock affecting the affected resource has been submitted. #### 10.4.11. Example - Matching ETags on Unmapped URLs Consider a collection "/specs" that does not contain the member "/specs/rfc2518.doc". In this case, the If header If: </specs/rfc2518.doc> (["4217"]) will evaluate to false (the URI isn't mapped, thus the resource identified by the URI doesn't have an entity matching the ETag "4217"). On the other hand, an If header of If: </specs/rfc2518.doc> (Not ["4217"]) will consequently evaluate to true. Note that, as defined above in [Section 10.4.4](#section-10.4.4), the same considerations apply to matching state tokens. ### 10.5. Lock-Token Header Lock-Token = "Lock-Token" ":" Coded-URL The Lock-Token request header is used with the UNLOCK method to identify the lock to be removed. The lock token in the Lock-Token request header MUST identify a lock that contains the resource identified by Request-URI as a member. The Lock-Token response header is used with the LOCK method to indicate the lock token created as a result of a successful LOCK request to create a new lock. ### 10.6. Overwrite Header Overwrite = "Overwrite" ":" ("T" | "F") The Overwrite request header specifies whether the server should overwrite a resource mapped to the destination URL during a COPY or MOVE. A value of "F" states that the server must not perform the COPY or MOVE operation if the destination URL does map to a resource. If the overwrite header is not included in a COPY or MOVE request, then the resource MUST treat the request as if it has an overwrite header of value "T". While the Overwrite header appears to duplicate the functionality of using an "If-Match: \*" header (see [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]), If-Match applies only to the Request-URI, and not to the Destination of a COPY or MOVE. If a COPY or MOVE is not performed due to the value of the Overwrite header, the method MUST fail with a 412 (Precondition Failed) status code. The server MUST do authorization checks before checking this or any conditional header. All DAV-compliant resources MUST support the Overwrite header. ### 10.7. Timeout Request Header TimeOut = "Timeout" ":" 1#TimeType TimeType = ("Second-" DAVTimeOutVal | "Infinite") ; No LWS allowed within TimeType DAVTimeOutVal = 1\*DIGIT Clients MAY include Timeout request headers in their LOCK requests. However, the server is not required to honor or even consider these requests. Clients MUST NOT submit a Timeout request header with any method other than a LOCK method. The "Second" TimeType specifies the number of seconds that will elapse between granting of the lock at the server, and the automatic removal of the lock. The timeout value for TimeType "Second" MUST NOT be greater than 2^32-1. See [Section 6.6](#section-6.6) for a description of lock timeout behavior. 11. Status Code Extensions to HTTP/1.1 -------------------------------------- The following status codes are added to those defined in HTTP/1.1 [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]. ### 11.1. 207 Multi-Status The 207 (Multi-Status) status code provides status for multiple independent operations (see [Section 13](#section-13) for more information). ### 11.2. 422 Unprocessable Entity The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions. ### 11.3. 423 Locked The 423 (Locked) status code means the source or destination resource of a method is locked. This response SHOULD contain an appropriate precondition or postcondition code, such as 'lock-token-submitted' or 'no-conflicting-lock'. ### 11.4. 424 Failed Dependency The 424 (Failed Dependency) status code means that the method could not be performed on the resource because the requested action depended on another action and that action failed. For example, if a command in a PROPPATCH method fails, then, at minimum, the rest of the commands will also fail with 424 (Failed Dependency). ### 11.5. 507 Insufficient Storage The 507 (Insufficient Storage) status code means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. This condition is considered to be temporary. If the request that received this status code was the result of a user action, the request MUST NOT be repeated until it is requested by a separate user action. 12. Use of HTTP Status Codes ---------------------------- These HTTP codes are not redefined, but their use is somewhat extended by WebDAV methods and requirements. In general, many HTTP status codes can be used in response to any request, not just in cases described in this document. Note also that WebDAV servers are known to use 300-level redirect responses (and early interoperability tests found clients unprepared to see those responses). A 300-level response MUST NOT be used when the server has created a new resource in response to the request. ### 12.1. 412 Precondition Failed Any request can contain a conditional header defined in HTTP (If- Match, If-Modified-Since, etc.) or the "If" or "Overwrite" conditional headers defined in this specification. If the server evaluates a conditional header, and if that condition fails to hold, then this error code MUST be returned. On the other hand, if the client did not include a conditional header in the request, then the server MUST NOT use this status code. ### 12.2. 414 Request-URI Too Long This status code is used in HTTP 1.1 only for Request-URIs, not URIs in other locations. 13. Multi-Status Response ------------------------- A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate. The default Multi-Status response body is a text/xml or application/xml HTTP entity with a 'multistatus' root element. Further elements contain 200, 300, 400, and 500 series status codes generated during the method invocation. 100 series status codes SHOULD NOT be recorded in a 'response' XML element. Although '207' is used as the overall response status code, the recipient needs to consult the contents of the multistatus response body for further information about the success or failure of the method execution. The response MAY be used in success, partial success and also in failure situations. The 'multistatus' root element holds zero or more 'response' elements in any order, each with information about an individual resource. Each 'response' element MUST have an 'href' element to identify the resource. A Multi-Status response uses one out of two distinct formats for representing the status: 1. A 'status' element as child of the 'response' element indicates the status of the message execution for the identified resource as a whole (for instance, see [Section 9.6.2](#section-9.6.2)). Some method definitions provide information about specific status codes clients should be prepared to see in a response. However, clients MUST be able to handle other status codes, using the generic rules defined in [Section 10 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-10). 2. For PROPFIND and PROPPATCH, the format has been extended using the 'propstat' element instead of 'status', providing information about individual properties of a resource. This format is specific to PROPFIND and PROPPATCH, and is described in detail in Sections [9.1](#section-9.1) and [9.2](#section-9.2). ### 13.1. Response Headers HTTP defines the Location header to indicate a preferred URL for the resource that was addressed in the Request-URI (e.g., in response to successful PUT requests or in redirect responses). However, use of this header creates ambiguity when there are URLs in the body of the response, as with Multi-Status. Thus, use of the Location header with the Multi-Status response is intentionally undefined. ### 13.2. Handling Redirected Child Resources Redirect responses (300-303, 305, and 307) defined in HTTP 1.1 normally take a Location header to indicate the new URI for the single resource redirected from the Request-URI. Multi-Status responses contain many resource addresses, but the original definition in [[RFC2518](https://datatracker.ietf.org/doc/html/rfc2518)] did not have any place for the server to provide the new URI for redirected resources. This specification does define a 'location' element for this information (see [Section 14.9](#section-14.9)). Servers MUST use this new element with redirect responses in Multi-Status. Clients encountering redirected resources in Multi-Status MUST NOT rely on the 'location' element being present with a new URI. If the element is not present, the client MAY reissue the request to the individual redirected resource, because the response to that request can be redirected with a Location header containing the new URI. ### 13.3. Internal Status Codes Sections [9.2.1](#section-9.2.1), [9.1.2](#section-9.1.2), [9.6.1](#section-9.6.1), [9.8.3](#section-9.8.3), and [9.9.2](#section-9.9.2) define various status codes used in Multi-Status responses. This specification does not define the meaning of other status codes that could appear in these responses. 14. XML Element Definitions --------------------------- In this section, the final line of each section gives the element type declaration using the format defined in [[REC-XML](#ref-REC-XML)]. The "Value" field, where present, specifies further restrictions on the allowable contents of the XML element using BNF (i.e., to further restrict the values of a PCDATA element). Note that all of the elements defined here may be extended according to the rules defined in [Section 17](#section-17). All elements defined here are in the "DAV:" namespace. ### 14.1. activelock XML Element Name: activelock Purpose: Describes a lock on a resource. <!ELEMENT activelock (lockscope, locktype, depth, owner?, timeout?, locktoken?, lockroot)> ### 14.2. allprop XML Element Name: allprop Purpose: Specifies that all names and values of dead properties and the live properties defined by this document existing on the resource are to be returned. <!ELEMENT allprop EMPTY > ### 14.3. collection XML Element Name: collection Purpose: Identifies the associated resource as a collection. The DAV:resourcetype property of a collection resource MUST contain this element. It is normally empty but extensions may add sub- elements. <!ELEMENT collection EMPTY > ### 14.4. depth XML Element Name: depth Purpose: Used for representing depth values in XML content (e.g., in lock information). Value: "0" | "1" | "infinity" <!ELEMENT depth (#PCDATA) > ### 14.5. error XML Element Name: error Purpose: Error responses, particularly 403 Forbidden and 409 Conflict, sometimes need more information to indicate what went wrong. In these cases, servers MAY return an XML response body with a document element of 'error', containing child elements identifying particular condition codes. Description: Contains at least one XML element, and MUST NOT contain text or mixed content. Any element that is a child of the 'error' element is considered to be a precondition or postcondition code. Unrecognized elements MUST be ignored. <!ELEMENT error ANY > ### 14.6. exclusive XML Element Name: exclusive Purpose: Specifies an exclusive lock. <!ELEMENT exclusive EMPTY > ### 14.7. href XML Element Name: href Purpose: MUST contain a URI or a relative reference. Description: There may be limits on the value of 'href' depending on the context of its use. Refer to the specification text where 'href' is used to see what limitations apply in each case. Value: Simple-ref <!ELEMENT href (#PCDATA)> ### 14.8. include XML Element Name: include Purpose: Any child element represents the name of a property to be included in the PROPFIND response. All elements inside an 'include' XML element MUST define properties related to the resource, although possible property names are in no way limited to those property names defined in this document or other standards. This element MUST NOT contain text or mixed content. <!ELEMENT include ANY > ### 14.9. location XML Element Name: location Purpose: HTTP defines the "Location" header (see [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)], [Section](#section-14.30) [14.30](#section-14.30)) for use with some status codes (such as 201 and the 300 series codes). When these codes are used inside a 'multistatus' element, the 'location' element can be used to provide the accompanying Location header value. Description: Contains a single href element with the same value that would be used in a Location header. <!ELEMENT location (href)> ### 14.10. lockentry XML Element Name: lockentry Purpose: Defines the types of locks that can be used with the resource. <!ELEMENT lockentry (lockscope, locktype) > ### 14.11. lockinfo XML Element Name: lockinfo Purpose: The 'lockinfo' XML element is used with a LOCK method to specify the type of lock the client wishes to have created. <!ELEMENT lockinfo (lockscope, locktype, owner?) > ### 14.12. lockroot XML Element Name: lockroot Purpose: Contains the root URL of the lock, which is the URL through which the resource was addressed in the LOCK request. Description: The href element contains the root of the lock. The server SHOULD include this in all DAV:lockdiscovery property values and the response to LOCK requests. <!ELEMENT lockroot (href) > ### 14.13. lockscope XML Element Name: lockscope Purpose: Specifies whether a lock is an exclusive lock, or a shared lock. <!ELEMENT lockscope (exclusive | shared) > ### 14.14. locktoken XML Element Name: locktoken Purpose: The lock token associated with a lock. Description: The href contains a single lock token URI, which refers to the lock. <!ELEMENT locktoken (href) > ### 14.15. locktype XML Element Name: locktype Purpose: Specifies the access type of a lock. At present, this specification only defines one lock type, the write lock. <!ELEMENT locktype (write) > ### 14.16. multistatus XML Element Name: multistatus Purpose: Contains multiple response messages. Description: The 'responsedescription' element at the top level is used to provide a general message describing the overarching nature of the response. If this value is available, an application may use it instead of presenting the individual response descriptions contained within the responses. <!ELEMENT multistatus (response\*, responsedescription?) > ### 14.17. owner XML Element Name: owner Purpose: Holds client-supplied information about the creator of a lock. Description: Allows a client to provide information sufficient for either directly contacting a principal (such as a telephone number or Email URI), or for discovering the principal (such as the URL of a homepage) who created a lock. The value provided MUST be treated as a dead property in terms of XML Information Item preservation. The server MUST NOT alter the value unless the owner value provided by the client is empty. For a certain amount of interoperability between different client implementations, if clients have URI-formatted contact information for the lock creator suitable for user display, then clients SHOULD put those URIs in 'href' child elements of the 'owner' element. Extensibility: MAY be extended with child elements, mixed content, text content or attributes. <!ELEMENT owner ANY > ### 14.18. prop XML Element Name: prop Purpose: Contains properties related to a resource. Description: A generic container for properties defined on resources. All elements inside a 'prop' XML element MUST define properties related to the resource, although possible property names are in no way limited to those property names defined in this document or other standards. This element MUST NOT contain text or mixed content. <!ELEMENT prop ANY > ### 14.19. propertyupdate XML Element Name: propertyupdate Purpose: Contains a request to alter the properties on a resource. Description: This XML element is a container for the information required to modify the properties on the resource. <!ELEMENT propertyupdate (remove | set)+ > ### 14.20. propfind XML Element Name: propfind Purpose: Specifies the properties to be returned from a PROPFIND method. Four special elements are specified for use with 'propfind': 'prop', 'allprop', 'include', and 'propname'. If 'prop' is used inside 'propfind', it MUST NOT contain property values. <!ELEMENT propfind ( propname | (allprop, include?) | prop ) > ### 14.21. propname XML Element Name: propname Purpose: Specifies that only a list of property names on the resource is to be returned. <!ELEMENT propname EMPTY > ### 14.22. propstat XML Element Name: propstat Purpose: Groups together a prop and status element that is associated with a particular 'href' element. Description: The propstat XML element MUST contain one prop XML element and one status XML element. The contents of the prop XML element MUST only list the names of properties to which the result in the status element applies. The optional precondition/ postcondition element and 'responsedescription' text also apply to the properties named in 'prop'. <!ELEMENT propstat (prop, status, error?, responsedescription?) > ### 14.23. remove XML Element Name: remove Purpose: Lists the properties to be removed from a resource. Description: Remove instructs that the properties specified in prop should be removed. Specifying the removal of a property that does not exist is not an error. All the XML elements in a 'prop' XML element inside of a 'remove' XML element MUST be empty, as only the names of properties to be removed are required. <!ELEMENT remove (prop) > ### 14.24. response XML Element Name: response Purpose: Holds a single response describing the effect of a method on resource and/or its properties. Description: The 'href' element contains an HTTP URL pointing to a WebDAV resource when used in the 'response' container. A particular 'href' value MUST NOT appear more than once as the child of a 'response' XML element under a 'multistatus' XML element. This requirement is necessary in order to keep processing costs for a response to linear time. Essentially, this prevents having to search in order to group together all the responses by 'href'. There are, however, no requirements regarding ordering based on 'href' values. The optional precondition/postcondition element and 'responsedescription' text can provide additional information about this resource relative to the request or result. <!ELEMENT response (href, ((href\*, status)|(propstat+)), error?, responsedescription? , location?) > ### 14.25. responsedescription XML Element Name: responsedescription Purpose: Contains information about a status response within a Multi-Status. Description: Provides information suitable to be presented to a user. <!ELEMENT responsedescription (#PCDATA) > ### 14.26. set XML Element Name: set Purpose: Lists the property values to be set for a resource. Description: The 'set' element MUST contain only a 'prop' element. The elements contained by the 'prop' element inside the 'set' element MUST specify the name and value of properties that are set on the resource identified by Request-URI. If a property already exists, then its value is replaced. Language tagging information appearing in the scope of the 'prop' element (in the "xml:lang" attribute, if present) MUST be persistently stored along with the property, and MUST be subsequently retrievable using PROPFIND. <!ELEMENT set (prop) > ### 14.27. shared XML Element Name: shared Purpose: Specifies a shared lock. <!ELEMENT shared EMPTY > ### 14.28. status XML Element Name: status Purpose: Holds a single HTTP status-line. Value: status-line (defined in [Section 6.1 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-6.1)) <!ELEMENT status (#PCDATA) > ### 14.29. timeout XML Element Name: timeout Purpose: The number of seconds remaining before a lock expires. Value: TimeType (defined in [Section 10.7](#section-10.7)) <!ELEMENT timeout (#PCDATA) > ### 14.30. write XML Element Name: write Purpose: Specifies a write lock. <!ELEMENT write EMPTY > 15. DAV Properties ------------------ For DAV properties, the name of the property is also the same as the name of the XML element that contains its value. In the section below, the final line of each section gives the element type declaration using the format defined in [[REC-XML](#ref-REC-XML)]. The "Value" field, where present, specifies further restrictions on the allowable contents of the XML element using BNF (i.e., to further restrict the values of a PCDATA element). A protected property is one that cannot be changed with a PROPPATCH request. There may be other requests that would result in a change to a protected property (as when a LOCK request affects the value of DAV:lockdiscovery). Note that a given property could be protected on one type of resource, but not protected on another type of resource. A computed property is one with a value defined in terms of a computation (based on the content and other properties of that resource, or even of some other resource). A computed property is always a protected property. COPY and MOVE behavior refers to local COPY and MOVE operations. For properties defined based on HTTP GET response headers (DAV:get\*), the header value could include LWS as defined in [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)], [Section](#section-4.2) [4.2](#section-4.2). Server implementors SHOULD strip LWS from these values before using as WebDAV property values. ### 15.1. creationdate Property Name: creationdate Purpose: Records the time and date the resource was created. Value: date-time (defined in [[RFC3339](https://datatracker.ietf.org/doc/html/rfc3339)], see the ABNF in [Section](#section-5.6) [5.6](#section-5.6).) Protected: MAY be protected. Some servers allow DAV:creationdate to be changed to reflect the time the document was created if that is more meaningful to the user (rather than the time it was uploaded). Thus, clients SHOULD NOT use this property in synchronization logic (use DAV:getetag instead). COPY/MOVE behavior: This property value SHOULD be kept during a MOVE operation, but is normally re-initialized when a resource is created with a COPY. It should not be set in a COPY. Description: The DAV:creationdate property SHOULD be defined on all DAV compliant resources. If present, it contains a timestamp of the moment when the resource was created. Servers that are incapable of persistently recording the creation date SHOULD instead leave it undefined (i.e. report "Not Found"). <!ELEMENT creationdate (#PCDATA) > ### 15.2. displayname Property Name: displayname Purpose: Provides a name for the resource that is suitable for presentation to a user. Value: Any text. Protected: SHOULD NOT be protected. Note that servers implementing [[RFC2518](https://datatracker.ietf.org/doc/html/rfc2518)] might have made this a protected property as this is a new requirement. COPY/MOVE behavior: This property value SHOULD be preserved in COPY and MOVE operations. Description: Contains a description of the resource that is suitable for presentation to a user. This property is defined on the resource, and hence SHOULD have the same value independent of the Request-URI used to retrieve it (thus, computing this property based on the Request-URI is deprecated). While generic clients might display the property value to end users, client UI designers must understand that the method for identifying resources is still the URL. Changes to DAV:displayname do not issue moves or copies to the server, but simply change a piece of meta-data on the individual resource. Two resources can have the same DAV: displayname value even within the same collection. <!ELEMENT displayname (#PCDATA) > ### 15.3. getcontentlanguage Property Name: getcontentlanguage Purpose: Contains the Content-Language header value (from [Section](https://datatracker.ietf.org/doc/html/rfc2616#section-14.12) [14.12 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-14.12)) as it would be returned by a GET without accept headers. Value: language-tag (language-tag is defined in [Section 3.10 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-3.10)) Protected: SHOULD NOT be protected, so that clients can reset the language. Note that servers implementing [[RFC2518](https://datatracker.ietf.org/doc/html/rfc2518)] might have made this a protected property as this is a new requirement. COPY/MOVE behavior: This property value SHOULD be preserved in COPY and MOVE operations. Description: The DAV:getcontentlanguage property MUST be defined on any DAV-compliant resource that returns the Content-Language header on a GET. <!ELEMENT getcontentlanguage (#PCDATA) > ### 15.4. getcontentlength Property Name: getcontentlength Purpose: Contains the Content-Length header returned by a GET without accept headers. Value: See [Section 14.13 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-14.13). Protected: This property is computed, therefore protected. Description: The DAV:getcontentlength property MUST be defined on any DAV-compliant resource that returns the Content-Length header in response to a GET. COPY/MOVE behavior: This property value is dependent on the size of the destination resource, not the value of the property on the source resource. <!ELEMENT getcontentlength (#PCDATA) > ### 15.5. getcontenttype Property Name: getcontenttype Purpose: Contains the Content-Type header value (from [Section 14.17 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-14.17)) as it would be returned by a GET without accept headers. Value: media-type (defined in [Section 3.7 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-3.7)) Protected: Potentially protected if the server prefers to assign content types on its own (see also discussion in [Section 9.7.1](#section-9.7.1)). COPY/MOVE behavior: This property value SHOULD be preserved in COPY and MOVE operations. Description: This property MUST be defined on any DAV-compliant resource that returns the Content-Type header in response to a GET. <!ELEMENT getcontenttype (#PCDATA) > ### 15.6. getetag Property Name: getetag Purpose: Contains the ETag header value (from [Section 14.19 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-14.19)) as it would be returned by a GET without accept headers. Value: entity-tag (defined in [Section 3.11 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-3.11)) Protected: MUST be protected because this value is created and controlled by the server. COPY/MOVE behavior: This property value is dependent on the final state of the destination resource, not the value of the property on the source resource. Also note the considerations in [Section 8.8](#section-8.8). Description: The getetag property MUST be defined on any DAV- compliant resource that returns the Etag header. Refer to [Section](https://datatracker.ietf.org/doc/html/rfc2616#section-3.11) [3.11 of RFC 2616](https://datatracker.ietf.org/doc/html/rfc2616#section-3.11) for a complete definition of the semantics of an ETag, and to [Section 8.6](#section-8.6) for a discussion of ETags in WebDAV. <!ELEMENT getetag (#PCDATA) > ### 15.7. getlastmodified Property Name: getlastmodified Purpose: Contains the Last-Modified header value (from [Section](https://datatracker.ietf.org/doc/html/rfc2616#section-14.29) [14.29 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-14.29)) as it would be returned by a GET method without accept headers. Value: [rfc1123](https://datatracker.ietf.org/doc/html/rfc1123)-date (defined in [Section 3.3.1 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-3.3.1)) Protected: SHOULD be protected because some clients may rely on the value for appropriate caching behavior, or on the value of the Last-Modified header to which this property is linked. COPY/MOVE behavior: This property value is dependent on the last modified date of the destination resource, not the value of the property on the source resource. Note that some server implementations use the file system date modified value for the DAV:getlastmodified value, and this can be preserved in a MOVE even when the HTTP Last-Modified value SHOULD change. Note that since [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)] requires clients to use ETags where provided, a server implementing ETags can count on clients using a much better mechanism than modification dates for offline synchronization or cache control. Also note the considerations in [Section 8.8](#section-8.8). Description: The last-modified date on a resource SHOULD only reflect changes in the body (the GET responses) of the resource. A change in a property only SHOULD NOT cause the last-modified date to change, because clients MAY rely on the last-modified date to know when to overwrite the existing body. The DAV: getlastmodified property MUST be defined on any DAV-compliant resource that returns the Last-Modified header in response to a GET. <!ELEMENT getlastmodified (#PCDATA) > ### 15.8. lockdiscovery Property Name: lockdiscovery Purpose: Describes the active locks on a resource Protected: MUST be protected. Clients change the list of locks through LOCK and UNLOCK, not through PROPPATCH. COPY/MOVE behavior: The value of this property depends on the lock state of the destination, not on the locks of the source resource. Recall that locks are not moved in a MOVE operation. Description: Returns a listing of who has a lock, what type of lock he has, the timeout type and the time remaining on the timeout, and the associated lock token. Owner information MAY be omitted if it is considered sensitive. If there are no locks, but the server supports locks, the property will be present but contain zero 'activelock' elements. If there are one or more locks, an 'activelock' element appears for each lock on the resource. This property is NOT lockable with respect to write locks ([Section 7](#section-7)). <!ELEMENT lockdiscovery (activelock)\* > #### 15.8.1. Example - Retrieving DAV:lockdiscovery >>Request PROPFIND /container/ HTTP/1.1 Host: www.example.com Content-Length: xxxx Content-Type: application/xml; charset="utf-8" <?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D='DAV:'> <D:prop><D:lockdiscovery/></D:prop> </D:propfind> >>Response HTTP/1.1 207 Multi-Status Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:multistatus xmlns:D='DAV:'> <D:response> <D:href>http://www.example.com/container/</D:href> <D:propstat> <D:prop> <D:lockdiscovery> <D:activelock> <D:locktype><D:write/></D:locktype> <D:lockscope><D:exclusive/></D:lockscope> <D:depth>0</D:depth> <D:owner>Jane Smith</D:owner> <D:timeout>Infinite</D:timeout> <D:locktoken> <D:href >urn:uuid:f81de2ad-7f3d-a1b2-4f3c-00a0c91a9d76</D:href> </D:locktoken> <D:lockroot> <D:href>http://www.example.com/container/</D:href> </D:lockroot> </D:activelock> </D:lockdiscovery> </D:prop> <D:status>HTTP/1.1 200 OK</D:status> </D:propstat> </D:response> </D:multistatus> This resource has a single exclusive write lock on it, with an infinite timeout. ### 15.9. resourcetype Property Name: resourcetype Purpose: Specifies the nature of the resource. Protected: SHOULD be protected. Resource type is generally decided through the operation creating the resource (MKCOL vs PUT), not by PROPPATCH. COPY/MOVE behavior: Generally a COPY/MOVE of a resource results in the same type of resource at the destination. Description: MUST be defined on all DAV-compliant resources. Each child element identifies a specific type the resource belongs to, such as 'collection', which is the only resource type defined by this specification (see [Section 14.3](#section-14.3)). If the element contains the 'collection' child element plus additional unrecognized elements, it should generally be treated as a collection. If the element contains no recognized child elements, it should be treated as a non-collection resource. The default value is empty. This element MUST NOT contain text or mixed content. Any custom child element is considered to be an identifier for a resource type. Example: (fictional example to show extensibility) <x:resourcetype xmlns:x="DAV:"> <x:collection/> <f:search-results xmlns:f="http://www.example.com/ns"/> </x:resourcetype> ### 15.10. supportedlock Property Name: supportedlock Purpose: To provide a listing of the lock capabilities supported by the resource. Protected: MUST be protected. Servers, not clients, determine what lock mechanisms are supported. COPY/MOVE behavior: This property value is dependent on the kind of locks supported at the destination, not on the value of the property at the source resource. Servers attempting to COPY to a destination should not attempt to set this property at the destination. Description: Returns a listing of the combinations of scope and access types that may be specified in a lock request on the resource. Note that the actual contents are themselves controlled by access controls, so a server is not required to provide information the client is not authorized to see. This property is NOT lockable with respect to write locks ([Section 7](#section-7)). <!ELEMENT supportedlock (lockentry)\* > #### 15.10.1. Example - Retrieving DAV:supportedlock >>Request PROPFIND /container/ HTTP/1.1 Host: www.example.com Content-Length: xxxx Content-Type: application/xml; charset="utf-8" <?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:"> <D:prop><D:supportedlock/></D:prop> </D:propfind> >>Response HTTP/1.1 207 Multi-Status Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:multistatus xmlns:D="DAV:"> <D:response> <D:href>http://www.example.com/container/</D:href> <D:propstat> <D:prop> <D:supportedlock> <D:lockentry> <D:lockscope><D:exclusive/></D:lockscope> <D:locktype><D:write/></D:locktype> </D:lockentry> <D:lockentry> <D:lockscope><D:shared/></D:lockscope> <D:locktype><D:write/></D:locktype> </D:lockentry> </D:supportedlock> </D:prop> <D:status>HTTP/1.1 200 OK</D:status> </D:propstat> </D:response> </D:multistatus> 16. Precondition/Postcondition XML Elements ------------------------------------------- As introduced in [Section 8.7](#section-8.7), extra information on error conditions can be included in the body of many status responses. This section makes requirements on the use of the error body mechanism and introduces a number of precondition and postcondition codes. A "precondition" of a method describes the state of the server that must be true for that method to be performed. A "postcondition" of a method describes the state of the server that must be true after that method has been completed. Each precondition and postcondition has a unique XML element associated with it. In a 207 Multi-Status response, the XML element MUST appear inside an 'error' element in the appropriate 'propstat or 'response' element depending on whether the condition applies to one or more properties or to the resource as a whole. In all other error responses where this specification's 'error' body is used, the precondition/postcondition XML element MUST be returned as the child of a top-level 'error' element in the response body, unless otherwise negotiated by the request, along with an appropriate response status. The most common response status codes are 403 (Forbidden) if the request should not be repeated because it will always fail, and 409 (Conflict) if it is expected that the user might be able to resolve the conflict and resubmit the request. The 'error' element MAY contain child elements with specific error information and MAY be extended with any custom child elements. This mechanism does not take the place of using a correct numeric status code as defined here or in HTTP, because the client must always be able to take a reasonable course of action based only on the numeric code. However, it does remove the need to define new numeric codes. The new machine-readable codes used for this purpose are XML elements classified as preconditions and postconditions, so naturally, any group defining a new condition code can use their own namespace. As always, the "DAV:" namespace is reserved for use by IETF-chartered WebDAV working groups. A server supporting this specification SHOULD use the XML error whenever a precondition or postcondition defined in this document is violated. For error conditions not specified in this document, the server MAY simply choose an appropriate numeric status and leave the response body blank. However, a server MAY instead use a custom condition code and other supporting text, because even when clients do not automatically recognize condition codes, they can be quite useful in interoperability testing and debugging. Example - Response with precondition code >>Response HTTP/1.1 423 Locked Content-Type: application/xml; charset="utf-8" Content-Length: xxxx <?xml version="1.0" encoding="utf-8" ?> <D:error xmlns:D="DAV:"> <D:lock-token-submitted> <D:href>/workspace/webdav/</D:href> </D:lock-token-submitted> </D:error> In this example, a client unaware of a depth-infinity lock on the parent collection "/workspace/webdav/" attempted to modify the collection member "/workspace/webdav/proposal.doc". Some other useful preconditions and postconditions have been defined in other specifications extending WebDAV, such as [[RFC3744](https://datatracker.ietf.org/doc/html/rfc3744)] (see particularly [Section 7.1.1](#section-7.1.1)), [[RFC3253](https://datatracker.ietf.org/doc/html/rfc3253)], and [[RFC3648](https://datatracker.ietf.org/doc/html/rfc3648)]. All these elements are in the "DAV:" namespace. If not specified otherwise, the content for each condition's XML element is defined to be empty. Name: lock-token-matches-request-uri Use with: 409 Conflict Purpose: (precondition) -- A request may include a Lock-Token header to identify a lock for the UNLOCK method. However, if the Request-URI does not fall within the scope of the lock identified by the token, the server SHOULD use this error. The lock may have a scope that does not include the Request-URI, or the lock could have disappeared, or the token may be invalid. Name: lock-token-submitted (precondition) Use with: 423 Locked Purpose: The request could not succeed because a lock token should have been submitted. This element, if present, MUST contain at least one URL of a locked resource that prevented the request. In cases of MOVE, COPY, and DELETE where collection locks are involved, it can be difficult for the client to find out which locked resource made the request fail -- but the server is only responsible for returning one such locked resource. The server MAY return every locked resource that prevented the request from succeeding if it knows them all. <!ELEMENT lock-token-submitted (href+) > Name: no-conflicting-lock (precondition) Use with: Typically 423 Locked Purpose: A LOCK request failed due the presence of an already existing conflicting lock. Note that a lock can be in conflict although the resource to which the request was directed is only indirectly locked. In this case, the precondition code can be used to inform the client about the resource that is the root of the conflicting lock, avoiding a separate lookup of the "lockdiscovery" property. <!ELEMENT no-conflicting-lock (href)\* > Name: no-external-entities Use with: 403 Forbidden Purpose: (precondition) -- If the server rejects a client request because the request body contains an external entity, the server SHOULD use this error. Name: preserved-live-properties Use with: 409 Conflict Purpose: (postcondition) -- The server received an otherwise-valid MOVE or COPY request, but cannot maintain the live properties with the same behavior at the destination. It may be that the server only supports some live properties in some parts of the repository, or simply has an internal error. Name: propfind-finite-depth Use with: 403 Forbidden Purpose: (precondition) -- This server does not allow infinite-depth PROPFIND requests on collections. Name: cannot-modify-protected-property Use with: 403 Forbidden Purpose: (precondition) -- The client attempted to set a protected property in a PROPPATCH (such as DAV:getetag). See also [[RFC3253], Section 3.12](https://datatracker.ietf.org/doc/html/rfc3253#section-3.12). 17. XML Extensibility in DAV ---------------------------- The XML namespace extension ([[REC-XML-NAMES](#ref-REC-XML-NAMES)]) is used in this specification in order to allow for new XML elements to be added without fear of colliding with other element names. Although WebDAV request and response bodies can be extended by arbitrary XML elements, which can be ignored by the message recipient, an XML element in the "DAV:" namespace SHOULD NOT be used in the request or response body unless that XML element is explicitly defined in an IETF RFC reviewed by a WebDAV working group. For WebDAV to be both extensible and backwards-compatible, both clients and servers need to know how to behave when unexpected or unrecognized command extensions are received. For XML processing, this means that clients and servers MUST process received XML documents as if unexpected elements and attributes (and all children of unrecognized elements) were not there. An unexpected element or attribute includes one that may be used in another context but is not expected here. Ignoring such items for purposes of processing can of course be consistent with logging all information or presenting for debugging. This restriction also applies to the processing, by clients, of DAV property values where unexpected XML elements SHOULD be ignored unless the property's schema declares otherwise. This restriction does not apply to setting dead DAV properties on the server where the server MUST record all XML elements. Additionally, this restriction does not apply to the use of XML where XML happens to be the content type of the entity body, for example, when used as the body of a PUT. Processing instructions in XML SHOULD be ignored by recipients. Thus, specifications extending WebDAV SHOULD NOT use processing instructions to define normative behavior. XML DTD fragments are included for all the XML elements defined in this specification. However, correct XML will not be valid according to any DTD due to namespace usage and extension rules. In particular: o Elements (from this specification) are in the "DAV:" namespace, o Element ordering is irrelevant unless otherwise stated, o Extension attributes MAY be added, o For element type definitions of "ANY", the normative text definition for that element defines what can be in it and what that means. o For element type definitions of "#PCDATA", extension elements MUST NOT be added. o For other element type definitions, including "EMPTY", extension elements MAY be added. Note that this means that elements containing elements cannot be extended to contain text, and vice versa. With DTD validation relaxed by the rules above, the constraints described by the DTD fragments are normative (see for example [Appendix A](#appendix-A)). A recipient of a WebDAV message with an XML body MUST NOT validate the XML document according to any hard-coded or dynamically-declared DTD. Note that this section describes backwards-compatible extensibility rules. There might also be times when an extension is designed not to be backwards-compatible, for example, defining an extension that reuses an XML element defined in this document but omitting one of the child elements required by the DTDs in this specification. 18. DAV Compliance Classes -------------------------- A DAV-compliant resource can advertise several classes of compliance. A client can discover the compliance classes of a resource by executing OPTIONS on the resource and examining the "DAV" header which is returned. Note particularly that resources, rather than servers, are spoken of as being compliant. That is because theoretically some resources on a server could support different feature sets. For example, a server could have a sub-repository where an advanced feature like versioning was supported, even if that feature was not supported on all sub-repositories. Since this document describes extensions to the HTTP/1.1 protocol, minimally all DAV-compliant resources, clients, and proxies MUST be compliant with [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]. A resource that is class 2 or class 3 compliant must also be class 1 compliant. ### 18.1. Class 1 A class 1 compliant resource MUST meet all "MUST" requirements in all sections of this document. Class 1 compliant resources MUST return, at minimum, the value "1" in the DAV header on all responses to the OPTIONS method. ### 18.2. Class 2 A class 2 compliant resource MUST meet all class 1 requirements and support the LOCK method, the DAV:supportedlock property, the DAV: lockdiscovery property, the Time-Out response header and the Lock- Token request header. A class 2 compliant resource SHOULD also support the Timeout request header and the 'owner' XML element. Class 2 compliant resources MUST return, at minimum, the values "1" and "2" in the DAV header on all responses to the OPTIONS method. ### 18.3. Class 3 A resource can explicitly advertise its support for the revisions to [[RFC2518](https://datatracker.ietf.org/doc/html/rfc2518)] made in this document. Class 1 MUST be supported as well. Class 2 MAY be supported. Advertising class 3 support in addition to class 1 and 2 means that the server supports all the requirements in this specification. Advertising class 3 and class 1 support, but not class 2, means that the server supports all the requirements in this specification except possibly those that involve locking support. Example: DAV: 1, 3 19. Internationalization Considerations --------------------------------------- In the realm of internationalization, this specification complies with the IETF Character Set Policy [[RFC2277](https://datatracker.ietf.org/doc/html/rfc2277)]. In this specification, human-readable fields can be found either in the value of a property, or in an error message returned in a response entity body. In both cases, the human-readable content is encoded using XML, which has explicit provisions for character set tagging and encoding, and requires that XML processors read XML elements encoded, at minimum, using the UTF-8 [[RFC3629](https://datatracker.ietf.org/doc/html/rfc3629)] and UTF-16 [[RFC2781](https://datatracker.ietf.org/doc/html/rfc2781)] encodings of the ISO 10646 multilingual plane. XML examples in this specification demonstrate use of the charset parameter of the Content-Type header (defined in [[RFC3023](https://datatracker.ietf.org/doc/html/rfc3023)]), as well as XML charset declarations. XML also provides a language tagging capability for specifying the language of the contents of a particular XML element. The "xml:lang" attribute appears on an XML element to identify the language of its content and attributes. See [[REC-XML](#ref-REC-XML)] for definitions of values and scoping. WebDAV applications MUST support the character set tagging, character set encoding, and the language tagging functionality of the XML specification. Implementors of WebDAV applications are strongly encouraged to read "XML Media Types" [[RFC3023](https://datatracker.ietf.org/doc/html/rfc3023)] for instruction on which MIME media type to use for XML transport, and on use of the charset parameter of the Content-Type header. Names used within this specification fall into four categories: names of protocol elements such as methods and headers, names of XML elements, names of properties, and names of conditions. Naming of protocol elements follows the precedent of HTTP, using English names encoded in US-ASCII for methods and headers. Since these protocol elements are not visible to users, and are simply long token identifiers, they do not need to support multiple languages. Similarly, the names of XML elements used in this specification are not visible to the user and hence do not need to support multiple languages. WebDAV property names are qualified XML names (pairs of XML namespace name and local name). Although some applications (e.g., a generic property viewer) will display property names directly to their users, it is expected that the typical application will use a fixed set of properties, and will provide a mapping from the property name and namespace to a human-readable field when displaying the property name to a user. It is only in the case where the set of properties is not known ahead of time that an application need display a property name to a user. We recommend that applications provide human-readable property names wherever feasible. For error reporting, we follow the convention of HTTP/1.1 status codes, including with each status code a short, English description of the code (e.g., 423 (Locked)). While the possibility exists that a poorly crafted user agent would display this message to a user, internationalized applications will ignore this message, and display an appropriate message in the user's language and character set. Since interoperation of clients and servers does not require locale information, this specification does not specify any mechanism for transmission of this information. 20. Security Considerations --------------------------- This section is provided to detail issues concerning security implications of which WebDAV applications need to be aware. All of the security considerations of HTTP/1.1 (discussed in [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]) and XML (discussed in [[RFC3023](https://datatracker.ietf.org/doc/html/rfc3023)]) also apply to WebDAV. In addition, the security risks inherent in remote authoring require stronger authentication technology, introduce several new privacy concerns, and may increase the hazards from poor server design. These issues are detailed below. ### 20.1. Authentication of Clients Due to their emphasis on authoring, WebDAV servers need to use authentication technology to protect not just access to a network resource, but the integrity of the resource as well. Furthermore, the introduction of locking functionality requires support for authentication. A password sent in the clear over an insecure channel is an inadequate means for protecting the accessibility and integrity of a resource as the password may be intercepted. Since Basic authentication for HTTP/1.1 performs essentially clear text transmission of a password, Basic authentication MUST NOT be used to authenticate a WebDAV client to a server unless the connection is secure. Furthermore, a WebDAV server MUST NOT send a Basic authentication challenge in a WWW-Authenticate header unless the connection is secure. An example of a secure connection would be a Transport Layer Security (TLS) connection employing a strong cipher suite and server authentication. WebDAV applications MUST support the Digest authentication scheme [[RFC2617](https://datatracker.ietf.org/doc/html/rfc2617)]. Since Digest authentication verifies that both parties to a communication know a shared secret, a password, without having to send that secret in the clear, Digest authentication avoids the security problems inherent in Basic authentication while providing a level of authentication that is useful in a wide range of scenarios. ### 20.2. Denial of Service Denial-of-service attacks are of special concern to WebDAV servers. WebDAV plus HTTP enables denial-of-service attacks on every part of a system's resources. o The underlying storage can be attacked by PUTting extremely large files. o Asking for recursive operations on large collections can attack processing time. o Making multiple pipelined requests on multiple connections can attack network connections. WebDAV servers need to be aware of the possibility of a denial-of- service attack at all levels. The proper response to such an attack MAY be to simply drop the connection. Or, if the server is able to make a response, the server MAY use a 400-level status request such as 400 (Bad Request) and indicate why the request was refused (a 500- level status response would indicate that the problem is with the server, whereas unintentional DoS attacks are something the client is capable of remedying). ### 20.3. Security through Obscurity WebDAV provides, through the PROPFIND method, a mechanism for listing the member resources of a collection. This greatly diminishes the effectiveness of security or privacy techniques that rely only on the difficulty of discovering the names of network resources. Users of WebDAV servers are encouraged to use access control techniques to prevent unwanted access to resources, rather than depending on the relative obscurity of their resource names. ### 20.4. Privacy Issues Connected to Locks When submitting a lock request, a user agent may also submit an 'owner' XML field giving contact information for the person taking out the lock (for those cases where a person, rather than a robot, is taking out the lock). This contact information is stored in a DAV: lockdiscovery property on the resource, and can be used by other collaborators to begin negotiation over access to the resource. However, in many cases, this contact information can be very private, and should not be widely disseminated. Servers SHOULD limit read access to the DAV:lockdiscovery property as appropriate. Furthermore, user agents SHOULD provide control over whether contact information is sent at all, and if contact information is sent, control over exactly what information is sent. ### 20.5. Privacy Issues Connected to Properties Since property values are typically used to hold information such as the author of a document, there is the possibility that privacy concerns could arise stemming from widespread access to a resource's property data. To reduce the risk of inadvertent release of private information via properties, servers are encouraged to develop access control mechanisms that separate read access to the resource body and read access to the resource's properties. This allows a user to control the dissemination of their property data without overly restricting access to the resource's contents. ### 20.6. Implications of XML Entities XML supports a facility known as "external entities", defined in Section 4.2.2 of [[REC-XML](#ref-REC-XML)], which instructs an XML processor to retrieve and include additional XML. An external XML entity can be used to append or modify the document type declaration (DTD) associated with an XML document. An external XML entity can also be used to include XML within the content of an XML document. For non- validating XML, such as the XML used in this specification, including an external XML entity is not required by XML. However, XML does state that an XML processor may, at its discretion, include the external XML entity. External XML entities have no inherent trustworthiness and are subject to all the attacks that are endemic to any HTTP GET request. Furthermore, it is possible for an external XML entity to modify the DTD, and hence affect the final form of an XML document, in the worst case, significantly modifying its semantics or exposing the XML processor to the security risks discussed in [[RFC3023](https://datatracker.ietf.org/doc/html/rfc3023)]. Therefore, implementers must be aware that external XML entities should be treated as untrustworthy. If a server chooses not to handle external XML entities, it SHOULD respond to requests containing external entities with the 'no-external-entities' condition code. There is also the scalability risk that would accompany a widely deployed application that made use of external XML entities. In this situation, it is possible that there would be significant numbers of requests for one external XML entity, potentially overloading any server that fields requests for the resource containing the external XML entity. Furthermore, there's also a risk based on the evaluation of "internal entities" as defined in Section 4.2.2 of [[REC-XML](#ref-REC-XML)]. A small, carefully crafted request using nested internal entities may require enormous amounts of memory and/or processing time to process. Server implementers should be aware of this risk and configure their XML parsers so that requests like these can be detected and rejected as early as possible. ### 20.7. Risks Connected with Lock Tokens This specification encourages the use of "A Universally Unique Identifier (UUID) URN Namespace" ([[RFC4122](https://datatracker.ietf.org/doc/html/rfc4122)]) for lock tokens ([Section 6.5](#section-6.5)), in order to guarantee their uniqueness across space and time. Version 1 UUIDs (defined in [Section 4](#section-4)) MAY contain a "node" field that "consists of an IEEE 802 MAC address, usually the host address. For systems with multiple IEEE addresses, any available one can be used". Since a WebDAV server will issue many locks over its lifetime, the implication is that it may also be publicly exposing its IEEE 802 address. There are several risks associated with exposure of IEEE 802 addresses. Using the IEEE 802 address: o It is possible to track the movement of hardware from subnet to subnet. o It may be possible to identify the manufacturer of the hardware running a WebDAV server. o It may be possible to determine the number of each type of computer running WebDAV. This risk only applies to host-address-based UUID versions. [Section](https://datatracker.ietf.org/doc/html/rfc4122#section-4) [4 of [RFC4122]](https://datatracker.ietf.org/doc/html/rfc4122#section-4) describes several other mechanisms for generating UUIDs that do not involve the host address and therefore do not suffer from this risk. ### 20.8. Hosting Malicious Content HTTP has the ability to host programs that are executed on client machines. These programs can take many forms including Web scripts, executables, plug-in modules, and macros in documents. WebDAV does not change any of the security concerns around these programs, yet often WebDAV is used in contexts where a wide range of users can publish documents on a server. The server might not have a close trust relationship with the author that is publishing the document. Servers that allow clients to publish arbitrary content can usefully implement precautions to check that content published to the server is not harmful to other clients. Servers could do this by techniques such as restricting the types of content that is allowed to be published and running virus and malware detection software on published content. Servers can also mitigate the risk by having appropriate access restriction and authentication of users that are allowed to publish content to the server. 21. IANA Considerations ----------------------- ### 21.1. New URI Schemes This specification defines two URI schemes: 1. the "opaquelocktoken" scheme defined in [Appendix C](#appendix-C), and 2. the "DAV" URI scheme, which historically was used in [[RFC2518](https://datatracker.ietf.org/doc/html/rfc2518)] to disambiguate WebDAV property and XML element names and which continues to be used for that purpose in this specification and others extending WebDAV. Creation of identifiers in the "DAV:" namespace is controlled by the IETF. Note that defining new URI schemes for XML namespaces is now discouraged. "DAV:" was defined before standard best practices emerged. ### 21.2. XML Namespaces XML namespaces disambiguate WebDAV property names and XML elements. Any WebDAV user or application can define a new namespace in order to create custom properties or extend WebDAV XML syntax. IANA does not need to manage such namespaces, property names, or element names. ### 21.3. Message Header Fields The message header fields below should be added to the permanent registry (see [[RFC3864](https://datatracker.ietf.org/doc/html/rfc3864)]). #### 21.3.1. DAV Header field name: DAV Applicable protocol: http Status: standard Author/Change controller: IETF Specification document: this specification ([Section 10.1](#section-10.1)) #### 21.3.2. Depth Header field name: Depth Applicable protocol: http Status: standard Author/Change controller: IETF Specification document: this specification ([Section 10.2](#section-10.2)) #### 21.3.3. Destination Header field name: Destination Applicable protocol: http Status: standard Author/Change controller: IETF Specification document: this specification ([Section 10.3](#section-10.3)) #### 21.3.4. If Header field name: If Applicable protocol: http Status: standard Author/Change controller: IETF Specification document: this specification ([Section 10.4](#section-10.4)) #### 21.3.5. Lock-Token Header field name: Lock-Token Applicable protocol: http Status: standard Author/Change controller: IETF Specification document: this specification ([Section 10.5](#section-10.5)) #### 21.3.6. Overwrite Header field name: Overwrite Applicable protocol: http Status: standard Author/Change controller: IETF Specification document: this specification ([Section 10.6](#section-10.6)) #### 21.3.7. Timeout Header field name: Timeout Applicable protocol: http Status: standard Author/Change controller: IETF Specification document: this specification ([Section 10.7](#section-10.7)) ### 21.4. HTTP Status Codes This specification defines the HTTP status codes o 207 Multi-Status ([Section 11.1](#section-11.1)) o 422 Unprocessable Entity ([Section 11.2](#section-11.2)), o 423 Locked ([Section 11.3](#section-11.3)), o 424 Failed Dependency ([Section 11.4](#section-11.4)) and o 507 Insufficient Storage ([Section 11.5](#section-11.5)), to be updated in the registry at <[http://www.iana.org/assignments/http-status-codes](https://www.iana.org/assignments/http-status-codes)>. Note: the HTTP status code 102 (Processing) has been removed in this specification; its IANA registration should continue to reference [RFC](https://datatracker.ietf.org/doc/html/rfc2518) [2518](https://datatracker.ietf.org/doc/html/rfc2518). 22. Acknowledgements -------------------- A specification such as this thrives on piercing critical review and withers from apathetic neglect. The authors gratefully acknowledge the contributions of the following people, whose insights were so valuable at every stage of our work. Contributors to [RFC 2518](https://datatracker.ietf.org/doc/html/rfc2518) Terry Allen, Harald Alvestrand, Jim Amsden, Becky Anderson, Alan Babich, Sanford Barr, Dylan Barrell, Bernard Chester, Tim Berners- Lee, Dan Connolly, Jim Cunningham, Ron Daniel, Jr., Jim Davis, Keith Dawson, Mark Day, Brian Deen, Martin Duerst, David Durand, Lee Farrell, Chuck Fay, Wesley Felter, Roy Fielding, Mark Fisher, Alan Freier, George Florentine, Jim Gettys, Phill Hallam-Baker, Dennis Hamilton, Steve Henning, Mead Himelstein, Alex Hopmann, Andre van der Hoek, Ben Laurie, Paul Leach, Ora Lassila, Karen MacArthur, Steven Martin, Larry Masinter, Michael Mealling, Keith Moore, Thomas Narten, Henrik Nielsen, Kenji Ota, Bob Parker, Glenn Peterson, Jon Radoff, Saveen Reddy, Henry Sanders, Christopher Seiwald, Judith Slein, Mike Spreitzer, Einar Stefferud, Greg Stein, Ralph Swick, Kenji Takahashi, Richard N. Taylor, Robert Thau, John Turner, Sankar Virdhagriswaran, Fabio Vitali, Gregory Woodhouse, and Lauren Wood. Two from this list deserve special mention. The contributions by Larry Masinter have been invaluable; he both helped the formation of the working group and patiently coached the authors along the way. In so many ways he has set high standards that we have toiled to meet. The contributions of Judith Slein were also invaluable; by clarifying the requirements and in patiently reviewing version after version, she both improved this specification and expanded our minds on document management. We would also like to thank John Turner for developing the XML DTD. The authors of [RFC 2518](https://datatracker.ietf.org/doc/html/rfc2518) were Yaron Goland, Jim Whitehead, A. Faizi, Steve Carter, and D. Jensen. Although their names had to be removed due to IETF author count restrictions, they can take credit for the majority of the design of WebDAV. Additional Acknowledgements for This Specification Significant contributors of text for this specification are listed as contributors in the section below. We must also gratefully acknowledge Geoff Clemm, Joel Soderberg, and Dan Brotsky for hashing out specific text on the list or in meetings. Joe Hildebrand and Cullen Jennings helped close many issues. Barry Lind described an additional security consideration and Cullen Jennings provided text for that consideration. Jason Crawford tracked issue status for this document for a period of years, followed by Elias Sinderson. 23. Contributors to This Specification -------------------------------------- Julian Reschke <green/>bytes GmbH Hafenweg 16, 48155 Muenster, Germany EMail: [email protected] Elias Sinderson University of California, Santa Cruz 1156 High Street, Santa Cruz, CA 95064 EMail: [email protected] Jim Whitehead University of California, Santa Cruz 1156 High Street, Santa Cruz, CA 95064 EMail: [email protected] 24. Authors of [RFC 2518](https://datatracker.ietf.org/doc/html/rfc2518) ------------------------------------------------------------------------ Y. Y. Goland Microsoft Corporation One Microsoft Way Redmond, WA 98052-6399 EMail: [email protected] E. J. Whitehead, Jr. Dept. Of Information and Computer Science University of California, Irvine Irvine, CA 92697-3425 EMail: [email protected] A. Faizi Netscape 685 East Middlefield Road Mountain View, CA 94043 EMail: [email protected] S. R. Carter Novell 1555 N. Technology Way M/S ORM F111 Orem, UT 84097-2399 EMail: [email protected] D. Jensen Novell 1555 N. Technology Way M/S ORM F111 Orem, UT 84097-2399 EMail: [email protected] 25. References -------------- ### 25.1. Normative References [REC-XML] Bray, T., Paoli, J., Sperberg-McQueen, C., Maler, E., and F. Yergeau, "Extensible Markup Language (XML) 1.0 (Fourth Edition)", W3C REC-xml-20060816, August 2006, <[http://www.w3.org/TR/2006/REC-xml-20060816/](https://www.w3.org/TR/2006/REC-xml-20060816/)>. [REC-XML-INFOSET] Cowan, J. and R. Tobin, "XML Information Set (Second Edition)", W3C REC-xml-infoset-20040204, February 2004, <[http://www.w3.org/TR/2004/](https://www.w3.org/TR/2004/REC-xml-infoset-20040204/) [REC-xml-infoset-20040204/](https://www.w3.org/TR/2004/REC-xml-infoset-20040204/)>. [REC-XML-NAMES] Bray, T., Hollander, D., Layman, A., and R. Tobin, "Namespaces in XML 1.0 (Second Edition)", W3C REC- xml-names-20060816, August 2006, <[http://](https://www.w3.org/TR/2006/REC-xml-names-20060816/) [www.w3.org/TR/2006/REC-xml-names-20060816/](https://www.w3.org/TR/2006/REC-xml-names-20060816/)>. [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", [BCP 14](https://datatracker.ietf.org/doc/html/bcp14), [RFC 2119](https://datatracker.ietf.org/doc/html/rfc2119), March 1997. [RFC2277] Alvestrand, H., "IETF Policy on Character Sets and Languages", [BCP 18](https://datatracker.ietf.org/doc/html/bcp18), [RFC 2277](https://datatracker.ietf.org/doc/html/rfc2277), January 1998. [RFC2616] Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, "Hypertext Transfer Protocol -- HTTP/1.1", [RFC 2616](https://datatracker.ietf.org/doc/html/rfc2616), June 1999. [RFC2617] Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, "HTTP Authentication: Basic and Digest Access Authentication", [RFC 2617](https://datatracker.ietf.org/doc/html/rfc2617), June 1999. [RFC3339] Klyne, G., Ed. and C. Newman, "Date and Time on the Internet: Timestamps", [RFC 3339](https://datatracker.ietf.org/doc/html/rfc3339), July 2002. [RFC3629] Yergeau, F., "UTF-8, a transformation format of ISO 10646", STD 63, [RFC 3629](https://datatracker.ietf.org/doc/html/rfc3629), November 2003. [RFC3986] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform Resource Identifier (URI): Generic Syntax", STD 66, [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986), January 2005. [RFC4122] Leach, P., Mealling, M., and R. Salz, "A Universally Unique IDentifier (UUID) URN Namespace", [RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122), July 2005. ### 25.2. Informative References [RFC2291] Slein, J., Vitali, F., Whitehead, E., and D. Durand, "Requirements for a Distributed Authoring and Versioning Protocol for the World Wide Web", [RFC 2291](https://datatracker.ietf.org/doc/html/rfc2291), February 1998. [RFC2518] Goland, Y., Whitehead, E., Faizi, A., Carter, S., and D. Jensen, "HTTP Extensions for Distributed Authoring -- WEBDAV", [RFC 2518](https://datatracker.ietf.org/doc/html/rfc2518), February 1999. [RFC2781] Hoffman, P. and F. Yergeau, "UTF-16, an encoding of ISO 10646", [RFC 2781](https://datatracker.ietf.org/doc/html/rfc2781), February 2000. [RFC3023] Murata, M., St. Laurent, S., and D. Kohn, "XML Media Types", [RFC 3023](https://datatracker.ietf.org/doc/html/rfc3023), January 2001. [RFC3253] Clemm, G., Amsden, J., Ellison, T., Kaler, C., and J. Whitehead, "Versioning Extensions to WebDAV (Web Distributed Authoring and Versioning)", [RFC 3253](https://datatracker.ietf.org/doc/html/rfc3253), March 2002. [RFC3648] Whitehead, J. and J. Reschke, Ed., "Web Distributed Authoring and Versioning (WebDAV) Ordered Collections Protocol", [RFC 3648](https://datatracker.ietf.org/doc/html/rfc3648), December 2003. [RFC3744] Clemm, G., Reschke, J., Sedlar, E., and J. Whitehead, "Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol", [RFC 3744](https://datatracker.ietf.org/doc/html/rfc3744), May 2004. [RFC3864] Klyne, G., Nottingham, M., and J. Mogul, "Registration Procedures for Message Header Fields", [BCP 90](https://datatracker.ietf.org/doc/html/bcp90), [RFC 3864](https://datatracker.ietf.org/doc/html/rfc3864), September 2004. Appendix A. Notes on Processing XML Elements -------------------------------------------- ### A.1. Notes on Empty XML Elements XML supports two mechanisms for indicating that an XML element does not have any content. The first is to declare an XML element of the form <A></A>. The second is to declare an XML element of the form <A/>. The two XML elements are semantically identical. ### A.2. Notes on Illegal XML Processing XML is a flexible data format that makes it easy to submit data that appears legal but in fact is not. The philosophy of "Be flexible in what you accept and strict in what you send" still applies, but it must not be applied inappropriately. XML is extremely flexible in dealing with issues of whitespace, element ordering, inserting new elements, etc. This flexibility does not require extension, especially not in the area of the meaning of elements. There is no kindness in accepting illegal combinations of XML elements. At best, it will cause an unwanted result and at worst it can cause real damage. ### A.3. Example - XML Syntax Error The following request body for a PROPFIND method is illegal. <?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:"> <D:allprop/> <D:propname/> </D:propfind> The definition of the propfind element only allows for the allprop or the propname element, not both. Thus, the above is an error and must be responded to with a 400 (Bad Request). Imagine, however, that a server wanted to be "kind" and decided to pick the allprop element as the true element and respond to it. A client running over a bandwidth limited line who intended to execute a propname would be in for a big surprise if the server treated the command as an allprop. Additionally, if a server were lenient and decided to reply to this request, the results would vary randomly from server to server, with some servers executing the allprop directive, and others executing the propname directive. This reduces interoperability rather than increasing it. ### A.4. Example - Unexpected XML Element The previous example was illegal because it contained two elements that were explicitly banned from appearing together in the propfind element. However, XML is an extensible language, so one can imagine new elements being defined for use with propfind. Below is the request body of a PROPFIND and, like the previous example, must be rejected with a 400 (Bad Request) by a server that does not understand the expired-props element. <?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:" xmlns:E="http://www.example.com/standards/props/"> <E:expired-props/> </D:propfind> To understand why a 400 (Bad Request) is returned, let us look at the request body as the server unfamiliar with expired-props sees it. <?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:" xmlns:E="http://www.example.com/standards/props/"> </D:propfind> As the server does not understand the 'expired-props' element, according to the WebDAV-specific XML processing rules specified in [Section 17](#section-17), it must process the request as if the element were not there. Thus, the server sees an empty propfind, which by the definition of the propfind element is illegal. Please note that had the extension been additive, it would not necessarily have resulted in a 400 (Bad Request). For example, imagine the following request body for a PROPFIND: <?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:" xmlns:E="http://www.example.com/standards/props/"> <D:propname/> <E:leave-out>\*boss\*</E:leave-out> </D:propfind> The previous example contains the fictitious element leave-out. Its purpose is to prevent the return of any property whose name matches the submitted pattern. If the previous example were submitted to a server unfamiliar with 'leave-out', the only result would be that the 'leave-out' element would be ignored and a propname would be executed. Appendix B. Notes on HTTP Client Compatibility ---------------------------------------------- WebDAV was designed to be, and has been found to be, backward- compatible with HTTP 1.1. The PUT and DELETE methods are defined in HTTP and thus may be used by HTTP clients as well as WebDAV-aware clients, but the responses to PUT and DELETE have been extended in this specification in ways that only a WebDAV client would be entirely prepared for. Some theoretical concerns were raised about whether those responses would cause interoperability problems with HTTP-only clients, and this section addresses those concerns. Since any HTTP client ought to handle unrecognized 400-level and 500- level status codes as errors, the following new status codes should not present any issues: 422, 423, and 507 (424 is also a new status code but it appears only in the body of a Multistatus response.) So, for example, if an HTTP client attempted to PUT or DELETE a locked resource, the 423 Locked response ought to result in a generic error presented to the user. The 207 Multistatus response is interesting because an HTTP client issuing a DELETE request to a collection might interpret a 207 response as a success, even though it does not realize the resource is a collection and cannot understand that the DELETE operation might have been a complete or partial failure. That interpretation isn't entirely justified, because a 200-level response indicates that the server "received, understood, and accepted" the request, not that the request resulted in complete success. One option is that a server could treat a DELETE of a collection as an atomic operation, and use either 204 No Content in case of success, or some appropriate error response (400 or 500 level) for an error. This approach would indeed maximize backward compatibility. However, since interoperability tests and working group discussions have not turned up any instances of HTTP clients issuing a DELETE request against a WebDAV collection, this concern is more theoretical than practical. Thus, servers are likely to be completely successful at interoperating with HTTP clients even if they treat any collection DELETE request as a WebDAV request and send a 207 Multi-Status response. In general, server implementations are encouraged to use the detailed responses and other mechanisms defined in this document rather than make changes for theoretical interoperability concerns. Appendix C. The 'opaquelocktoken' Scheme and URIs ------------------------------------------------- The 'opaquelocktoken' URI scheme was defined in [[RFC2518](https://datatracker.ietf.org/doc/html/rfc2518)] (and registered by IANA) in order to create syntactically correct and easy-to-generate URIs out of UUIDs, intended to be used as lock tokens and to be unique across all resources for all time. An opaquelocktoken URI is constructed by concatenating the 'opaquelocktoken' scheme with a UUID, along with an optional extension. Servers can create new UUIDs for each new lock token. If a server wishes to reuse UUIDs, the server MUST add an extension, and the algorithm generating the extension MUST guarantee that the same extension will never be used twice with the associated UUID. OpaqueLockToken-URI = "opaquelocktoken:" UUID [Extension] ; UUID is defined in [Section 3 of [RFC4122]](https://datatracker.ietf.org/doc/html/rfc4122#section-3). Note that LWS ; is not allowed between elements of ; this production. Extension = path ; path is defined in [Section 3.3 of [RFC3986]](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3) Appendix D. Lock-null Resources ------------------------------- The original WebDAV model for locking unmapped URLs created "lock- null resources". This model was over-complicated and some interoperability and implementation problems were discovered. The new WebDAV model for locking unmapped URLs (see [Section 7.3](#section-7.3)) creates "locked empty resources". Lock-null resources are deprecated. This section discusses the original model briefly because clients MUST be able to handle either model. In the original "lock-null resource" model, which is no longer recommended for implementation: o A lock-null resource sometimes appeared as "Not Found". The server responds with a 404 or 405 to any method except for PUT, MKCOL, OPTIONS, PROPFIND, LOCK, UNLOCK. o A lock-null resource does however show up as a member of its parent collection. o The server removes the lock-null resource entirely (its URI becomes unmapped) if its lock goes away before it is converted to a regular resource. Recall that locks go away not only when they expire or are unlocked, but are also removed if a resource is renamed or moved, or if any parent collection is renamed or moved. o The server converts the lock-null resource into a regular resource if a PUT request to the URL is successful. o The server converts the lock-null resource into a collection if a MKCOL request to the URL is successful (though interoperability experience showed that not all servers followed this requirement). o Property values were defined for DAV:lockdiscovery and DAV: supportedlock properties but not necessarily for other properties like DAV:getcontenttype. Clients can easily interoperate both with servers that support the old model "lock-null resources" and the recommended model of "locked empty resources" by only attempting PUT after a LOCK to an unmapped URL, not MKCOL or GET. ### D.1. Guidance for Clients Using LOCK to Create Resources A WebDAV client implemented to this specification might find servers that create lock-null resources (implemented before this specification using [[RFC2518](https://datatracker.ietf.org/doc/html/rfc2518)]) as well as servers that create locked empty resources. The response to the LOCK request will not indicate what kind of resource was created. There are a few techniques that help the client deal with either type. If the client wishes to avoid accidentally creating either lock- null or empty locked resources, an "If-Match: \*" header can be included with LOCK requests to prevent the server from creating a new resource. If a LOCK request creates a resource and the client subsequently wants to overwrite that resource using a COPY or MOVE request, the client should include an "Overwrite: T" header. If a LOCK request creates a resource and the client then decides to get rid of that resource, a DELETE request is supposed to fail on a lock-null resource and UNLOCK should be used instead. But with a locked empty resource, UNLOCK doesn't make the resource disappear. Therefore, the client might have to try both requests and ignore an error in one of the two requests. Appendix E. Guidance for Clients Desiring to Authenticate --------------------------------------------------------- Many WebDAV clients that have already been implemented have account settings (similar to the way email clients store IMAP account settings). Thus, the WebDAV client would be able to authenticate with its first couple requests to the server, provided it had a way to get the authentication challenge from the server with realm name, nonce, and other challenge information. Note that the results of some requests might vary according to whether or not the client is authenticated -- a PROPFIND might return more visible resources if the client is authenticated, yet not fail if the client is anonymous. There are a number of ways the client might be able to trigger the server to provide an authentication challenge. This appendix describes a couple approaches that seem particularly likely to work. The first approach is to perform a request that ought to require authentication. However, it's possible that a server might handle any request even without authentication, so to be entirely safe, the client could add a conditional header to ensure that even if the request passes permissions checks, it's not actually handled by the server. An example of following this approach would be to use a PUT request with an "If-Match" header with a made-up ETag value. This approach might fail to result in an authentication challenge if the server does not test authorization before testing conditionals as is required (see [Section 8.5](#section-8.5)), or if the server does not need to test authorization. Example - forcing auth challenge with write request >>Request PUT /forceauth.txt HTTP/1.1 Host: www.example.com If-Match: "xxx" Content-Type: text/plain Content-Length: 0 The second approach is to use an Authorization header (defined in [[RFC2617](https://datatracker.ietf.org/doc/html/rfc2617)]), which is likely to be rejected by the server but which will then prompt a proper authentication challenge. For example, the client could start with a PROPFIND request containing an Authorization header containing a made-up Basic userid:password string or with actual plausible credentials. This approach relies on the server responding with a "401 Unauthorized" along with a challenge if it receives an Authorization header with an unrecognized username, invalid password, or if it doesn't even handle Basic authentication. This seems likely to work because of the requirements of [RFC 2617](https://datatracker.ietf.org/doc/html/rfc2617): "If the origin server does not wish to accept the credentials sent with a request, it SHOULD return a 401 (Unauthorized) response. The response MUST include a WWW-Authenticate header field containing at least one (possibly new) challenge applicable to the requested resource." There's a slight problem with implementing that recommendation in some cases, because some servers do not even have challenge information for certain resources. Thus, when there's no way to authenticate to a resource or the resource is entirely publicly available over all accepted methods, the server MAY ignore the Authorization header, and the client will presumably try again later. Example - forcing auth challenge with Authorization header >>Request PROPFIND /docs/ HTTP/1.1 Host: www.example.com Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== Content-type: application/xml; charset="utf-8" Content-Length: xxxx [body omitted] Appendix F. Summary of Changes from [RFC 2518](https://datatracker.ietf.org/doc/html/rfc2518) --------------------------------------------------------------------------------------------- This section lists major changes between this document and [RFC 2518](https://datatracker.ietf.org/doc/html/rfc2518), starting with those that are likely to result in implementation changes. Servers will advertise support for all changes in this specification by returning the compliance class "3" in the DAV response header (see Sections [10.1](#section-10.1) and [18.3](#section-18.3)). ### F.1. Changes for Both Client and Server Implementations Collections and Namespace Operations o The semantics of PROPFIND 'allprop' ([Section 9.1](#section-9.1)) have been relaxed so that servers return results including, at a minimum, the live properties defined in this specification, but not necessarily return other live properties. The 'allprop' directive therefore means something more like "return all properties that are supposed to be returned when 'allprop' is requested" -- a set of properties that may include custom properties and properties defined in other specifications if those other specifications so require. Related to this, 'allprop' requests can now be extended with the 'include' syntax to include specific named properties, thereby avoiding additional requests due to changed 'allprop' semantics. o Servers are now allowed to reject PROPFIND requests with Depth: Infinity. Clients that used this will need to be able to do a series of Depth:1 requests instead. o Multi-Status response bodies now can transport the value of HTTP's Location response header in the new 'location' element. Clients may use this to avoid additional roundtrips to the server when there is a 'response' element with a 3xx status (see [Section 14.24](#section-14.24)). o The definition of COPY has been relaxed so that it doesn't require servers to first delete the target resources anymore (this was a known incompatibility with [[RFC3253](https://datatracker.ietf.org/doc/html/rfc3253)]). See [Section 9.8](#section-9.8). Headers and Marshalling o The Destination and If request headers now allow absolute paths in addition to full URIs (see [Section 8.3](#section-8.3)). This may be useful for clients operating through a reverse proxy that does rewrite the Host request header, but not WebDAV-specific headers. o This specification adopts the error marshalling extensions and the "precondition/postcondition" terminology defined in [[RFC3253](https://datatracker.ietf.org/doc/html/rfc3253)] (see [Section 16](#section-16)). Related to that, it adds the "error" XML element inside multistatus response bodies (see [Section 14.5](#section-14.5), however note that it uses a format different from the one recommended in [RFC](https://datatracker.ietf.org/doc/html/rfc3253) [3253](https://datatracker.ietf.org/doc/html/rfc3253)). o Senders and recipients are now required to support the UTF-16 character encoding in XML message bodies (see [Section 19](#section-19)). o Clients are now required to send the Depth header on PROPFIND requests, although servers are still encouraged to support clients that don't. Locking o [RFC 2518](https://datatracker.ietf.org/doc/html/rfc2518)'s concept of "lock-null resources" (LNRs) has been replaced by a simplified approach, the "locked empty resources" (see [Section 7.3](#section-7.3)). There are some aspects of lock-null resources clients cannot rely on anymore, namely, the ability to use them to create a locked collection or the fact that they disappear upon UNLOCK when no PUT or MKCOL request was issued. Note that servers are still allowed to implement LNRs as per [RFC 2518](https://datatracker.ietf.org/doc/html/rfc2518). o There is no implicit refresh of locks anymore. Locks are only refreshed upon explicit request (see [Section 9.10.2](#section-9.10.2)). o Clarified that the DAV:owner value supplied in the LOCK request must be preserved by the server just like a dead property ([Section 14.17](#section-14.17)). Also added the DAV:lockroot element ([Section 14.12](#section-14.12)), which allows clients to discover the root of lock. ### F.2. Changes for Server Implementations Collections and Namespace Operations o Due to interoperability problems, allowable formats for contents of 'href' elements in multistatus responses have been limited (see [Section 8.3](#section-8.3)). o Due to lack of implementation, support for the 'propertybehavior' request body for COPY and MOVE has been removed. Instead, requirements for property preservation have been clarified (see Sections [9.8](#section-9.8) and [9.9](#section-9.9)). Properties o Strengthened server requirements for storage of property values, in particular persistence of language information (xml:lang), whitespace, and XML namespace information (see [Section 4.3](#section-4.3)). o Clarified requirements on which properties should be writable by the client; in particular, setting "DAV:displayname" should be supported by servers (see [Section 15](#section-15)). o Only '[rfc1123](https://datatracker.ietf.org/doc/html/rfc1123)-date' productions are legal as values for DAV: getlastmodified (see [Section 15.7](#section-15.7)). Headers and Marshalling o Servers are now required to do authorization checks before processing conditional headers (see [Section 8.5](#section-8.5)). Locking o Strengthened requirement to check identity of lock creator when accessing locked resources (see [Section 6.4](#section-6.4)). Clients should be aware that lock tokens returned to other principals can only be used to break a lock, if at all. o [Section 8.10.4 of [RFC2518]](https://datatracker.ietf.org/doc/html/rfc2518#section-8.10.4) incorrectly required servers to return a 409 status where a 207 status was really appropriate. This has been corrected ([Section 9.10](#section-9.10)). ### F.3. Other Changes The definition of collection state has been fixed so it doesn't vary anymore depending on the Request-URI (see [Section 5.2](#section-5.2)). The DAV:source property introduced in [Section 4.6 of [RFC2518]](https://datatracker.ietf.org/doc/html/rfc2518#section-4.6) was removed due to lack of implementation experience. The DAV header now allows non-IETF extensions through URIs in addition to compliance class tokens. It also can now be used in requests, although this specification does not define any associated semantics for the compliance classes defined in here (see [Section 10.1](#section-10.1)). In [RFC 2518](https://datatracker.ietf.org/doc/html/rfc2518), the definition of the Depth header ([Section 9.2](#section-9.2)) required that, by default, request headers would be applied to each resource in scope. Based on implementation experience, the default has now been reversed (see [Section 10.2](#section-10.2)). The definitions of HTTP status code 102 ([[RFC2518], Section 10.1](https://datatracker.ietf.org/doc/html/rfc2518#section-10.1)) and the Status-URI response header ([Section 9.7](#section-9.7)) have been removed due to lack of implementation. The TimeType format used in the Timeout request header and the "timeout" XML element used to be extensible. Now, only the two formats defined by this specification are allowed (see [Section 10.7](#section-10.7)). Author's Address Lisa Dusseault (editor) CommerceNet 2064 Edgewood Dr. Palo Alto, CA 94303 US EMail: [email protected] Full Copyright Statement Copyright (C) The IETF Trust (2007). This document is subject to the rights, licenses and restrictions contained in [BCP 78](https://datatracker.ietf.org/doc/html/bcp78), and except as set forth therein, the authors retain all their rights. This document and the information contained herein are provided on an "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY, THE IETF TRUST AND THE INTERNET ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Intellectual Property The IETF takes no position regarding the validity or scope of any Intellectual Property Rights or other rights that might be claimed to pertain to the implementation or use of the technology described in this document or the extent to which any license under such rights might or might not be available; nor does it represent that it has made any independent effort to identify any such rights. Information on the procedures with respect to rights in RFC documents can be found in [BCP 78](https://datatracker.ietf.org/doc/html/bcp78) and [BCP 79](https://datatracker.ietf.org/doc/html/bcp79). Copies of IPR disclosures made to the IETF Secretariat and any assurances of licenses to be made available, or the result of an attempt made to obtain a general license or permission for the use of such proprietary rights by implementers or users of this specification can be obtained from the IETF on-line IPR repository at [http://www.ietf.org/ipr](https://www.ietf.org/ipr). The IETF invites any interested party to bring to its attention any copyrights, patents or patent applications, or other proprietary rights that may cover technology that may be required to implement this standard. Please address the information to the IETF at [email protected]. Acknowledgement Funding for the RFC Editor function is currently provided by the Internet Society. Dusseault Standards Track [Page 127]
programming_docs
http Browser detection using the user agent Browser detection using the user agent ====================================== Browser detection using the user agent ====================================== Serving different Web pages or services to different browsers is usually a bad idea. The Web is meant to be accessible to everyone, regardless of which browser or device they're using. There are ways to develop your website to progressively enhance itself based on the availability of features rather than by targeting specific browsers. But browsers and standards are not perfect, and there are still some edge cases where detecting the browser is needed. Using the user agent to detect the browser looks simple, but doing it well is, in fact, a very hard problem. This document will guide you in doing this as correctly as possible. **Note:** It's worth re-iterating: it's very rarely a good idea to use user agent sniffing. You can almost always find a better, more broadly compatible way to solve your problem! Considerations before using browser detection --------------------------------------------- When considering using the user agent string to detect which browser is being used, your first step is to try to avoid it if possible. Start by trying to identify **why** you want to do it. Are you trying to work around a specific bug in some version of a browser? Look, or ask, in specialized forums: you're unlikely to be the first to hit this problem. Also, experts, or people with another point of view, can give you ideas for working around the bug. If the problem seems uncommon, it's worth checking if this bug has been reported to the browser vendor via their bug tracking system ([Mozilla](https://bugzilla.mozilla.org); [WebKit](https://bugs.webkit.org); [Blink](https://www.chromium.org/issue-tracking/); [Opera](https://bugs.opera.com/)). Browser makers do pay attention to bug reports, and the analysis may hint about other workarounds for the bug. Are you trying to check for the existence of a specific feature? Your site needs to use a specific Web feature that some browsers don't yet support, and you want to send those users to an older Web site with fewer features but that you know will work. This is the worst reason to use user agent detection because odds are eventually all the other browsers will catch up. In addition, it is not practical to test every one of the less popular browsers and test for those Web features. You should **never** do user agent sniffing. There is **always** the alternative of doing feature detection instead. Do you want to provide different HTML depending on which browser is being used? This is usually a bad practice, but there are some cases in which this is necessary. In these cases, you should first analyze your situation to be sure it's really necessary. Can you prevent it by adding some non-semantic [`<div>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div) or [`<span>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span) elements? The difficulty of successfully using user agent detection is worth a few disruptions to the purity of your HTML. Also, rethink your design: can you use progressive enhancement or fluid layouts to help remove the need to do this? Avoiding user agent detection ----------------------------- If you want to avoid using user agent detection, you have options! Feature detection Feature detection is where you don't try to figure out which browser is rendering your page, but instead, you check to see if the specific feature you need is available. If it's not, you use a fallback. In those rare cases where behavior differs between browsers, instead of checking the user agent string, you should instead implement a test to detect how the browser implements the API and determine how to use it from that. An example of feature detection is as follows. In 2017, Chrome [unflagged experimental lookbehind support in regular expressions](https://chromestatus.com/feature/5668726032564224), but no other browser supported it. So, you might have thought to do this: ``` // This code snippet splits a string in a special notation let splitUpString; if (navigator.userAgent.includes("Chrome")) { // YES! The user is suspected to support look-behind regexps // DO NOT USE /(?<=[A-Z])/. It will cause a syntax error in // browsers that do not support look-behind expressions // because all browsers parse the entire script, including // sections of the code that are never executed. const camelCaseExpression = new RegExp("(?<=[A-Z])"); splitUpString = (str) => String(str).split(camelCaseExpression); } else { // This fallback code is much less performant, but works splitUpString = (str) => str.replace(/[A-Z]/g, "z$1").split(/z(?=[A-Z])/g); } console.log(splitUpString("fooBare")); // ["fooB", "are"] console.log(splitUpString("jQWhy")); // ["jQ", "W", "hy"] ``` The above code would have made several incorrect assumptions: First, it assumed that all user agent strings that include the substring "Chrome" are Chrome. UA strings are notoriously misleading. Then, it assumed that the lookbehind feature would always be available if the browser was Chrome. The agent might be an older version of Chrome, from before support was added, or (because the feature was experimental at the time) it could be a later version of Chrome that removed it. Most importantly, it assumed no other browsers would support the feature. Support could have been added to other browsers at any time, but this code would have continued choosing the inferior path. Problems like these can be avoided by testing for support of the feature itself instead: ``` let isLookBehindSupported = false; try { new RegExp("(?<=)"); isLookBehindSupported = true; } catch (err) { // If the agent doesn't support look behinds, the attempted // creation of a RegExp object using that syntax throws and // isLookBehindSupported remains false. } const splitUpString = isLookBehindSupported ? (str) => String(str).split(new RegExp("(?<=[A-Z])")) : (str) => str.replace(/[A-Z]/g, "z$1").split(/z(?=[A-Z])/g); ``` As the above code demonstrates, there is **always** a way to test browser support without user agent sniffing. There is **never** any reason to check the user agent string for this. Lastly, the above code snippets bring about a critical issue with cross-browser coding that must always be taken into account. Don't unintentionally use the API you are testing for in unsupported browsers. This may sound obvious and simple, but sometimes it is not. For example, in the above code snippets, using lookbehind in short-regexp notation (for example, /reg/igm) will cause a parser error in unsupported browsers. Thus, in the above example, you would use *new RegExp("(?<=look\_behind\_stuff)");* instead of */(?<=look\_behind\_stuff)/*, even in the lookbehind supported section of your code. Progressive enhancement This design technique involves developing your Web site in 'layers', using a bottom-up approach, starting with a simpler layer and improving the capabilities of the site in successive layers, each using more features. Graceful degradation This is a top-down approach in which you build the best possible site using all the features you want, then tweak it to make it work on older browsers. This can be harder to do, and less effective, than progressive enhancement, but may be useful in some cases. Mobile device detection Arguably the most common use and misuse of user agent sniffing is to detect if the device is a mobile device. However, people too often overlook what they are really after. People use user agent sniffing to detect if the users' device is touch-friendly and has a small screen so they can optimize their website accordingly. While user agent sniffing can sometimes detect these, not all devices are the same: some mobile devices have big screen sizes, some desktops have a small touchscreen, some people use smart TV's which are an entirely different ballgame altogether, and some people can dynamically change the width and height of their screen by flipping their tablet on its side! So, user agent sniffing is definitely not the way to go. Thankfully, there are much better alternatives. Use [Navigator.maxTouchPoints](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/maxTouchPoints) to detect if the user's device has a touchscreen. Then, default back to checking the user agent screen only *if (!("maxTouchPoints" in navigator)) { /\*Code here\*/}*. Using this information of whether the device has a touchscreen, do not change the entire layout of the website just for touch devices: you will only create more work and maintenance for yourself. Rather, add in touch conveniences such as bigger, more easily clickable buttons (you can do this using CSS by increasing the font size). Here is an example of code that increases the padding of #exampleButton to 1em on mobile devices. ``` let hasTouchScreen = false; if ("maxTouchPoints" in navigator) { hasTouchScreen = navigator.maxTouchPoints > 0; } else if ("msMaxTouchPoints" in navigator) { hasTouchScreen = navigator.msMaxTouchPoints > 0; } else { const mQ = matchMedia?.("(pointer:coarse)"); if (mQ?.media === "(pointer:coarse)") { hasTouchScreen = !!mQ.matches; } else if ("orientation" in window) { hasTouchScreen = true; // deprecated, but good fallback } else { // Only as a last resort, fall back to user agent sniffing const UA = navigator.userAgent; hasTouchScreen = /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) || /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA); } } if (hasTouchScreen) { document.getElementById("exampleButton").style.padding = "1em"; } ``` As for the screen size, use *window.innerWidth* and window.addEventListener("resize", () => { /\*refresh screen size dependent things\*/ }). What you want to do for screen size is not slash off information on smaller screens. That will only annoy people because it will force them to use the desktop version. Rather, try to have fewer columns of information in a longer page on smaller screens while having more columns with a shorter page on larger screen sizes. This effect can be easily achieved using CSS [flexboxes](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox), sometimes with [floats](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Floats) as a partial fallback. Also try to move less relevant/important information down to the bottom and group the page's content together meaningfully. Although it is off-topic, perhaps the following detailed example might give you insights and ideas that persuade you to forgo user agent sniffing. Let us imagine a page composed of boxes of information; each box is about a different feline breed or canine breed. Each box has an image, an overview, and a historical fun fact. The pictures are kept to a maximum reasonable size even on large screens. For the purposes of grouping the content meaningfully, all the cat boxes are separated from all the dog boxes such that the cat and dog boxes are not intermixed together. On a large screen, it saves space to have multiple columns to reduce the space wasted to the left and to the right of the pictures. The boxes can be separated into multiple columns via two equally fair method. From this point on, we shall assume that all the dog boxes are at the top of the source code, that all the cat boxes are at the bottom of the source code, and that all these boxes have the same parent element. There a single instance of a dog box immediately above a cat box, of course. The first method uses horizontal [Flexboxes](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox) to group the content such that when the page is displayed to the end user, all the dogs boxes are at the top of the page and all the cat boxes are lower on the page. The second method uses a [Column](https://developer.mozilla.org/en-US/docs/Web/CSS/Layout_cookbook/Column_layouts) layout and resents all the dogs to the left and all the cats to the right. Only in this particular scenario, it is appropriate to provide no fallback for the flexboxes/multicolumns, resulting in a single column of very wide boxes on old browsers. Also consider the following. If more people visit the webpage to see the cats, then it might be a good idea to put all the cats higher in the source code than the dogs so that more people can find what they are looking for faster on smaller screens where the content collapses down to one column. Next, always make your code dynamic. The user can flip their mobile device on its side, changing the width and height of the page. Or, there might be some weird flip-phone-like device thing in the future where flipping it out extends the screen. Do not be the developer having a headache over how to deal with the flip-phone-like device thing. Never be satisfied with your webpage until you can open up the dev tools side panel and resize the screen while the webpage looks smooth, fluid, and dynamically resized. The simplest way to do this is to separate all the code that moves content around based on screen size to a single function that is called when the page is loaded and at each [resize](https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event) event thereafter. If there is a lot calculated by this layout function before it determines the new layout of the page, then consider debouncing the event listener such that it is not called as often. Also note that there is a huge difference between the media queries `(max-width: 25em)`, `not all and (min-width: 25em)`, and `(max-width: 24.99em)`: `(max-width: 25em)` excludes `(max-width: 25em)`, whereas `not all and (min-width: 25em)` includes `(max-width: 25em)`. `(max-width: 24.99em)` is a poor man's version of `not all and (min-width: 25em)`: do not use `(max-width: 24.99em)` because the layout *might* break on very high font sizes on very high definition devices in the future. Always be very deliberate about choosing the right media query and choosing the right >=, <=, >, or < in any corresponding JavaScript because it is very easy to get these mixed up, resulting in the website looking wonky right at the screen size where the layout changes. Thus, thoroughly test the website at the exact widths/heights where layout changes occur to ensure that the layout changes occur properly. Making the best of user agent sniffing -------------------------------------- After reviewing all of the above better alternatives to user agent sniffing, there are still some potential cases where user agent sniffing is appropriate and justified. One such case is using user agent sniffing as a fallback when detecting if the device has a touch screen. See the [Mobile Device Detection](#mobile_device_detection) section for more information. Another such case is for fixing bugs in browsers that do not automatically update. Internet Explorer (on Windows) and Webkit (on iOS) are two perfect examples. Prior to version 9, Internet Explorer had issues with rendering bugs, CSS bugs, API bugs, and so forth. However, prior to version 9, Internet Explorer was very easy to detect based upon the browser-specific features available. Webkit is a bit worse because Apple forces all of the browsers on IOS to use Webkit internally, thus the user has no way to get a better more updated browser on older devices. Most bugs can be detected, but some bugs take more effort to detect than others. In such cases, it might be beneficial to use user agent sniffing to save on performance. For example, Webkit 6 has a bug whereby when the device orientation changes, the browser might not fire [MediaQueryList](https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList) listeners when it should. To overcome this bug, observe the code below. ``` const UA = navigator.userAgent; const isWebkit = /\b(iPad|iPhone|iPod)\b/.test(UA) && /WebKit/.test(UA) && !/Edge/.test(UA) && !window.MSStream; let mediaQueryUpdated = true; const mqL = []; function whenMediaChanges() { mediaQueryUpdated = true; } const listenToMediaQuery = isWebkit ? (mQ, f) => { if (/height|width/.test(mQ.media)) { mqL.push([mQ, f]); } mQ.addListener(f); mQ.addListener(whenMediaChanges); } : () => {}; const destroyMediaQuery = isWebkit ? (mQ) => { for (let i = 0; i < mqL.length; i++) { if (mqL[i][0] === mQ) { mqL.splice(i, 1); } } mQ.removeListener(whenMediaChanges); } : listenToMediaQuery; let orientationChanged = false; addEventListener( "orientationchange", () => { orientationChanged = true; }, PASSIVE\_LISTENER\_OPTION ); addEventListener("resize", () => setTimeout(() => { if (orientationChanged && !mediaQueryUpdated) { for (let i = 0; i < mqL.length; i++) { mqL[i][1](mqL[i][0]); } } mediaQueryUpdated = orientationChanged = false; }, 0) ); ``` Which part of the user agent contains the information you are looking for? -------------------------------------------------------------------------- As there is no uniformity of the different part of the user agent string, this is the tricky part. ### Browser Name When people say they want "browser detection", often they actually want "rendering engine detection". Do you actually want to detect Firefox, as opposed to SeaMonkey, or Chrome as opposed to Chromium? Or do you actually want to see if the browser is using the Gecko or the WebKit rendering engine? If this is what you need, see further down the page. Most browsers set the name and version in the format *BrowserName/VersionNumber*, with the notable exception of Internet Explorer. But as the name is not the only information in a user agent string that is in that format, you can not discover the name of the browser, you can only check if the name you are looking for. But note that some browsers are lying: Chrome for example reports both as Chrome and Safari. So to detect Safari you have to check for the Safari string and the absence of the Chrome string, Chromium often reports itself as Chrome too or Seamonkey sometimes reports itself as Firefox. Also, pay attention not to use a simple regular expression on the BrowserName, user agents also contain strings outside the Keyword/Value syntax. Safari & Chrome contain the string 'like Gecko', for instance. | Engine | Must contain | Must not contain | | --- | --- | --- | | Firefox | `Firefox/xyz` | `Seamonkey/xyz` | | Seamonkey | `Seamonkey/xyz` | | | Chrome | `Chrome/xyz` | `Chromium/xyz` | | Chromium | `Chromium/xyz` | | | Safari | `Safari/xyz` | `Chrome/xyz` or `Chromium/xyz` | | Opera 15+ (Blink-based engine) | `OPR/xyz` | | | Opera 12- (Presto-based engine) | `Opera/xyz` | | | Internet Explorer 10- | `; MSIE xyz;` | | | Internet Explorer 11 | `Trident/7.0; .*rv:xyz` | | [1] Safari gives two version numbers: one technical in the `Safari/xyz` token, and one user-friendly in a `Version/xyz` token. Of course, there is absolutely no guarantee that another browser will not hijack some of these things (like Chrome hijacked the Safari string in the past). That's why browser detection using the user agent string is unreliable and should be done only with the check of the version number (hijacking of past versions is less likely). ### Browser version The browser version is often, but not always, put in the value part of the *BrowserName/VersionNumber* token in the User Agent String. This is of course not the case for Internet Explorer (which puts the version number right after the MSIE token), and for Opera after version 10, which has added a Version/*VersionNumber* token. Here again, be sure to take the right token for the browser you are looking for, as there is no guarantee that others will contain a valid number. ### Rendering engine As seen earlier, in most cases, looking for the rendering engine is a better way to go. This will help to not exclude lesser known browsers. Browsers sharing a common rendering engine will display a page in the same way: it is often a fair assumption that what will work in one will work in the other. There are five major rendering engines: Trident, Gecko, Presto, Blink, and WebKit. As sniffing the rendering engines names is common, a lot of user agents added other rendering names to trigger detection. It is therefore important to pay attention not to trigger false-positives when detecting the rendering engine. | Engine | Must contain | Comment | | --- | --- | --- | | Gecko | `Gecko/xyz` | | | WebKit | `AppleWebKit/xyz` | Pay attention, WebKit browsers add a 'like Gecko' string that may trigger false positive for Gecko if the detection is not careful. | | Presto | `Opera/xyz` | **Note:** Presto is no longer used in Opera browser builds >= version 15 (see 'Blink') | | Trident | `Trident/xyz` | Internet Explorer put this token in the *comment* part of the User Agent String | | EdgeHTML | `Edge/xyz` | The non-Chromium Edge puts its engine version after the *Edge/* token, not the application version. **Note:** EdgeHTML is no longer used in Edge browser builds >= version 79 (see 'Blink'). | | Blink | `Chrome/xyz` | | Rendering engine version ------------------------ Most rendering engines put the version number in the *RenderingEngine/VersionNumber* token, with the notable exception of Gecko. Gecko puts the Gecko version number in the comment part of the User Agent after the `rv:` string. From Gecko 14 for the mobile version and Gecko 17 for the desktop version, it also puts this value in the `Gecko/version` token (previous version put there the build date, then a fixed date called the GeckoTrail). OS -- The Operating System is given in most User Agent strings (although not web-focused platforms like Firefox OS), but the format varies a lot. It is a fixed string between two semicolons, in the comment part of the User Agent. These strings are specific for each browser. They indicate the OS, but also often its version and information on the relying hardware (32 or 64 bits, or Intel/PPC for Mac). Like in all cases, these strings may change in the future, one should use them only in conjunction with the detection of already released browsers. A technological survey must be in place to adapt the script when new browser versions are coming out. ### Mobile, Tablet or Desktop The most common reason to perform user agent sniffing is to determine which type of device the browser runs on. The goal is to serve different HTML to different device types. * Never assume that a browser or a rendering engine only runs on one type of device. Especially don't make different defaults for different browsers or rendering engines. * Never use the OS token to define if a browser is on mobile, tablet or desktop. The OS may run on more than one type of (for example, Android runs on tablets as well as phones). The following table summarizes the way common browser vendors indicate that their browsers are running on a mobile device: | Browser | Rule | Example | | --- | --- | --- | | Mozilla (Gecko, Firefox) | `Mobile` or `Tablet` inside the comment. | `Mozilla/5.0 (Android; Mobile; rv:13.0) Gecko/13.0 Firefox/13.0` | | WebKit-based (Android, Safari) | `Mobile Safari` token [outside](https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/OptimizingforSafarioniPhone/OptimizingforSafarioniPhone.html#//apple_ref/doc/uid/TP40006517-SW3) the comment. | `Mozilla/5.0 (Linux; U; Android 4.0.3; de-ch; HTC Sensation Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30` | | Blink-based (Chromium, Google Chrome, Opera 15+, Edge on Android) | `Mobile Safari` token [outside](https://developer.chrome.com/docs/multidevice/user-agent/) the comment. | `Mozilla/5.0 (Linux; Android 4.4.2); Nexus 5 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Mobile Safari/537.36 OPR/20.0.1396.72047` | | Presto-based (Opera 12-) | `Opera Mobi/xyz` token [inside](https://developers.whatismybrowser.com/useragents/explore/layout_engine_name/presto/) the comment. | `Opera/9.80 (Android 2.3.3; Linux; Opera Mobi/ADR-1111101157; U; es-ES) Presto/2.9.201 Version/11.50` | | Internet Explorer | `IEMobile/xyz` token in the comment. | `Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0)` | | Edge on Windows 10 Mobile | `Mobile/xyz` and `Edge/` tokens outside the comment. | `Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; Xbox; Xbox One) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Mobile Safari/537.36 Edge/16.16299` | In summary, we recommend looking for the string `Mobi` anywhere in the User Agent to detect a mobile device. **Note:** If the device is large enough that it's not marked with `Mobi`, you should serve your desktop site (which, as a best practice, should support touch input anyway, as more desktop machines are appearing with touchscreens).
programming_docs
http Compression Compression =========== Compression in HTTP =================== **Compression** is an important way to increase the performance of a Web site. For some documents, size reduction of up to 70% lowers the bandwidth capacity needs. Over the years, algorithms also got more efficient, and new ones are supported by clients and servers. In practice, web developers don't need to implement compression mechanisms, both browsers and servers have it implemented already, but they have to be sure that the server is configured adequately. Compression happens at three different levels: * first some file formats are compressed with specific optimized methods, * then general encryption can happen at the HTTP level (the resource is transmitted compressed from end to end), * and finally compression can be defined at the connection level, between two nodes of an HTTP connection. File format compression ----------------------- Each data type has some redundancy, that is *wasted space*, in it. If text can typically have as much as 60% redundancy, this rate can be much higher for some other media like audio and video. Unlike text, these other media types use a lot of space to store their data and the need to optimize storage and regain space was apparent very early. Engineers designed the optimized compression algorithm used by file formats designed for this specific purpose. Compression algorithms used for files can be grouped into two broad categories: * *Loss-less compression*, where the compression-uncompression cycle doesn't alter the data that is recovered. It matches (byte to byte) with the original. For images, `gif` or `png` are using lossless compression. * *Lossy compression*, where the cycle alters the original data in a (hopefully) imperceptible way for the user. Video formats on the Web are lossy; the `jpeg` image format is also lossy. Some formats can be used for both loss-less or lossy compression, like `webp`, and usually lossy algorithm can be configured to compress more or less, which then of course leads to less or more quality. For better performance of a Web site, it is ideal to compress as much as possible, while keeping an acceptable level of quality. For images, an image generated by a tool could be not optimized enough for the Web; it is recommended to use tools that will compress as much as possible with the required quality. There are [numerous tools](https://www.creativebloq.com/design/image-compression-tools-1132865) that are specialized for this. Lossy compression algorithms are usually more efficient than loss-less ones. **Note:** As compression works better on a specific kind of files, it usually provides nothing to compress them a second time. In fact, this is often counterproductive as the cost of the overhead (algorithms usually need a dictionary that adds to the initial size) can be higher than the extra gain in compression resulting in a larger file. Do not use the two following techniques for files in a compressed format. End-to-end compression ---------------------- For compression, end-to-end compression is where the largest performance improvements of Web sites reside. End-to-end compression refers to a compression of the body of a message that is done by the server and will last unchanged until it reaches the client. Whatever the intermediate nodes are, they leave the body untouched. All modern browsers and servers do support it and the only thing to negotiate is the compression algorithm to use. These algorithms are optimized for text. In the 1990s, compression technology was advancing at a rapid pace and numerous successive algorithms have been added to the set of possible choices. Nowadays, only two are relevant: `gzip`, the most common one, and `br` the new challenger. To select the algorithm to use, browsers and servers use [proactive content negotiation](content_negotiation). The browser sends an [`Accept-Encoding`](headers/accept-encoding) header with the algorithm it supports and its order of precedence, the server picks one, uses it to compress the body of the response and uses the [`Content-Encoding`](headers/content-encoding) header to tell the browser the algorithm it has chosen. As content negotiation has been used to choose a representation based on its encoding, the server must send a [`Vary`](headers/vary) header containing at least [`Accept-Encoding`](headers/accept-encoding) alongside this header in the response; that way, caches will be able to cache the different representations of the resource. As compression brings significant performance improvements, it is recommended to activate it for all files, but already compressed ones like images, audio files and videos. Apache supports compression and uses [mod\_deflate](https://httpd.apache.org/docs/current/mod/mod_deflate.html); for Nginx there is [ngx\_http\_gzip\_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html); for IIS, the [`<httpCompression>`](https://docs.microsoft.com/iis/configuration/system.webServer/httpCompression/) element. Hop-by-hop compression ---------------------- Hop-by-hop compression, though similar to end-to-end compression, differs by one fundamental element: the compression doesn't happen on the resource in the server, creating a specific representation that is then transmitted, but on the body of the message between any two nodes on the path between the client and the server. Connections between successive intermediate nodes may apply a *different* compression. To do this, HTTP uses a mechanism similar to the content negotiation for end-to-end compression: the node transmitting the request advertizes its will using the [`TE`](headers/te) header and the other node chooses the adequate method, applies it, and indicates its choice with the [`Transfer-Encoding`](headers/transfer-encoding) header. In practice, hop-by-hop compression is transparent for the server and the client, and is rarely used. [`TE`](headers/te) and [`Transfer-Encoding`](headers/transfer-encoding) are mostly used to send a response by chunks, allowing to start transmitting a resource without knowing its length. Note that using [`Transfer-Encoding`](headers/transfer-encoding) and compression at the hop level is so rare that most servers, like Apache, Nginx, or IIS, have no easy way to configure it. Such configuration usually happens at the proxy level. http HTTP/1.1 Internet Engineering Task Force (IETF) R. Fielding, Ed. Request for Comments: 9112 Adobe STD: 99 M. Nottingham, Ed. Obsoletes: [7230](https://datatracker.ietf.org/doc/html/rfc7230) Fastly Category: Standards Track J. Reschke, Ed. ISSN: 2070-1721 greenbytes June 2022 HTTP/1.1 ======== Abstract The Hypertext Transfer Protocol (HTTP) is a stateless application- level protocol for distributed, collaborative, hypertext information systems. This document specifies the HTTP/1.1 message syntax, message parsing, connection management, and related security concerns. This document obsoletes portions of [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230). Status of This Memo This is an Internet Standards Track document. This document is a product of the Internet Engineering Task Force (IETF). It represents the consensus of the IETF community. It has received public review and has been approved for publication by the Internet Engineering Steering Group (IESG). Further information on Internet Standards is available in [Section 2 of RFC 7841](https://datatracker.ietf.org/doc/html/rfc7841#section-2). Information about the current status of this document, any errata, and how to provide feedback on it may be obtained at <https://www.rfc-editor.org/info/rfc9112>. Copyright Notice Copyright (c) 2022 IETF Trust and the persons identified as the document authors. All rights reserved. This document is subject to [BCP 78](https://datatracker.ietf.org/doc/html/bcp78) and the IETF Trust's Legal Provisions Relating to IETF Documents (<https://trustee.ietf.org/license-info>) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Revised BSD License text as described in [Section 4](#section-4).e of the Trust Legal Provisions and are provided without warranty as described in the Revised BSD License. This document may contain material from IETF Documents or IETF Contributions published or made publicly available before November 10, 2008. The person(s) controlling the copyright in some of this material may not have granted the IETF Trust the right to allow modifications of such material outside the IETF Standards Process. Without obtaining an adequate license from the person(s) controlling the copyright in such materials, this document may not be modified outside the IETF Standards Process, and derivative works of it may not be created outside the IETF Standards Process, except to format it for publication as an RFC or to translate it into languages other than English. Table of Contents 1. Introduction 1.1. Requirements Notation 1.2. Syntax Notation 2. Message 2.1. Message Format 2.2. Message Parsing 2.3. HTTP Version 3. Request Line 3.1. Method 3.2. Request Target 3.2.1. origin-form 3.2.2. absolute-form 3.2.3. authority-form 3.2.4. asterisk-form 3.3. Reconstructing the Target URI 4. Status Line 5. Field Syntax 5.1. Field Line Parsing 5.2. Obsolete Line Folding 6. Message Body 6.1. Transfer-Encoding 6.2. Content-Length 6.3. Message Body Length 7. Transfer Codings 7.1. Chunked Transfer Coding 7.1.1. Chunk Extensions 7.1.2. Chunked Trailer [Section](#section-7.1.3) [7.1.3](#section-7.1.3). Decoding Chunked 7.2. Transfer Codings for Compression 7.3. Transfer Coding Registry 7.4. Negotiating Transfer Codings 8. Handling Incomplete Messages 9. Connection Management 9.1. Establishment 9.2. Associating a Response to a Request 9.3. Persistence 9.3.1. Retrying Requests 9.3.2. Pipelining 9.4. Concurrency 9.5. Failures and Timeouts 9.6. Tear-down 9.7. TLS Connection Initiation 9.8. TLS Connection Closure 10. Enclosing Messages as Data 10.1. Media Type message/http 10.2. Media Type application/http 11. Security Considerations 11.1. Response Splitting 11.2. Request Smuggling 11.3. Message Integrity 11.4. Message Confidentiality 12. IANA Considerations 12.1. Field Name Registration 12.2. Media Type Registration 12.3. Transfer Coding Registration 12.4. ALPN Protocol ID Registration 13. References 13.1. Normative References 13.2. Informative References [Appendix A](#appendix-A). Collected ABNF [Appendix B](#appendix-B). Differences between HTTP and MIME B.1. MIME-Version B.2. Conversion to Canonical Form B.3. Conversion of Date Formats B.4. Conversion of Content-Encoding B.5. Conversion of Content-Transfer-Encoding B.6. MHTML and Line Length Limitations [Appendix C](#appendix-C). Changes from Previous RFCs C.1. Changes from HTTP/0.9 C.2. Changes from HTTP/1.0 C.2.1. Multihomed Web Servers C.2.2. Keep-Alive Connections C.2.3. Introduction of Transfer-Encoding C.3. Changes from [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230) Acknowledgements Index Authors' Addresses 1. Introduction --------------- The Hypertext Transfer Protocol (HTTP) is a stateless application- level request/response protocol that uses extensible semantics and self-descriptive messages for flexible interaction with network-based hypertext information systems. HTTP/1.1 is defined by: \* This document \* "HTTP Semantics" [[HTTP](#ref-HTTP)] \* "HTTP Caching" [[CACHING](#ref-CACHING)] This document specifies how HTTP semantics are conveyed using the HTTP/1.1 message syntax, framing, and connection management mechanisms. Its goal is to define the complete set of requirements for HTTP/1.1 message parsers and message-forwarding intermediaries. This document obsoletes the portions of [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230) related to HTTP/1.1 messaging and connection management, with the changes being summarized in [Appendix C.3](#appendix-C.3). The other parts of [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230) are obsoleted by "HTTP Semantics" [[HTTP](#ref-HTTP)]. ### 1.1. Requirements Notation The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://datatracker.ietf.org/doc/html/bcp14) [[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)] [[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when, and only when, they appear in all capitals, as shown here. Conformance criteria and considerations regarding error handling are defined in Section 2 of [[HTTP](#ref-HTTP)]. ### 1.2. Syntax Notation This specification uses the Augmented Backus-Naur Form (ABNF) notation of [[RFC5234](https://datatracker.ietf.org/doc/html/rfc5234)], extended with the notation for case- sensitivity in strings defined in [[RFC7405](https://datatracker.ietf.org/doc/html/rfc7405)]. It also uses a list extension, defined in Section 5.6.1 of [[HTTP](#ref-HTTP)], that allows for compact definition of comma-separated lists using a "#" operator (similar to how the "\*" operator indicates repetition). [Appendix A](#appendix-A) shows the collected grammar with all list operators expanded to standard ABNF notation. As a convention, ABNF rule names prefixed with "obs-" denote obsolete grammar rules that appear for historical reasons. The following core rules are included by reference, as defined in [[RFC5234], Appendix B.1](https://datatracker.ietf.org/doc/html/rfc5234#appendix-B.1): ALPHA (letters), CR (carriage return), CRLF (CR LF), CTL (controls), DIGIT (decimal 0-9), DQUOTE (double quote), HEXDIG (hexadecimal 0-9/A-F/a-f), HTAB (horizontal tab), LF (line feed), OCTET (any 8-bit sequence of data), SP (space), and VCHAR (any visible [[USASCII](#ref-USASCII)] character). The rules below are defined in [[HTTP](#ref-HTTP)]: BWS = <BWS, see [[HTTP](#ref-HTTP)], Section 5.6.3> OWS = <OWS, see [[HTTP](#ref-HTTP)], Section 5.6.3> RWS = <RWS, see [[HTTP](#ref-HTTP)], Section 5.6.3> absolute-path = <absolute-path, see [[HTTP](#ref-HTTP)], Section 4.1> field-name = <field-name, see [[HTTP](#ref-HTTP)], Section 5.1> field-value = <field-value, see [[HTTP](#ref-HTTP)], Section 5.5> obs-text = <obs-text, see [[HTTP](#ref-HTTP)], Section 5.6.4> quoted-string = <quoted-string, see [[HTTP](#ref-HTTP)], Section 5.6.4> token = <token, see [[HTTP](#ref-HTTP)], Section 5.6.2> transfer-coding = <transfer-coding, see [[HTTP](#ref-HTTP)], Section 10.1.4> The rules below are defined in [[URI](#ref-URI)]: absolute-URI = <absolute-URI, see [[URI](#ref-URI)], Section 4.3> authority = <authority, see [[URI](#ref-URI)], Section 3.2> uri-host = <host, see [[URI](#ref-URI)], Section 3.2.2> port = <port, see [[URI](#ref-URI)], Section 3.2.3> query = <query, see [[URI](#ref-URI)], Section 3.4> 2. Message ---------- HTTP/1.1 clients and servers communicate by sending messages. See Section 3 of [[HTTP](#ref-HTTP)] for the general terminology and core concepts of HTTP. ### 2.1. Message Format An HTTP/1.1 message consists of a start-line followed by a CRLF and a sequence of octets in a format similar to the Internet Message Format [[RFC5322](https://datatracker.ietf.org/doc/html/rfc5322)]: zero or more header field lines (collectively referred to as the "headers" or the "header section"), an empty line indicating the end of the header section, and an optional message body. HTTP-message = start-line CRLF \*( field-line CRLF ) CRLF [ message-body ] A message can be either a request from client to server or a response from server to client. Syntactically, the two types of messages differ only in the start-line, which is either a request-line (for requests) or a status-line (for responses), and in the algorithm for determining the length of the message body ([Section 6](#section-6)). start-line = request-line / status-line In theory, a client could receive requests and a server could receive responses, distinguishing them by their different start-line formats. In practice, servers are implemented to only expect a request (a response is interpreted as an unknown or invalid request method), and clients are implemented to only expect a response. HTTP makes use of some protocol elements similar to the Multipurpose Internet Mail Extensions (MIME) [[RFC2045](https://datatracker.ietf.org/doc/html/rfc2045)]. See [Appendix B](#appendix-B) for the differences between HTTP and MIME messages. ### 2.2. Message Parsing The normal procedure for parsing an HTTP message is to read the start-line into a structure, read each header field line into a hash table by field name until the empty line, and then use the parsed data to determine if a message body is expected. If a message body has been indicated, then it is read as a stream until an amount of octets equal to the message body length is read or the connection is closed. A recipient MUST parse an HTTP message as a sequence of octets in an encoding that is a superset of US-ASCII [[USASCII](#ref-USASCII)]. Parsing an HTTP message as a stream of Unicode characters, without regard for the specific encoding, creates security vulnerabilities due to the varying ways that string processing libraries handle invalid multibyte character sequences that contain the octet LF (%x0A). String-based parsers can only be safely used within protocol elements after the element has been extracted from the message, such as within a header field line value after message parsing has delineated the individual field lines. Although the line terminator for the start-line and fields is the sequence CRLF, a recipient MAY recognize a single LF as a line terminator and ignore any preceding CR. A sender MUST NOT generate a bare CR (a CR character not immediately followed by LF) within any protocol elements other than the content. A recipient of such a bare CR MUST consider that element to be invalid or replace each bare CR with SP before processing the element or forwarding the message. Older HTTP/1.0 user agent implementations might send an extra CRLF after a POST request as a workaround for some early server applications that failed to read message body content that was not terminated by a line-ending. An HTTP/1.1 user agent MUST NOT preface or follow a request with an extra CRLF. If terminating the request message body with a line-ending is desired, then the user agent MUST count the terminating CRLF octets as part of the message body length. In the interest of robustness, a server that is expecting to receive and parse a request-line SHOULD ignore at least one empty line (CRLF) received prior to the request-line. A sender MUST NOT send whitespace between the start-line and the first header field. A recipient that receives whitespace between the start-line and the first header field MUST either reject the message as invalid or consume each whitespace-preceded line without further processing of it (i.e., ignore the entire line, along with any subsequent lines preceded by whitespace, until a properly formed header field is received or the header section is terminated). Rejection or removal of invalid whitespace-preceded lines is necessary to prevent their misinterpretation by downstream recipients that might be vulnerable to request smuggling ([Section 11.2](#section-11.2)) or response splitting ([Section 11.1](#section-11.1)) attacks. When a server listening only for HTTP request messages, or processing what appears from the start-line to be an HTTP request message, receives a sequence of octets that does not match the HTTP-message grammar aside from the robustness exceptions listed above, the server SHOULD respond with a 400 (Bad Request) response and close the connection. ### 2.3. HTTP Version HTTP uses a "<major>.<minor>" numbering scheme to indicate versions of the protocol. This specification defines version "1.1". Section 2.5 of [[HTTP](#ref-HTTP)] specifies the semantics of HTTP version numbers. The version of an HTTP/1.x message is indicated by an HTTP-version field in the start-line. HTTP-version is case-sensitive. HTTP-version = HTTP-name "/" DIGIT "." DIGIT HTTP-name = %s"HTTP" When an HTTP/1.1 message is sent to an HTTP/1.0 recipient [HTTP/1.0] or a recipient whose version is unknown, the HTTP/1.1 message is constructed such that it can be interpreted as a valid HTTP/1.0 message if all of the newer features are ignored. This specification places recipient-version requirements on some new features so that a conformant sender will only use compatible features until it has determined, through configuration or the receipt of a message, that the recipient supports HTTP/1.1. Intermediaries that process HTTP messages (i.e., all intermediaries other than those acting as tunnels) MUST send their own HTTP-version in forwarded messages, unless it is purposefully downgraded as a workaround for an upstream issue. In other words, an intermediary is not allowed to blindly forward the start-line without ensuring that the protocol version in that message matches a version to which that intermediary is conformant for both the receiving and sending of messages. Forwarding an HTTP message without rewriting the HTTP- version might result in communication errors when downstream recipients use the message sender's version to determine what features are safe to use for later communication with that sender. A server MAY send an HTTP/1.0 response to an HTTP/1.1 request if it is known or suspected that the client incorrectly implements the HTTP specification and is incapable of correctly processing later version responses, such as when a client fails to parse the version number correctly or when an intermediary is known to blindly forward the HTTP-version even when it doesn't conform to the given minor version of the protocol. Such protocol downgrades SHOULD NOT be performed unless triggered by specific client attributes, such as when one or more of the request header fields (e.g., User-Agent) uniquely match the values sent by a client known to be in error. 3. Request Line --------------- A request-line begins with a method token, followed by a single space (SP), the request-target, and another single space (SP), and ends with the protocol version. request-line = method SP request-target SP HTTP-version Although the request-line grammar rule requires that each of the component elements be separated by a single SP octet, recipients MAY instead parse on whitespace-delimited word boundaries and, aside from the CRLF terminator, treat any form of whitespace as the SP separator while ignoring preceding or trailing whitespace; such whitespace includes one or more of the following octets: SP, HTAB, VT (%x0B), FF (%x0C), or bare CR. However, lenient parsing can result in request smuggling security vulnerabilities if there are multiple recipients of the message and each has its own unique interpretation of robustness (see [Section 11.2](#section-11.2)). HTTP does not place a predefined limit on the length of a request- line, as described in Section 2.3 of [[HTTP](#ref-HTTP)]. A server that receives a method longer than any that it implements SHOULD respond with a 501 (Not Implemented) status code. A server that receives a request- target longer than any URI it wishes to parse MUST respond with a 414 (URI Too Long) status code (see Section 15.5.15 of [[HTTP](#ref-HTTP)]). Various ad hoc limitations on request-line length are found in practice. It is RECOMMENDED that all HTTP senders and recipients support, at a minimum, request-line lengths of 8000 octets. ### 3.1. Method The method token indicates the request method to be performed on the target resource. The request method is case-sensitive. method = token The request methods defined by this specification can be found in Section 9 of [[HTTP](#ref-HTTP)], along with information regarding the HTTP method registry and considerations for defining new methods. ### 3.2. Request Target The request-target identifies the target resource upon which to apply the request. The client derives a request-target from its desired target URI. There are four distinct formats for the request-target, depending on both the method being requested and whether the request is to a proxy. request-target = origin-form / absolute-form / authority-form / asterisk-form No whitespace is allowed in the request-target. Unfortunately, some user agents fail to properly encode or exclude whitespace found in hypertext references, resulting in those disallowed characters being sent as the request-target in a malformed request-line. Recipients of an invalid request-line SHOULD respond with either a 400 (Bad Request) error or a 301 (Moved Permanently) redirect with the request-target properly encoded. A recipient SHOULD NOT attempt to autocorrect and then process the request without a redirect, since the invalid request-line might be deliberately crafted to bypass security filters along the request chain. A client MUST send a Host header field (Section 7.2 of [[HTTP](#ref-HTTP)]) in all HTTP/1.1 request messages. If the target URI includes an authority component, then a client MUST send a field value for Host that is identical to that authority component, excluding any userinfo subcomponent and its "@" delimiter (Section 4.2 of [[HTTP](#ref-HTTP)]). If the authority component is missing or undefined for the target URI, then a client MUST send a Host header field with an empty field value. A server MUST respond with a 400 (Bad Request) status code to any HTTP/1.1 request message that lacks a Host header field and to any request message that contains more than one Host header field line or a Host header field with an invalid field value. #### 3.2.1. origin-form The most common form of request-target is the "origin-form". origin-form = absolute-path [ "?" query ] When making a request directly to an origin server, other than a CONNECT or server-wide OPTIONS request (as detailed below), a client MUST send only the absolute path and query components of the target URI as the request-target. If the target URI's path component is empty, the client MUST send "/" as the path within the origin-form of request-target. A Host header field is also sent, as defined in Section 7.2 of [[HTTP](#ref-HTTP)]. For example, a client wishing to retrieve a representation of the resource identified as http://www.example.org/where?q=now directly from the origin server would open (or reuse) a TCP connection to port 80 of the host "www.example.org" and send the lines: GET /where?q=now HTTP/1.1 Host: www.example.org followed by the remainder of the request message. #### 3.2.2. absolute-form When making a request to a proxy, other than a CONNECT or server-wide OPTIONS request (as detailed below), a client MUST send the target URI in "absolute-form" as the request-target. absolute-form = absolute-URI The proxy is requested to either service that request from a valid cache, if possible, or make the same request on the client's behalf either to the next inbound proxy server or directly to the origin server indicated by the request-target. Requirements on such "forwarding" of messages are defined in Section 7.6 of [[HTTP](#ref-HTTP)]. An example absolute-form of request-line would be: GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1 A client MUST send a Host header field in an HTTP/1.1 request even if the request-target is in the absolute-form, since this allows the Host information to be forwarded through ancient HTTP/1.0 proxies that might not have implemented Host. When a proxy receives a request with an absolute-form of request- target, the proxy MUST ignore the received Host header field (if any) and instead replace it with the host information of the request- target. A proxy that forwards such a request MUST generate a new Host field value based on the received request-target rather than forward the received Host field value. When an origin server receives a request with an absolute-form of request-target, the origin server MUST ignore the received Host header field (if any) and instead use the host information of the request-target. Note that if the request-target does not have an authority component, an empty Host header field will be sent in this case. A server MUST accept the absolute-form in requests even though most HTTP/1.1 clients will only send the absolute-form to a proxy. #### 3.2.3. authority-form The "authority-form" of request-target is only used for CONNECT requests (Section 9.3.6 of [[HTTP](#ref-HTTP)]). It consists of only the uri-host and port number of the tunnel destination, separated by a colon (":"). authority-form = uri-host ":" port When making a CONNECT request to establish a tunnel through one or more proxies, a client MUST send only the host and port of the tunnel destination as the request-target. The client obtains the host and port from the target URI's authority component, except that it sends the scheme's default port if the target URI elides the port. For example, a CONNECT request to "http://www.example.com" looks like the following: CONNECT www.example.com:80 HTTP/1.1 Host: www.example.com #### 3.2.4. asterisk-form The "asterisk-form" of request-target is only used for a server-wide OPTIONS request (Section 9.3.7 of [[HTTP](#ref-HTTP)]). asterisk-form = "\*" When a client wishes to request OPTIONS for the server as a whole, as opposed to a specific named resource of that server, the client MUST send only "\*" (%x2A) as the request-target. For example, OPTIONS \* HTTP/1.1 If a proxy receives an OPTIONS request with an absolute-form of request-target in which the URI has an empty path and no query component, then the last proxy on the request chain MUST send a request-target of "\*" when it forwards the request to the indicated origin server. For example, the request OPTIONS <http://www.example.org:8001> HTTP/1.1 would be forwarded by the final proxy as OPTIONS \* HTTP/1.1 Host: www.example.org:8001 after connecting to port 8001 of host "www.example.org". ### 3.3. Reconstructing the Target URI The target URI is the request-target when the request-target is in absolute-form. In that case, a server will parse the URI into its generic components for further evaluation. Otherwise, the server reconstructs the target URI from the connection context and various parts of the request message in order to identify the target resource (Section 7.1 of [[HTTP](#ref-HTTP)]): \* If the server's configuration provides for a fixed URI scheme, or a scheme is provided by a trusted outbound gateway, that scheme is used for the target URI. This is common in large-scale deployments because a gateway server will receive the client's connection context and replace that with their own connection to the inbound server. Otherwise, if the request is received over a secured connection, the target URI's scheme is "https"; if not, the scheme is "http". \* If the request-target is in authority-form, the target URI's authority component is the request-target. Otherwise, the target URI's authority component is the field value of the Host header field. If there is no Host header field or if its field value is empty or invalid, the target URI's authority component is empty. \* If the request-target is in authority-form or asterisk-form, the target URI's combined path and query component is empty. Otherwise, the target URI's combined path and query component is the request-target. \* The components of a reconstructed target URI, once determined as above, can be recombined into absolute-URI form by concatenating the scheme, "://", authority, and combined path and query component. Example 1: The following message received over a secure connection GET /pub/WWW/TheProject.html HTTP/1.1 Host: www.example.org has a target URI of https://www.example.org/pub/WWW/TheProject.html Example 2: The following message received over an insecure connection OPTIONS \* HTTP/1.1 Host: www.example.org:8080 has a target URI of <http://www.example.org:8080> If the target URI's authority component is empty and its URI scheme requires a non-empty authority (as is the case for "http" and "https"), the server can reject the request or determine whether a configured default applies that is consistent with the incoming connection's context. Context might include connection details like address and port, what security has been applied, and locally defined information specific to that server's configuration. An empty authority is replaced with the configured default before further processing of the request. Supplying a default name for authority within the context of a secured connection is inherently unsafe if there is any chance that the user agent's intended authority might differ from the default. A server that can uniquely identify an authority from the request context MAY use that identity as a default without this risk. Alternatively, it might be better to redirect the request to a safe resource that explains how to obtain a new client. Note that reconstructing the client's target URI is only half of the process for identifying a target resource. The other half is determining whether that target URI identifies a resource for which the server is willing and able to send a response, as defined in Section 7.4 of [[HTTP](#ref-HTTP)]. 4. Status Line -------------- The first line of a response message is the status-line, consisting of the protocol version, a space (SP), the status code, and another space and ending with an OPTIONAL textual phrase describing the status code. status-line = HTTP-version SP status-code SP [ reason-phrase ] Although the status-line grammar rule requires that each of the component elements be separated by a single SP octet, recipients MAY instead parse on whitespace-delimited word boundaries and, aside from the line terminator, treat any form of whitespace as the SP separator while ignoring preceding or trailing whitespace; such whitespace includes one or more of the following octets: SP, HTAB, VT (%x0B), FF (%x0C), or bare CR. However, lenient parsing can result in response splitting security vulnerabilities if there are multiple recipients of the message and each has its own unique interpretation of robustness (see [Section 11.1](#section-11.1)). The status-code element is a 3-digit integer code describing the result of the server's attempt to understand and satisfy the client's corresponding request. A recipient parses and interprets the remainder of the response message in light of the semantics defined for that status code, if the status code is recognized by that recipient, or in accordance with the class of that status code when the specific code is unrecognized. status-code = 3DIGIT HTTP's core status codes are defined in Section 15 of [[HTTP](#ref-HTTP)], along with the classes of status codes, considerations for the definition of new status codes, and the IANA registry for collecting such definitions. The reason-phrase element exists for the sole purpose of providing a textual description associated with the numeric status code, mostly out of deference to earlier Internet application protocols that were more frequently used with interactive text clients. reason-phrase = 1\*( HTAB / SP / VCHAR / obs-text ) A client SHOULD ignore the reason-phrase content because it is not a reliable channel for information (it might be translated for a given locale, overwritten by intermediaries, or discarded when the message is forwarded via other versions of HTTP). A server MUST send the space that separates the status-code from the reason-phrase even when the reason-phrase is absent (i.e., the status-line would end with the space). 5. Field Syntax --------------- Each field line consists of a case-insensitive field name followed by a colon (":"), optional leading whitespace, the field line value, and optional trailing whitespace. field-line = field-name ":" OWS field-value OWS Rules for parsing within field values are defined in Section 5.5 of [[HTTP](#ref-HTTP)]. This section covers the generic syntax for header field inclusion within, and extraction from, HTTP/1.1 messages. ### 5.1. Field Line Parsing Messages are parsed using a generic algorithm, independent of the individual field names. The contents within a given field line value are not parsed until a later stage of message interpretation (usually after the message's entire field section has been processed). No whitespace is allowed between the field name and colon. In the past, differences in the handling of such whitespace have led to security vulnerabilities in request routing and response handling. A server MUST reject, with a response status code of 400 (Bad Request), any received request message that contains whitespace between a header field name and colon. A proxy MUST remove any such whitespace from a response message before forwarding the message downstream. A field line value might be preceded and/or followed by optional whitespace (OWS); a single SP preceding the field line value is preferred for consistent readability by humans. The field line value does not include that leading or trailing whitespace: OWS occurring before the first non-whitespace octet of the field line value, or after the last non-whitespace octet of the field line value, is excluded by parsers when extracting the field line value from a field line. ### 5.2. Obsolete Line Folding Historically, HTTP/1.x field values could be extended over multiple lines by preceding each extra line with at least one space or horizontal tab (obs-fold). This specification deprecates such line folding except within the "message/http" media type ([Section 10.1](#section-10.1)). obs-fold = OWS CRLF RWS ; obsolete line folding A sender MUST NOT generate a message that includes line folding (i.e., that has any field line value that contains a match to the obs-fold rule) unless the message is intended for packaging within the "message/http" media type. A server that receives an obs-fold in a request message that is not within a "message/http" container MUST either reject the message by sending a 400 (Bad Request), preferably with a representation explaining that obsolete line folding is unacceptable, or replace each received obs-fold with one or more SP octets prior to interpreting the field value or forwarding the message downstream. A proxy or gateway that receives an obs-fold in a response message that is not within a "message/http" container MUST either discard the message and replace it with a 502 (Bad Gateway) response, preferably with a representation explaining that unacceptable line folding was received, or replace each received obs-fold with one or more SP octets prior to interpreting the field value or forwarding the message downstream. A user agent that receives an obs-fold in a response message that is not within a "message/http" container MUST replace each received obs-fold with one or more SP octets prior to interpreting the field value. 6. Message Body --------------- The message body (if any) of an HTTP/1.1 message is used to carry content (Section 6.4 of [[HTTP](#ref-HTTP)]) for the request or response. The message body is identical to the content unless a transfer coding has been applied, as described in [Section 6.1](#section-6.1). message-body = \*OCTET The rules for determining when a message body is present in an HTTP/1.1 message differ for requests and responses. The presence of a message body in a request is signaled by a Content-Length or Transfer-Encoding header field. Request message framing is independent of method semantics. The presence of a message body in a response, as detailed in [Section 6.3](#section-6.3), depends on both the request method to which it is responding and the response status code. This corresponds to when response content is allowed by HTTP semantics (Section 6.4.1 of [[HTTP](#ref-HTTP)]). ### 6.1. Transfer-Encoding The Transfer-Encoding header field lists the transfer coding names corresponding to the sequence of transfer codings that have been (or will be) applied to the content in order to form the message body. Transfer codings are defined in [Section 7](#section-7). Transfer-Encoding = #transfer-coding ; defined in [[HTTP](#ref-HTTP)], Section 10.1.4 Transfer-Encoding is analogous to the Content-Transfer-Encoding field of MIME, which was designed to enable safe transport of binary data over a 7-bit transport service ([[RFC2045], Section 6](https://datatracker.ietf.org/doc/html/rfc2045#section-6)). However, safe transport has a different focus for an 8bit-clean transfer protocol. In HTTP's case, Transfer-Encoding is primarily intended to accurately delimit dynamically generated content. It also serves to distinguish encodings that are only applied in transit from the encodings that are a characteristic of the selected representation. A recipient MUST be able to parse the chunked transfer coding ([Section 7.1](#section-7.1)) because it plays a crucial role in framing messages when the content size is not known in advance. A sender MUST NOT apply the chunked transfer coding more than once to a message body (i.e., chunking an already chunked message is not allowed). If any transfer coding other than chunked is applied to a request's content, the sender MUST apply chunked as the final transfer coding to ensure that the message is properly framed. If any transfer coding other than chunked is applied to a response's content, the sender MUST either apply chunked as the final transfer coding or terminate the message by closing the connection. For example, Transfer-Encoding: gzip, chunked indicates that the content has been compressed using the gzip coding and then chunked using the chunked coding while forming the message body. Unlike Content-Encoding (Section 8.4.1 of [[HTTP](#ref-HTTP)]), Transfer-Encoding is a property of the message, not of the representation. Any recipient along the request/response chain MAY decode the received transfer coding(s) or apply additional transfer coding(s) to the message body, assuming that corresponding changes are made to the Transfer-Encoding field value. Additional information about the encoding parameters can be provided by other header fields not defined by this specification. Transfer-Encoding MAY be sent in a response to a HEAD request or in a 304 (Not Modified) response (Section 15.4.5 of [[HTTP](#ref-HTTP)]) to a GET request, neither of which includes a message body, to indicate that the origin server would have applied a transfer coding to the message body if the request had been an unconditional GET. This indication is not required, however, because any recipient on the response chain (including the origin server) can remove transfer codings when they are not needed. A server MUST NOT send a Transfer-Encoding header field in any response with a status code of 1xx (Informational) or 204 (No Content). A server MUST NOT send a Transfer-Encoding header field in any 2xx (Successful) response to a CONNECT request (Section 9.3.6 of [[HTTP](#ref-HTTP)]). A server that receives a request message with a transfer coding it does not understand SHOULD respond with 501 (Not Implemented). Transfer-Encoding was added in HTTP/1.1. It is generally assumed that implementations advertising only HTTP/1.0 support will not understand how to process transfer-encoded content, and that an HTTP/1.0 message received with a Transfer-Encoding is likely to have been forwarded without proper handling of the chunked transfer coding in transit. A client MUST NOT send a request containing Transfer-Encoding unless it knows the server will handle HTTP/1.1 requests (or later minor revisions); such knowledge might be in the form of specific user configuration or by remembering the version of a prior received response. A server MUST NOT send a response containing Transfer- Encoding unless the corresponding request indicates HTTP/1.1 (or later minor revisions). Early implementations of Transfer-Encoding would occasionally send both a chunked transfer coding for message framing and an estimated Content-Length header field for use by progress bars. This is why Transfer-Encoding is defined as overriding Content-Length, as opposed to them being mutually incompatible. Unfortunately, forwarding such a message can lead to vulnerabilities regarding request smuggling ([Section 11.2](#section-11.2)) or response splitting ([Section 11.1](#section-11.1)) attacks if any downstream recipient fails to parse the message according to this specification, particularly when a downstream recipient only implements HTTP/1.0. A server MAY reject a request that contains both Content-Length and Transfer-Encoding or process such a request in accordance with the Transfer-Encoding alone. Regardless, the server MUST close the connection after responding to such a request to avoid the potential attacks. A server or client that receives an HTTP/1.0 message containing a Transfer-Encoding header field MUST treat the message as if the framing is faulty, even if a Content-Length is present, and close the connection after processing the message. The message sender might have retained a portion of the message, in buffer, that could be misinterpreted by further use of the connection. ### 6.2. Content-Length When a message does not have a Transfer-Encoding header field, a Content-Length header field (Section 8.6 of [[HTTP](#ref-HTTP)]) can provide the anticipated size, as a decimal number of octets, for potential content. For messages that do include content, the Content-Length field value provides the framing information necessary for determining where the data (and message) ends. For messages that do not include content, the Content-Length indicates the size of the selected representation (Section 8.6 of [[HTTP](#ref-HTTP)]). A sender MUST NOT send a Content-Length header field in any message that contains a Transfer-Encoding header field. | \*Note:\* HTTP's use of Content-Length for message framing | differs significantly from the same field's use in MIME, where | it is an optional field used only within the "message/external- | body" media-type. ### 6.3. Message Body Length The length of a message body is determined by one of the following (in order of precedence): 1. Any response to a HEAD request and any response with a 1xx (Informational), 204 (No Content), or 304 (Not Modified) status code is always terminated by the first empty line after the header fields, regardless of the header fields present in the message, and thus cannot contain a message body or trailer section. 2. Any 2xx (Successful) response to a CONNECT request implies that the connection will become a tunnel immediately after the empty line that concludes the header fields. A client MUST ignore any Content-Length or Transfer-Encoding header fields received in such a message. 3. If a message is received with both a Transfer-Encoding and a Content-Length header field, the Transfer-Encoding overrides the Content-Length. Such a message might indicate an attempt to perform request smuggling ([Section 11.2](#section-11.2)) or response splitting ([Section 11.1](#section-11.1)) and ought to be handled as an error. An intermediary that chooses to forward the message MUST first remove the received Content-Length field and process the Transfer-Encoding (as described below) prior to forwarding the message downstream. 4. If a Transfer-Encoding header field is present and the chunked transfer coding ([Section 7.1](#section-7.1)) is the final encoding, the message body length is determined by reading and decoding the chunked data until the transfer coding indicates the data is complete. If a Transfer-Encoding header field is present in a response and the chunked transfer coding is not the final encoding, the message body length is determined by reading the connection until it is closed by the server. If a Transfer-Encoding header field is present in a request and the chunked transfer coding is not the final encoding, the message body length cannot be determined reliably; the server MUST respond with the 400 (Bad Request) status code and then close the connection. 5. If a message is received without Transfer-Encoding and with an invalid Content-Length header field, then the message framing is invalid and the recipient MUST treat it as an unrecoverable error, unless the field value can be successfully parsed as a comma-separated list (Section 5.6.1 of [[HTTP](#ref-HTTP)]), all values in the list are valid, and all values in the list are the same (in which case, the message is processed with that single value used as the Content-Length field value). If the unrecoverable error is in a request message, the server MUST respond with a 400 (Bad Request) status code and then close the connection. If it is in a response message received by a proxy, the proxy MUST close the connection to the server, discard the received response, and send a 502 (Bad Gateway) response to the client. If it is in a response message received by a user agent, the user agent MUST close the connection to the server and discard the received response. 6. If a valid Content-Length header field is present without Transfer-Encoding, its decimal value defines the expected message body length in octets. If the sender closes the connection or the recipient times out before the indicated number of octets are received, the recipient MUST consider the message to be incomplete and close the connection. 7. If this is a request message and none of the above are true, then the message body length is zero (no message body is present). 8. Otherwise, this is a response message without a declared message body length, so the message body length is determined by the number of octets received prior to the server closing the connection. Since there is no way to distinguish a successfully completed, close- delimited response message from a partially received message interrupted by network failure, a server SHOULD generate encoding or length-delimited messages whenever possible. The close-delimiting feature exists primarily for backwards compatibility with HTTP/1.0. | \*Note:\* Request messages are never close-delimited because they | are always explicitly framed by length or transfer coding, with | the absence of both implying the request ends immediately after | the header section. A server MAY reject a request that contains a message body but not a Content-Length by responding with 411 (Length Required). Unless a transfer coding other than chunked has been applied, a client that sends a request containing a message body SHOULD use a valid Content-Length header field if the message body length is known in advance, rather than the chunked transfer coding, since some existing services respond to chunked with a 411 (Length Required) status code even though they understand the chunked transfer coding. This is typically because such services are implemented via a gateway that requires a content length in advance of being called, and the server is unable or unwilling to buffer the entire request before processing. A user agent that sends a request that contains a message body MUST send either a valid Content-Length header field or use the chunked transfer coding. A client MUST NOT use the chunked transfer coding unless it knows the server will handle HTTP/1.1 (or later) requests; such knowledge can be in the form of specific user configuration or by remembering the version of a prior received response. If the final response to the last request on a connection has been completely received and there remains additional data to read, a user agent MAY discard the remaining data or attempt to determine if that data belongs as part of the prior message body, which might be the case if the prior message's Content-Length value is incorrect. A client MUST NOT process, cache, or forward such extra data as a separate response, since such behavior would be vulnerable to cache poisoning. 7. Transfer Codings ------------------- Transfer coding names are used to indicate an encoding transformation that has been, can be, or might need to be applied to a message's content in order to ensure "safe transport" through the network. This differs from a content coding in that the transfer coding is a property of the message rather than a property of the representation that is being transferred. All transfer-coding names are case-insensitive and ought to be registered within the HTTP Transfer Coding registry, as defined in [Section 7.3](#section-7.3). They are used in the Transfer-Encoding ([Section 6.1](#section-6.1)) and TE (Section 10.1.4 of [[HTTP](#ref-HTTP)]) header fields (the latter also defining the "transfer-coding" grammar). ### 7.1. Chunked Transfer Coding The chunked transfer coding wraps content in order to transfer it as a series of chunks, each with its own size indicator, followed by an OPTIONAL trailer section containing trailer fields. Chunked enables content streams of unknown size to be transferred as a sequence of length-delimited buffers, which enables the sender to retain connection persistence and the recipient to know when it has received the entire message. chunked-body = \*chunk last-chunk trailer-section CRLF chunk = chunk-size [ chunk-ext ] CRLF chunk-data CRLF chunk-size = 1\*HEXDIG last-chunk = 1\*("0") [ chunk-ext ] CRLF chunk-data = 1\*OCTET ; a sequence of chunk-size octets The chunk-size field is a string of hex digits indicating the size of the chunk-data in octets. The chunked transfer coding is complete when a chunk with a chunk-size of zero is received, possibly followed by a trailer section, and finally terminated by an empty line. A recipient MUST be able to parse and decode the chunked transfer coding. HTTP/1.1 does not define any means to limit the size of a chunked response such that an intermediary can be assured of buffering the entire response. Additionally, very large chunk sizes may cause overflows or loss of precision if their values are not represented accurately in a receiving implementation. Therefore, recipients MUST anticipate potentially large hexadecimal numerals and prevent parsing errors due to integer conversion overflows or precision loss due to integer representation. The chunked coding does not define any parameters. Their presence SHOULD be treated as an error. #### 7.1.1. Chunk Extensions The chunked coding allows each chunk to include zero or more chunk extensions, immediately following the chunk-size, for the sake of supplying per-chunk metadata (such as a signature or hash), mid- message control information, or randomization of message body size. chunk-ext = \*( BWS ";" BWS chunk-ext-name [ BWS "=" BWS chunk-ext-val ] ) chunk-ext-name = token chunk-ext-val = token / quoted-string The chunked coding is specific to each connection and is likely to be removed or recoded by each recipient (including intermediaries) before any higher-level application would have a chance to inspect the extensions. Hence, the use of chunk extensions is generally limited to specialized HTTP services such as "long polling" (where client and server can have shared expectations regarding the use of chunk extensions) or for padding within an end-to-end secured connection. A recipient MUST ignore unrecognized chunk extensions. A server ought to limit the total length of chunk extensions received in a request to an amount reasonable for the services provided, in the same way that it applies length limitations and timeouts for other parts of a message, and generate an appropriate 4xx (Client Error) response if that amount is exceeded. #### 7.1.2. Chunked Trailer Section A trailer section allows the sender to include additional fields at the end of a chunked message in order to supply metadata that might be dynamically generated while the content is sent, such as a message integrity check, digital signature, or post-processing status. The proper use and limitations of trailer fields are defined in Section 6.5 of [[HTTP](#ref-HTTP)]. trailer-section = \*( field-line CRLF ) A recipient that removes the chunked coding from a message MAY selectively retain or discard the received trailer fields. A recipient that retains a received trailer field MUST either store/ forward the trailer field separately from the received header fields or merge the received trailer field into the header section. A recipient MUST NOT merge a received trailer field into the header section unless its corresponding header field definition explicitly permits and instructs how the trailer field value can be safely merged. #### 7.1.3. Decoding Chunked A process for decoding the chunked transfer coding can be represented in pseudo-code as: length := 0 read chunk-size, chunk-ext (if any), and CRLF while (chunk-size > 0) { read chunk-data and CRLF append chunk-data to content length := length + chunk-size read chunk-size, chunk-ext (if any), and CRLF } read trailer field while (trailer field is not empty) { if (trailer fields are stored/forwarded separately) { append trailer field to existing trailer fields } else if (trailer field is understood and defined as mergeable) { merge trailer field with existing header fields } else { discard trailer field } read trailer field } Content-Length := length Remove "chunked" from Transfer-Encoding ### 7.2. Transfer Codings for Compression The following transfer coding names for compression are defined by the same algorithm as their corresponding content coding: compress (and x-compress) See Section 8.4.1.1 of [[HTTP](#ref-HTTP)]. deflate See Section 8.4.1.2 of [[HTTP](#ref-HTTP)]. gzip (and x-gzip) See Section 8.4.1.3 of [[HTTP](#ref-HTTP)]. The compression codings do not define any parameters. The presence of parameters with any of these compression codings SHOULD be treated as an error. ### 7.3. Transfer Coding Registry The "HTTP Transfer Coding Registry" defines the namespace for transfer coding names. It is maintained at <<https://www.iana.org/assignments/http-parameters>>. Registrations MUST include the following fields: \* Name \* Description \* Pointer to specification text Names of transfer codings MUST NOT overlap with names of content codings (Section 8.4.1 of [[HTTP](#ref-HTTP)]) unless the encoding transformation is identical, as is the case for the compression codings defined in [Section 7.2](#section-7.2). The TE header field (Section 10.1.4 of [[HTTP](#ref-HTTP)]) uses a pseudo- parameter named "q" as the rank value when multiple transfer codings are acceptable. Future registrations of transfer codings SHOULD NOT define parameters called "q" (case-insensitively) in order to avoid ambiguities. Values to be added to this namespace require IETF Review (see [Section 4.8 of [RFC8126]](https://datatracker.ietf.org/doc/html/rfc8126#section-4.8)) and MUST conform to the purpose of transfer coding defined in this specification. Use of program names for the identification of encoding formats is not desirable and is discouraged for future encodings. ### 7.4. Negotiating Transfer Codings The TE field (Section 10.1.4 of [[HTTP](#ref-HTTP)]) is used in HTTP/1.1 to indicate what transfer codings, besides chunked, the client is willing to accept in the response and whether the client is willing to preserve trailer fields in a chunked transfer coding. A client MUST NOT send the chunked transfer coding name in TE; chunked is always acceptable for HTTP/1.1 recipients. Three examples of TE use are below. TE: deflate TE: TE: trailers, deflate;q=0.5 When multiple transfer codings are acceptable, the client MAY rank the codings by preference using a case-insensitive "q" parameter (similar to the qvalues used in content negotiation fields; see Section 12.4.2 of [[HTTP](#ref-HTTP)]). The rank value is a real number in the range 0 through 1, where 0.001 is the least preferred and 1 is the most preferred; a value of 0 means "not acceptable". If the TE field value is empty or if no TE field is present, the only acceptable transfer coding is chunked. A message with no transfer coding is always acceptable. The keyword "trailers" indicates that the sender will not discard trailer fields, as described in Section 6.5 of [[HTTP](#ref-HTTP)]. Since the TE header field only applies to the immediate connection, a sender of TE MUST also send a "TE" connection option within the Connection header field (Section 7.6.1 of [[HTTP](#ref-HTTP)]) in order to prevent the TE header field from being forwarded by intermediaries that do not support its semantics. 8. Handling Incomplete Messages ------------------------------- A server that receives an incomplete request message, usually due to a canceled request or a triggered timeout exception, MAY send an error response prior to closing the connection. A client that receives an incomplete response message, which can occur when a connection is closed prematurely or when decoding a supposedly chunked transfer coding fails, MUST record the message as incomplete. Cache requirements for incomplete responses are defined in Section 3.3 of [[CACHING](#ref-CACHING)]. If a response terminates in the middle of the header section (before the empty line is received) and the status code might rely on header fields to convey the full meaning of the response, then the client cannot assume that meaning has been conveyed; the client might need to repeat the request in order to determine what action to take next. A message body that uses the chunked transfer coding is incomplete if the zero-sized chunk that terminates the encoding has not been received. A message that uses a valid Content-Length is incomplete if the size of the message body received (in octets) is less than the value given by Content-Length. A response that has neither chunked transfer coding nor Content-Length is terminated by closure of the connection and, if the header section was received intact, is considered complete unless an error was indicated by the underlying connection (e.g., an "incomplete close" in TLS would leave the response incomplete, as described in [Section 9.8](#section-9.8)). 9. Connection Management ------------------------ HTTP messaging is independent of the underlying transport- or session-layer connection protocol(s). HTTP only presumes a reliable transport with in-order delivery of requests and the corresponding in-order delivery of responses. The mapping of HTTP request and response structures onto the data units of an underlying transport protocol is outside the scope of this specification. As described in Section 7.3 of [[HTTP](#ref-HTTP)], the specific connection protocols to be used for an HTTP interaction are determined by client configuration and the target URI. For example, the "http" URI scheme (Section 4.2.1 of [[HTTP](#ref-HTTP)]) indicates a default connection of TCP over IP, with a default TCP port of 80, but the client might be configured to use a proxy via some other connection, port, or protocol. HTTP implementations are expected to engage in connection management, which includes maintaining the state of current connections, establishing a new connection or reusing an existing connection, processing messages received on a connection, detecting connection failures, and closing each connection. Most clients maintain multiple connections in parallel, including more than one connection per server endpoint. Most servers are designed to maintain thousands of concurrent connections, while controlling request queues to enable fair use and detect denial-of-service attacks. ### 9.1. Establishment It is beyond the scope of this specification to describe how connections are established via various transport- or session-layer protocols. Each HTTP connection maps to one underlying transport connection. ### 9.2. Associating a Response to a Request HTTP/1.1 does not include a request identifier for associating a given request message with its corresponding one or more response messages. Hence, it relies on the order of response arrival to correspond exactly to the order in which requests are made on the same connection. More than one response message per request only occurs when one or more informational responses (1xx; see Section 15.2 of [[HTTP](#ref-HTTP)]) precede a final response to the same request. A client that has more than one outstanding request on a connection MUST maintain a list of outstanding requests in the order sent and MUST associate each received response message on that connection to the first outstanding request that has not yet received a final (non- 1xx) response. If a client receives data on a connection that doesn't have outstanding requests, the client MUST NOT consider that data to be a valid response; the client SHOULD close the connection, since message delimitation is now ambiguous, unless the data consists only of one or more CRLF (which can be discarded per [Section 2.2](#section-2.2)). ### 9.3. Persistence HTTP/1.1 defaults to the use of "persistent connections", allowing multiple requests and responses to be carried over a single connection. HTTP implementations SHOULD support persistent connections. A recipient determines whether a connection is persistent or not based on the protocol version and Connection header field (Section 7.6.1 of [[HTTP](#ref-HTTP)]) in the most recently received message, if any: \* If the "close" connection option is present ([Section 9.6](#section-9.6)), the connection will not persist after the current response; else, \* If the received protocol is HTTP/1.1 (or later), the connection will persist after the current response; else, \* If the received protocol is HTTP/1.0, the "keep-alive" connection option is present, either the recipient is not a proxy or the message is a response, and the recipient wishes to honor the HTTP/1.0 "keep-alive" mechanism, the connection will persist after the current response; otherwise, \* The connection will close after the current response. A client that does not support persistent connections MUST send the "close" connection option in every request message. A server that does not support persistent connections MUST send the "close" connection option in every response message that does not have a 1xx (Informational) status code. A client MAY send additional requests on a persistent connection until it sends or receives a "close" connection option or receives an HTTP/1.0 response without a "keep-alive" connection option. In order to remain persistent, all messages on a connection need to have a self-defined message length (i.e., one not defined by closure of the connection), as described in [Section 6](#section-6). A server MUST read the entire request message body or close the connection after sending its response; otherwise, the remaining data on a persistent connection would be misinterpreted as the next request. Likewise, a client MUST read the entire response message body if it intends to reuse the same connection for a subsequent request. A proxy server MUST NOT maintain a persistent connection with an HTTP/1.0 client (see [Appendix C.2.2](#appendix-C.2.2) for information and discussion of the problems with the Keep-Alive header field implemented by many HTTP/1.0 clients). See [Appendix C.2.2](#appendix-C.2.2) for more information on backwards compatibility with HTTP/1.0 clients. #### 9.3.1. Retrying Requests Connections can be closed at any time, with or without intention. Implementations ought to anticipate the need to recover from asynchronous close events. The conditions under which a client can automatically retry a sequence of outstanding requests are defined in Section 9.2.2 of [[HTTP](#ref-HTTP)]. #### 9.3.2. Pipelining A client that supports persistent connections MAY "pipeline" its requests (i.e., send multiple requests without waiting for each response). A server MAY process a sequence of pipelined requests in parallel if they all have safe methods (Section 9.2.1 of [[HTTP](#ref-HTTP)]), but it MUST send the corresponding responses in the same order that the requests were received. A client that pipelines requests SHOULD retry unanswered requests if the connection closes before it receives all of the corresponding responses. When retrying pipelined requests after a failed connection (a connection not explicitly closed by the server in its last complete response), a client MUST NOT pipeline immediately after connection establishment, since the first remaining request in the prior pipeline might have caused an error response that can be lost again if multiple requests are sent on a prematurely closed connection (see the TCP reset problem described in [Section 9.6](#section-9.6)). Idempotent methods (Section 9.2.2 of [[HTTP](#ref-HTTP)]) are significant to pipelining because they can be automatically retried after a connection failure. A user agent SHOULD NOT pipeline requests after a non-idempotent method, until the final response status code for that method has been received, unless the user agent has a means to detect and recover from partial failure conditions involving the pipelined sequence. An intermediary that receives pipelined requests MAY pipeline those requests when forwarding them inbound, since it can rely on the outbound user agent(s) to determine what requests can be safely pipelined. If the inbound connection fails before receiving a response, the pipelining intermediary MAY attempt to retry a sequence of requests that have yet to receive a response if the requests all have idempotent methods; otherwise, the pipelining intermediary SHOULD forward any received responses and then close the corresponding outbound connection(s) so that the outbound user agent(s) can recover accordingly. ### 9.4. Concurrency A client ought to limit the number of simultaneous open connections that it maintains to a given server. Previous revisions of HTTP gave a specific number of connections as a ceiling, but this was found to be impractical for many applications. As a result, this specification does not mandate a particular maximum number of connections but, instead, encourages clients to be conservative when opening multiple connections. Multiple connections are typically used to avoid the "head-of-line blocking" problem, wherein a request that takes significant server- side processing and/or transfers very large content would block subsequent requests on the same connection. However, each connection consumes server resources. Furthermore, using multiple connections can cause undesirable side effects in congested networks. Using larger numbers of connections can also cause side effects in otherwise uncongested networks, because their aggregate and initially synchronized sending behavior can cause congestion that would not have been present if fewer parallel connections had been used. Note that a server might reject traffic that it deems abusive or characteristic of a denial-of-service attack, such as an excessive number of open connections from a single client. ### 9.5. Failures and Timeouts Servers will usually have some timeout value beyond which they will no longer maintain an inactive connection. Proxy servers might make this a higher value since it is likely that the client will be making more connections through the same proxy server. The use of persistent connections places no requirements on the length (or existence) of this timeout for either the client or the server. A client or server that wishes to time out SHOULD issue a graceful close on the connection. Implementations SHOULD constantly monitor open connections for a received closure signal and respond to it as appropriate, since prompt closure of both sides of a connection enables allocated system resources to be reclaimed. A client, server, or proxy MAY close the transport connection at any time. For example, a client might have started to send a new request at the same time that the server has decided to close the "idle" connection. From the server's point of view, the connection is being closed while it was idle, but from the client's point of view, a request is in progress. A server SHOULD sustain persistent connections, when possible, and allow the underlying transport's flow-control mechanisms to resolve temporary overloads rather than terminate connections with the expectation that clients will retry. The latter technique can exacerbate network congestion or server load. A client sending a message body SHOULD monitor the network connection for an error response while it is transmitting the request. If the client sees a response that indicates the server does not wish to receive the message body and is closing the connection, the client SHOULD immediately cease transmitting the body and close its side of the connection. ### 9.6. Tear-down The "close" connection option is defined as a signal that the sender will close this connection after completion of the response. A sender SHOULD send a Connection header field (Section 7.6.1 of [[HTTP](#ref-HTTP)]) containing the "close" connection option when it intends to close a connection. For example, Connection: close as a request header field indicates that this is the last request that the client will send on this connection, while in a response, the same field indicates that the server is going to close this connection after the response message is complete. Note that the field name "Close" is reserved, since using that name as a header field might conflict with the "close" connection option. A client that sends a "close" connection option MUST NOT send further requests on that connection (after the one containing the "close") and MUST close the connection after reading the final response message corresponding to this request. A server that receives a "close" connection option MUST initiate closure of the connection (see below) after it sends the final response to the request that contained the "close" connection option. The server SHOULD send a "close" connection option in its final response on that connection. The server MUST NOT process any further requests received on that connection. A server that sends a "close" connection option MUST initiate closure of the connection (see below) after it sends the response containing the "close" connection option. The server MUST NOT process any further requests received on that connection. A client that receives a "close" connection option MUST cease sending requests on that connection and close the connection after reading the response message containing the "close" connection option; if additional pipelined requests had been sent on the connection, the client SHOULD NOT assume that they will be processed by the server. If a server performs an immediate close of a TCP connection, there is a significant risk that the client will not be able to read the last HTTP response. If the server receives additional data from the client on a fully closed connection, such as another request sent by the client before receiving the server's response, the server's TCP stack will send a reset packet to the client; unfortunately, the reset packet might erase the client's unacknowledged input buffers before they can be read and interpreted by the client's HTTP parser. To avoid the TCP reset problem, servers typically close a connection in stages. First, the server performs a half-close by closing only the write side of the read/write connection. The server then continues to read from the connection until it receives a corresponding close by the client, or until the server is reasonably certain that its own TCP stack has received the client's acknowledgement of the packet(s) containing the server's last response. Finally, the server fully closes the connection. It is unknown whether the reset problem is exclusive to TCP or might also be found in other transport connection protocols. Note that a TCP connection that is half-closed by the client does not delimit a request message, nor does it imply that the client is no longer interested in a response. In general, transport signals cannot be relied upon to signal edge cases, since HTTP/1.1 is independent of transport. ### 9.7. TLS Connection Initiation Conceptually, HTTP/TLS is simply sending HTTP messages over a connection secured via TLS [[TLS13](#ref-TLS13)]. The HTTP client also acts as the TLS client. It initiates a connection to the server on the appropriate port and sends the TLS ClientHello to begin the TLS handshake. When the TLS handshake has finished, the client may then initiate the first HTTP request. All HTTP data MUST be sent as TLS "application data" but is otherwise treated like a normal connection for HTTP (including potential reuse as a persistent connection). ### 9.8. TLS Connection Closure TLS uses an exchange of closure alerts prior to (non-error) connection closure to provide secure connection closure; see Section 6.1 of [[TLS13](#ref-TLS13)]. When a valid closure alert is received, an implementation can be assured that no further data will be received on that connection. When an implementation knows that it has sent or received all the message data that it cares about, typically by detecting HTTP message boundaries, it might generate an "incomplete close" by sending a closure alert and then closing the connection without waiting to receive the corresponding closure alert from its peer. An incomplete close does not call into question the security of the data already received, but it could indicate that subsequent data might have been truncated. As TLS is not directly aware of HTTP message framing, it is necessary to examine the HTTP data itself to determine whether messages are complete. Handling of incomplete messages is defined in [Section 8](#section-8). When encountering an incomplete close, a client SHOULD treat as completed all requests for which it has received either 1. as much data as specified in the Content-Length header field or 2. the terminal zero-length chunk (when Transfer-Encoding of chunked is used). A response that has neither chunked transfer coding nor Content- Length is complete only if a valid closure alert has been received. Treating an incomplete message as complete could expose implementations to attack. A client detecting an incomplete close SHOULD recover gracefully. Clients MUST send a closure alert before closing the connection. Clients that do not expect to receive any more data MAY choose not to wait for the server's closure alert and simply close the connection, thus generating an incomplete close on the server side. Servers SHOULD be prepared to receive an incomplete close from the client, since the client can often locate the end of server data. Servers MUST attempt to initiate an exchange of closure alerts with the client before closing the connection. Servers MAY close the connection after sending the closure alert, thus generating an incomplete close on the client side. 10. Enclosing Messages as Data ------------------------------ ### 10.1. Media Type message/http The "message/http" media type can be used to enclose a single HTTP request or response message, provided that it obeys the MIME restrictions for all "message" types regarding line length and encodings. Because of the line length limitations, field values within "message/http" are allowed to use line folding (obs-fold), as described in [Section 5.2](#section-5.2), to convey the field value over multiple lines. A recipient of "message/http" data MUST replace any obsolete line folding with one or more SP characters when the message is consumed. Type name: message Subtype name: http Required parameters: N/A Optional parameters: version, msgtype version: The HTTP-version number of the enclosed message (e.g., "1.1"). If not present, the version can be determined from the first line of the body. msgtype: The message type -- "request" or "response". If not present, the type can be determined from the first line of the body. Encoding considerations: only "7bit", "8bit", or "binary" are permitted Security considerations: see [Section 11](#section-11) Interoperability considerations: N/A Published specification: [RFC 9112](https://datatracker.ietf.org/doc/html/rfc9112) (see [Section 10.1](#section-10.1)). Applications that use this media type: N/A Fragment identifier considerations: N/A Additional information: Magic number(s): N/A Deprecated alias names for this type: N/A File extension(s): N/A Macintosh file type code(s): N/A Person and email address to contact for further information: See Aut hors' Addresses section. Intended usage: COMMON Restrictions on usage: N/A Author: See Authors' Addresses section. Change controller: IESG ### 10.2. Media Type application/http The "application/http" media type can be used to enclose a pipeline of one or more HTTP request or response messages (not intermixed). Type name: application Subtype name: http Required parameters: N/A Optional parameters: version, msgtype version: The HTTP-version number of the enclosed messages (e.g., "1.1"). If not present, the version can be determined from the first line of the body. msgtype: The message type -- "request" or "response". If not present, the type can be determined from the first line of the body. Encoding considerations: HTTP messages enclosed by this type are in "binary" format; use of an appropriate Content-Transfer-Encoding is required when transmitted via email. Security considerations: see [Section 11](#section-11) Interoperability considerations: N/A Published specification: [RFC 9112](https://datatracker.ietf.org/doc/html/rfc9112) (see [Section 10.2](#section-10.2)). Applications that use this media type: N/A Fragment identifier considerations: N/A Additional information: Deprecated alias names for this type: N/A Magic number(s): N/A File extension(s): N/A Macintosh file type code(s): N/A Person and email address to contact for further information: See Aut hors' Addresses section. Intended usage: COMMON Restrictions on usage: N/A Author: See Authors' Addresses section. Change controller: IESG 11. Security Considerations --------------------------- This section is meant to inform developers, information providers, and users about known security considerations relevant to HTTP message syntax and parsing. Security considerations about HTTP semantics, content, and routing are addressed in [[HTTP](#ref-HTTP)]. ### 11.1. Response Splitting Response splitting (a.k.a. CRLF injection) is a common technique, used in various attacks on Web usage, that exploits the line-based nature of HTTP message framing and the ordered association of requests to responses on persistent connections [[Klein](#ref-Klein)]. This technique can be particularly damaging when the requests pass through a shared cache. Response splitting exploits a vulnerability in servers (usually within an application server) where an attacker can send encoded data within some parameter of the request that is later decoded and echoed within any of the response header fields of the response. If the decoded data is crafted to look like the response has ended and a subsequent response has begun, the response has been split, and the content within the apparent second response is controlled by the attacker. The attacker can then make any other request on the same persistent connection and trick the recipients (including intermediaries) into believing that the second half of the split is an authoritative answer to the second request. For example, a parameter within the request-target might be read by an application server and reused within a redirect, resulting in the same parameter being echoed in the Location header field of the response. If the parameter is decoded by the application and not properly encoded when placed in the response field, the attacker can send encoded CRLF octets and other content that will make the application's single response look like two or more responses. A common defense against response splitting is to filter requests for data that looks like encoded CR and LF (e.g., "%0D" and "%0A"). However, that assumes the application server is only performing URI decoding rather than more obscure data transformations like charset transcoding, XML entity translation, base64 decoding, sprintf reformatting, etc. A more effective mitigation is to prevent anything other than the server's core protocol libraries from sending a CR or LF within the header section, which means restricting the output of header fields to APIs that filter for bad octets and not allowing application servers to write directly to the protocol stream. ### 11.2. Request Smuggling Request smuggling ([[Linhart](#ref-Linhart)]) is a technique that exploits differences in protocol parsing among various recipients to hide additional requests (which might otherwise be blocked or disabled by policy) within an apparently harmless request. Like response splitting, request smuggling can lead to a variety of attacks on HTTP usage. This specification has introduced new requirements on request parsing, particularly with regard to message framing in [Section 6.3](#section-6.3), to reduce the effectiveness of request smuggling. ### 11.3. Message Integrity HTTP does not define a specific mechanism for ensuring message integrity, instead relying on the error-detection ability of underlying transport protocols and the use of length or chunk- delimited framing to detect completeness. Historically, the lack of a single integrity mechanism has been justified by the informal nature of most HTTP communication. However, the prevalence of HTTP as an information access mechanism has resulted in its increasing use within environments where verification of message integrity is crucial. The mechanisms provided with the "https" scheme, such as authenticated encryption, provide protection against modification of messages. Care is needed, however, to ensure that connection closure cannot be used to truncate messages (see [Section 9.8](#section-9.8)). User agents might refuse to accept incomplete messages or treat them specially. For example, a browser being used to view medical history or drug interaction information needs to indicate to the user when such information is detected by the protocol to be incomplete, expired, or corrupted during transfer. Such mechanisms might be selectively enabled via user agent extensions or the presence of message integrity metadata in a response. The "http" scheme provides no protection against accidental or malicious modification of messages. Extensions to the protocol might be used to mitigate the risk of unwanted modification of messages by intermediaries, even when the "https" scheme is used. Integrity might be assured by using message authentication codes or digital signatures that are selectively added to messages via extensible metadata fields. ### 11.4. Message Confidentiality HTTP relies on underlying transport protocols to provide message confidentiality when that is desired. HTTP has been specifically designed to be independent of the transport protocol, such that it can be used over many forms of encrypted connection, with the selection of such transports being identified by the choice of URI scheme or within user agent configuration. The "https" scheme can be used to identify resources that require a confidential connection, as described in Section 4.2.2 of [[HTTP](#ref-HTTP)]. 12. IANA Considerations ----------------------- The change controller for the following registrations is: "IETF ([email protected]) - Internet Engineering Task Force". ### 12.1. Field Name Registration IANA has added the following field names to the "Hypertext Transfer Protocol (HTTP) Field Name Registry" at <<https://www.iana.org/assignments/http-fields>>, as described in Section 18.4 of [[HTTP](#ref-HTTP)]. +===================+===========+=========+============+ | Field Name | Status | Section | Comments | +===================+===========+=========+============+ | Close | permanent | 9.6 | (reserved) | +-------------------+-----------+---------+------------+ | MIME-Version | permanent | B.1 | | +-------------------+-----------+---------+------------+ | Transfer-Encoding | permanent | 6.1 | | +-------------------+-----------+---------+------------+ Table 1 ### 12.2. Media Type Registration IANA has updated the "Media Types" registry at <<https://www.iana.org/assignments/media-types>> with the registration information in Sections [10.1](#section-10.1) and [10.2](#section-10.2) for the media types "message/ http" and "application/http", respectively. ### 12.3. Transfer Coding Registration IANA has updated the "HTTP Transfer Coding Registry" at <<https://www.iana.org/assignments/http-parameters/>> with the registration procedure of [Section 7.3](#section-7.3) and the content coding names summarized in the table below. +============+===========================================+=========+ | Name | Description | Section | +============+===========================================+=========+ | chunked | Transfer in a series of chunks | 7.1 | +------------+-------------------------------------------+---------+ | compress | UNIX "compress" data format [[Welch](#ref-Welch)] | 7.2 | +------------+-------------------------------------------+---------+ | deflate | "deflate" compressed data ([[RFC1951](https://datatracker.ietf.org/doc/html/rfc1951)]) | 7.2 | | | inside the "zlib" data format ([[RFC1950](https://datatracker.ietf.org/doc/html/rfc1950)]) | | +------------+-------------------------------------------+---------+ | gzip | GZIP file format [[RFC1952](https://datatracker.ietf.org/doc/html/rfc1952)] | 7.2 | +------------+-------------------------------------------+---------+ | trailers | (reserved) | 12.3 | +------------+-------------------------------------------+---------+ | x-compress | Deprecated (alias for compress) | 7.2 | +------------+-------------------------------------------+---------+ | x-gzip | Deprecated (alias for gzip) | 7.2 | +------------+-------------------------------------------+---------+ Table 2 | \*Note:\* the coding name "trailers" is reserved because its use | would conflict with the keyword "trailers" in the TE header | field (Section 10.1.4 of [[HTTP](#ref-HTTP)]). ### 12.4. ALPN Protocol ID Registration IANA has updated the "TLS Application-Layer Protocol Negotiation (ALPN) Protocol IDs" registry at <[https://www.iana.org/assignments/](https://www.iana.org/assignments/tls-extensiontype-values/) [tls-extensiontype-values/](https://www.iana.org/assignments/tls-extensiontype-values/)> with the registration below: +==========+=============================+===========+ | Protocol | Identification Sequence | Reference | +==========+=============================+===========+ | HTTP/1.1 | 0x68 0x74 0x74 0x70 0x2f | [RFC 9112](https://datatracker.ietf.org/doc/html/rfc9112) | | | 0x31 0x2e 0x31 ("http/1.1") | | +----------+-----------------------------+-----------+ Table 3 13. References -------------- ### 13.1. Normative References [CACHING] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP Caching", STD 98, [RFC 9111](https://datatracker.ietf.org/doc/html/rfc9111), DOI 10.17487/RFC9111, June 2022, <<https://www.rfc-editor.org/info/rfc9111>>. [HTTP] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP Semantics", STD 97, [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110), DOI 10.17487/RFC9110, June 2022, <<https://www.rfc-editor.org/info/rfc9110>>. [RFC1950] Deutsch, P. and J-L. Gailly, "ZLIB Compressed Data Format Specification version 3.3", [RFC 1950](https://datatracker.ietf.org/doc/html/rfc1950), DOI 10.17487/RFC1950, May 1996, <<https://www.rfc-editor.org/info/rfc1950>>. [RFC1951] Deutsch, P., "DEFLATE Compressed Data Format Specification version 1.3", [RFC 1951](https://datatracker.ietf.org/doc/html/rfc1951), DOI 10.17487/RFC1951, May 1996, <<https://www.rfc-editor.org/info/rfc1951>>. [RFC1952] Deutsch, P., "GZIP file format specification version 4.3", [RFC 1952](https://datatracker.ietf.org/doc/html/rfc1952), DOI 10.17487/RFC1952, May 1996, <<https://www.rfc-editor.org/info/rfc1952>>. [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", [BCP 14](https://datatracker.ietf.org/doc/html/bcp14), [RFC 2119](https://datatracker.ietf.org/doc/html/rfc2119), DOI 10.17487/RFC2119, March 1997, <<https://www.rfc-editor.org/info/rfc2119>>. [RFC5234] Crocker, D., Ed. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, [RFC 5234](https://datatracker.ietf.org/doc/html/rfc5234), DOI 10.17487/RFC5234, January 2008, <<https://www.rfc-editor.org/info/rfc5234>>. [RFC7405] Kyzivat, P., "Case-Sensitive String Support in ABNF", [RFC 7405](https://datatracker.ietf.org/doc/html/rfc7405), DOI 10.17487/RFC7405, December 2014, <<https://www.rfc-editor.org/info/rfc7405>>. [RFC8174] Leiba, B., "Ambiguity of Uppercase vs Lowercase in [RFC](https://datatracker.ietf.org/doc/html/rfc2119) [2119](https://datatracker.ietf.org/doc/html/rfc2119) Key Words", [BCP 14](https://datatracker.ietf.org/doc/html/bcp14), [RFC 8174](https://datatracker.ietf.org/doc/html/rfc8174), DOI 10.17487/RFC8174, May 2017, <<https://www.rfc-editor.org/info/rfc8174>>. [TLS13] Rescorla, E., "The Transport Layer Security (TLS) Protocol Version 1.3", [RFC 8446](https://datatracker.ietf.org/doc/html/rfc8446), DOI 10.17487/RFC8446, August 2018, <<https://www.rfc-editor.org/info/rfc8446>>. [URI] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform Resource Identifier (URI): Generic Syntax", STD 66, [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986), DOI 10.17487/RFC3986, January 2005, <<https://www.rfc-editor.org/info/rfc3986>>. [USASCII] American National Standards Institute, "Coded Character Set -- 7-bit American Standard Code for Information Interchange", ANSI X3.4, 1986. [Welch] Welch, T., "A Technique for High-Performance Data Compression", IEEE Computer 17(6), DOI 10.1109/MC.1984.1659158, June 1984, <<https://ieeexplore.ieee.org/document/1659158/>>. ### 13.2. Informative References [HTTP/1.0] Berners-Lee, T., Fielding, R., and H. Frystyk, "Hypertext Transfer Protocol -- HTTP/1.0", [RFC 1945](https://datatracker.ietf.org/doc/html/rfc1945), DOI 10.17487/RFC1945, May 1996, <<https://www.rfc-editor.org/info/rfc1945>>. [Klein] Klein, A., "Divide and Conquer - HTTP Response Splitting, Web Cache Poisoning Attacks, and Related Topics", March 2004, <[https://packetstormsecurity.com/papers/general/](https://packetstormsecurity.com/papers/general/whitepaper_httpresponse.pdf) [whitepaper\_httpresponse.pdf](https://packetstormsecurity.com/papers/general/whitepaper_httpresponse.pdf)>. [Linhart] Linhart, C., Klein, A., Heled, R., and S. Orrin, "HTTP Request Smuggling", June 2005, <[https://www.cgisecurity.com/lib/HTTP-Request-](https://www.cgisecurity.com/lib/HTTP-Request-Smuggling.pdf) [Smuggling.pdf](https://www.cgisecurity.com/lib/HTTP-Request-Smuggling.pdf)>. [RFC2045] Freed, N. and N. Borenstein, "Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies", [RFC 2045](https://datatracker.ietf.org/doc/html/rfc2045), DOI 10.17487/RFC2045, November 1996, <<https://www.rfc-editor.org/info/rfc2045>>. [RFC2046] Freed, N. and N. Borenstein, "Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types", [RFC 2046](https://datatracker.ietf.org/doc/html/rfc2046), DOI 10.17487/RFC2046, November 1996, <<https://www.rfc-editor.org/info/rfc2046>>. [RFC2049] Freed, N. and N. Borenstein, "Multipurpose Internet Mail Extensions (MIME) Part Five: Conformance Criteria and Examples", [RFC 2049](https://datatracker.ietf.org/doc/html/rfc2049), DOI 10.17487/RFC2049, November 1996, <<https://www.rfc-editor.org/info/rfc2049>>. [RFC2068] Fielding, R., Gettys, J., Mogul, J., Frystyk, H., and T. Berners-Lee, "Hypertext Transfer Protocol -- HTTP/1.1", [RFC 2068](https://datatracker.ietf.org/doc/html/rfc2068), DOI 10.17487/RFC2068, January 1997, <<https://www.rfc-editor.org/info/rfc2068>>. [RFC2557] Palme, J., Hopmann, A., and N. Shelness, "MIME Encapsulation of Aggregate Documents, such as HTML (MHTML)", [RFC 2557](https://datatracker.ietf.org/doc/html/rfc2557), DOI 10.17487/RFC2557, March 1999, <<https://www.rfc-editor.org/info/rfc2557>>. [RFC5322] Resnick, P., Ed., "Internet Message Format", [RFC 5322](https://datatracker.ietf.org/doc/html/rfc5322), DOI 10.17487/RFC5322, October 2008, <<https://www.rfc-editor.org/info/rfc5322>>. [RFC7230] Fielding, R., Ed. and J. Reschke, Ed., "Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing", [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230), DOI 10.17487/RFC7230, June 2014, <<https://www.rfc-editor.org/info/rfc7230>>. [RFC8126] Cotton, M., Leiba, B., and T. Narten, "Guidelines for Writing an IANA Considerations Section in RFCs", [BCP 26](https://datatracker.ietf.org/doc/html/bcp26), [RFC 8126](https://datatracker.ietf.org/doc/html/rfc8126), DOI 10.17487/RFC8126, June 2017, <<https://www.rfc-editor.org/info/rfc8126>>. Appendix A. Collected ABNF -------------------------- In the collected ABNF below, list rules are expanded per Section 5.6.1 of [[HTTP](#ref-HTTP)]. BWS = <BWS, see [[HTTP](#ref-HTTP)], Section 5.6.3> HTTP-message = start-line CRLF \*( field-line CRLF ) CRLF [ message-body ] HTTP-name = %x48.54.54.50 ; HTTP HTTP-version = HTTP-name "/" DIGIT "." DIGIT OWS = <OWS, see [[HTTP](#ref-HTTP)], Section 5.6.3> RWS = <RWS, see [[HTTP](#ref-HTTP)], Section 5.6.3> Transfer-Encoding = [ transfer-coding \*( OWS "," OWS transfer-coding ) ] absolute-URI = <absolute-URI, see [[URI](#ref-URI)], Section 4.3> absolute-form = absolute-URI absolute-path = <absolute-path, see [[HTTP](#ref-HTTP)], Section 4.1> asterisk-form = "\*" authority = <authority, see [[URI](#ref-URI)], Section 3.2> authority-form = uri-host ":" port chunk = chunk-size [ chunk-ext ] CRLF chunk-data CRLF chunk-data = 1\*OCTET chunk-ext = \*( BWS ";" BWS chunk-ext-name [ BWS "=" BWS chunk-ext-val ] ) chunk-ext-name = token chunk-ext-val = token / quoted-string chunk-size = 1\*HEXDIG chunked-body = \*chunk last-chunk trailer-section CRLF field-line = field-name ":" OWS field-value OWS field-name = <field-name, see [[HTTP](#ref-HTTP)], Section 5.1> field-value = <field-value, see [[HTTP](#ref-HTTP)], Section 5.5> last-chunk = 1\*"0" [ chunk-ext ] CRLF message-body = \*OCTET method = token obs-fold = OWS CRLF RWS obs-text = <obs-text, see [[HTTP](#ref-HTTP)], Section 5.6.4> origin-form = absolute-path [ "?" query ] port = <port, see [[URI](#ref-URI)], Section 3.2.3> query = <query, see [[URI](#ref-URI)], Section 3.4> quoted-string = <quoted-string, see [[HTTP](#ref-HTTP)], Section 5.6.4> reason-phrase = 1\*( HTAB / SP / VCHAR / obs-text ) request-line = method SP request-target SP HTTP-version request-target = origin-form / absolute-form / authority-form / asterisk-form start-line = request-line / status-line status-code = 3DIGIT status-line = HTTP-version SP status-code SP [ reason-phrase ] token = <token, see [[HTTP](#ref-HTTP)], Section 5.6.2> trailer-section = \*( field-line CRLF ) transfer-coding = <transfer-coding, see [[HTTP](#ref-HTTP)], Section 10.1.4> uri-host = <host, see [[URI](#ref-URI)], Section 3.2.2> Appendix B. Differences between HTTP and MIME --------------------------------------------- HTTP/1.1 uses many of the constructs defined for the Internet Message Format [[RFC5322](https://datatracker.ietf.org/doc/html/rfc5322)] and Multipurpose Internet Mail Extensions (MIME) [[RFC2045](https://datatracker.ietf.org/doc/html/rfc2045)] to allow a message body to be transmitted in an open variety of representations and with extensible fields. However, some of these constructs have been reinterpreted to better fit the needs of interactive communication, leading to some differences in how MIME constructs are used within HTTP. These differences were carefully chosen to optimize performance over binary connections, allow greater freedom in the use of new media types, ease date comparisons, and accommodate common implementations. This appendix describes specific areas where HTTP differs from MIME. Proxies and gateways to and from strict MIME environments need to be aware of these differences and provide the appropriate conversions where necessary. ### B.1. MIME-Version HTTP is not a MIME-compliant protocol. However, messages can include a single MIME-Version header field to indicate what version of the MIME protocol was used to construct the message. Use of the MIME- Version header field indicates that the message is in full conformance with the MIME protocol (as defined in [[RFC2045](https://datatracker.ietf.org/doc/html/rfc2045)]). Senders are responsible for ensuring full conformance (where possible) when exporting HTTP messages to strict MIME environments. ### B.2. Conversion to Canonical Form MIME requires that an Internet mail body part be converted to canonical form prior to being transferred, as described in [Section 4 of [RFC2049]](https://datatracker.ietf.org/doc/html/rfc2049#section-4), and that content with a type of "text" represents line breaks as CRLF, forbidding the use of CR or LF outside of line break sequences [[RFC2046](https://datatracker.ietf.org/doc/html/rfc2046)]. In contrast, HTTP does not care whether CRLF, bare CR, or bare LF are used to indicate a line break within content. A proxy or gateway from HTTP to a strict MIME environment ought to translate all line breaks within text media types to the [RFC 2049](https://datatracker.ietf.org/doc/html/rfc2049) canonical form of CRLF. Note, however, this might be complicated by the presence of a Content-Encoding and by the fact that HTTP allows the use of some charsets that do not use octets 13 and 10 to represent CR and LF, respectively. Conversion will break any cryptographic checksums applied to the original content unless the original content is already in canonical form. Therefore, the canonical form is recommended for any content that uses such checksums in HTTP. ### B.3. Conversion of Date Formats HTTP/1.1 uses a restricted set of date formats (Section 5.6.7 of [[HTTP](#ref-HTTP)]) to simplify the process of date comparison. Proxies and gateways from other protocols ought to ensure that any Date header field present in a message conforms to one of the HTTP/1.1 formats and rewrite the date if necessary. ### B.4. Conversion of Content-Encoding MIME does not include any concept equivalent to HTTP's Content- Encoding header field. Since this acts as a modifier on the media type, proxies and gateways from HTTP to MIME-compliant protocols ought to either change the value of the Content-Type header field or decode the representation before forwarding the message. (Some experimental applications of Content-Type for Internet mail have used a media-type parameter of ";conversions=<content-coding>" to perform a function equivalent to Content-Encoding. However, this parameter is not part of the MIME standards.) ### B.5. Conversion of Content-Transfer-Encoding HTTP does not use the Content-Transfer-Encoding field of MIME. Proxies and gateways from MIME-compliant protocols to HTTP need to remove any Content-Transfer-Encoding prior to delivering the response message to an HTTP client. Proxies and gateways from HTTP to MIME-compliant protocols are responsible for ensuring that the message is in the correct format and encoding for safe transport on that protocol, where "safe transport" is defined by the limitations of the protocol being used. Such a proxy or gateway ought to transform and label the data with an appropriate Content-Transfer-Encoding if doing so will improve the likelihood of safe transport over the destination protocol. ### B.6. MHTML and Line Length Limitations HTTP implementations that share code with MHTML [[RFC2557](https://datatracker.ietf.org/doc/html/rfc2557)] implementations need to be aware of MIME line length limitations. Since HTTP does not have this limitation, HTTP does not fold long lines. MHTML messages being transported by HTTP follow all conventions of MHTML, including line length limitations and folding, canonicalization, etc., since HTTP transfers message-bodies without modification and, aside from the "multipart/byteranges" type (Section 14.6 of [[HTTP](#ref-HTTP)]), does not interpret the content or any MIME header lines that might be contained therein. Appendix C. Changes from Previous RFCs -------------------------------------- ### C.1. Changes from HTTP/0.9 Since HTTP/0.9 did not support header fields in a request, there is no mechanism for it to support name-based virtual hosts (selection of resource by inspection of the Host header field). Any server that implements name-based virtual hosts ought to disable support for HTTP/0.9. Most requests that appear to be HTTP/0.9 are, in fact, badly constructed HTTP/1.x requests caused by a client failing to properly encode the request-target. ### C.2. Changes from HTTP/1.0 #### C.2.1. Multihomed Web Servers The requirements that clients and servers support the Host header field (Section 7.2 of [[HTTP](#ref-HTTP)]), report an error if it is missing from an HTTP/1.1 request, and accept absolute URIs ([Section 3.2](#section-3.2)) are among the most important changes defined by HTTP/1.1. Older HTTP/1.0 clients assumed a one-to-one relationship of IP addresses and servers; there was no established mechanism for distinguishing the intended server of a request other than the IP address to which that request was directed. The Host header field was introduced during the development of HTTP/1.1 and, though it was quickly implemented by most HTTP/1.0 browsers, additional requirements were placed on all HTTP/1.1 requests in order to ensure complete adoption. At the time of this writing, most HTTP-based services are dependent upon the Host header field for targeting requests. #### C.2.2. Keep-Alive Connections In HTTP/1.0, each connection is established by the client prior to the request and closed by the server after sending the response. However, some implementations implement the explicitly negotiated ("Keep-Alive") version of persistent connections described in [Section 19.7.1 of [RFC2068]](https://datatracker.ietf.org/doc/html/rfc2068#section-19.7.1). Some clients and servers might wish to be compatible with these previous approaches to persistent connections, by explicitly negotiating for them with a "Connection: keep-alive" request header field. However, some experimental implementations of HTTP/1.0 persistent connections are faulty; for example, if an HTTP/1.0 proxy server doesn't understand Connection, it will erroneously forward that header field to the next inbound server, which would result in a hung connection. One attempted solution was the introduction of a Proxy-Connection header field, targeted specifically at proxies. In practice, this was also unworkable, because proxies are often deployed in multiple layers, bringing about the same problem discussed above. As a result, clients are encouraged not to send the Proxy-Connection header field in any requests. Clients are also encouraged to consider the use of "Connection: keep- alive" in requests carefully; while they can enable persistent connections with HTTP/1.0 servers, clients using them will need to monitor the connection for "hung" requests (which indicate that the client ought to stop sending the header field), and this mechanism ought not be used by clients at all when a proxy is being used. #### C.2.3. Introduction of Transfer-Encoding HTTP/1.1 introduces the Transfer-Encoding header field ([Section 6.1](#section-6.1)). Transfer codings need to be decoded prior to forwarding an HTTP message over a MIME-compliant protocol. ### C.3. Changes from [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230) Most of the sections introducing HTTP's design goals, history, architecture, conformance criteria, protocol versioning, URIs, message routing, and header fields have been moved to [[HTTP](#ref-HTTP)]. This document has been reduced to just the messaging syntax and connection management requirements specific to HTTP/1.1. Bare CRs have been prohibited outside of content. ([Section 2.2](#section-2.2)) The ABNF definition of authority-form has changed from the more general authority component of a URI (in which port is optional) to the specific host:port format that is required by CONNECT. ([Section 3.2.3](#section-3.2.3)) Recipients are required to avoid smuggling/splitting attacks when processing an ambiguous message framing. ([Section 6.1](#section-6.1)) In the ABNF for chunked extensions, (bad) whitespace around ";" and "=" has been reintroduced. Whitespace was removed in [[RFC7230](https://datatracker.ietf.org/doc/html/rfc7230)], but that change was found to break existing implementations. ([Section 7.1.1](#section-7.1.1)) Trailer field semantics now transcend the specifics of chunked transfer coding. The decoding algorithm for chunked ([Section 7.1.3](#section-7.1.3)) has been updated to encourage storage/forwarding of trailer fields separately from the header section, to only allow merging into the header section if the recipient knows the corresponding field definition permits and defines how to merge, and otherwise to discard the trailer fields instead of merging. The trailer part is now called the trailer section to be more consistent with the header section and more distinct from a body part. ([Section 7.1.2](#section-7.1.2)) Transfer coding parameters called "q" are disallowed in order to avoid conflicts with the use of ranks in the TE header field. ([Section 7.3](#section-7.3)) Acknowledgements See Appendix "Acknowledgements" of [[HTTP](#ref-HTTP)], which applies to this document as well. Index A C D F G H M O R T X A absolute-form (of request-target) [Section 3.2.2](#section-3.2.2) application/http Media Type \*\_[Section 10.2](#section-10.2)\_\* asterisk-form (of request-target) [Section 3.2.4](#section-3.2.4) authority-form (of request-target) [Section 3.2.3](#section-3.2.3) C chunked (Coding Format) [Section 6.1](#section-6.1); [Section 6.3](#section-6.3) chunked (transfer coding) \*\_[Section 7.1](#section-7.1)\_\* close [Section 9.3](#section-9.3); \*\_[Section 9.6](#section-9.6)\_\* compress (transfer coding) \*\_[Section 7.2](#section-7.2)\_\* Connection header field [Section 9.6](#section-9.6) Content-Length header field [Section 6.2](#section-6.2) Content-Transfer-Encoding header field [Appendix B.5](#appendix-B.5) D deflate (transfer coding) \*\_[Section 7.2](#section-7.2)\_\* F Fields Close \*\_[Section 9.6](#section-9.6), Paragraph 4\_\* MIME-Version \*\_Appendix B.1\_\* Transfer-Encoding \*\_[Section 6.1](#section-6.1)\_\* G Grammar ALPHA \*\_[Section 1.2](#section-1.2)\_\* CR \*\_[Section 1.2](#section-1.2)\_\* CRLF \*\_[Section 1.2](#section-1.2)\_\* CTL \*\_[Section 1.2](#section-1.2)\_\* DIGIT \*\_[Section 1.2](#section-1.2)\_\* DQUOTE \*\_[Section 1.2](#section-1.2)\_\* HEXDIG \*\_[Section 1.2](#section-1.2)\_\* HTAB \*\_[Section 1.2](#section-1.2)\_\* HTTP-message \*\_[Section 2.1](#section-2.1)\_\* HTTP-name \*\_[Section 2.3](#section-2.3)\_\* HTTP-version \*\_[Section 2.3](#section-2.3)\_\* LF \*\_[Section 1.2](#section-1.2)\_\* OCTET \*\_[Section 1.2](#section-1.2)\_\* SP \*\_[Section 1.2](#section-1.2)\_\* Transfer-Encoding \*\_[Section 6.1](#section-6.1)\_\* VCHAR \*\_[Section 1.2](#section-1.2)\_\* absolute-form [Section 3.2](#section-3.2); \*\_[Section 3.2.2](#section-3.2.2)\_\* asterisk-form [Section 3.2](#section-3.2); \*\_[Section 3.2.4](#section-3.2.4)\_\* authority-form [Section 3.2](#section-3.2); \*\_[Section 3.2.3](#section-3.2.3)\_\* chunk \*\_[Section 7.1](#section-7.1)\_\* chunk-data \*\_[Section 7.1](#section-7.1)\_\* chunk-ext [Section 7.1](#section-7.1); \*\_[Section 7.1.1](#section-7.1.1)\_\* chunk-ext-name \*\_[Section 7.1.1](#section-7.1.1)\_\* chunk-ext-val \*\_[Section 7.1.1](#section-7.1.1)\_\* chunk-size \*\_[Section 7.1](#section-7.1)\_\* chunked-body \*\_[Section 7.1](#section-7.1)\_\* field-line \*\_[Section 5](#section-5)\_\*; [Section 7.1.2](#section-7.1.2) field-name [Section 5](#section-5) field-value [Section 5](#section-5) last-chunk \*\_[Section 7.1](#section-7.1)\_\* message-body \*\_[Section 6](#section-6)\_\* method \*\_[Section 3.1](#section-3.1)\_\* obs-fold \*\_[Section 5.2](#section-5.2)\_\* origin-form [Section 3.2](#section-3.2); \*\_[Section 3.2.1](#section-3.2.1)\_\* reason-phrase \*\_[Section 4](#section-4)\_\* request-line \*\_[Section 3](#section-3)\_\* request-target \*\_[Section 3.2](#section-3.2)\_\* start-line \*\_[Section 2.1](#section-2.1)\_\* status-code \*\_[Section 4](#section-4)\_\* status-line \*\_[Section 4](#section-4)\_\* trailer-section [Section 7.1](#section-7.1); \*\_[Section 7.1.2](#section-7.1.2)\_\* gzip (transfer coding) \*\_[Section 7.2](#section-7.2)\_\* H Header Fields MIME-Version \*\_Appendix B.1\_\* Transfer-Encoding \*\_[Section 6.1](#section-6.1)\_\* header line [Section 2.1](#section-2.1) header section [Section 2.1](#section-2.1) headers [Section 2.1](#section-2.1) M Media Type application/http \*\_[Section 10.2](#section-10.2)\_\* message/http \*\_[Section 10.1](#section-10.1)\_\* message/http Media Type \*\_[Section 10.1](#section-10.1)\_\* method \*\_[Section 3.1](#section-3.1)\_\* MIME-Version header field \*\_Appendix B.1\_\* O origin-form (of request-target) [Section 3.2.1](#section-3.2.1) R request-target \*\_[Section 3.2](#section-3.2)\_\* T Transfer-Encoding header field \*\_[Section 6.1](#section-6.1)\_\* X x-compress (transfer coding) \*\_[Section 7.2](#section-7.2)\_\* x-gzip (transfer coding) \*\_[Section 7.2](#section-7.2)\_\* Authors' Addresses Roy T. Fielding (editor) Adobe 345 Park Ave San Jose, CA 95110 United States of America Email: [email protected] URI: <https://roy.gbiv.com/> Mark Nottingham (editor) Fastly Prahran Australia Email: [email protected] URI: <https://www.mnot.net/> Julian Reschke (editor) greenbytes GmbH Hafenweg 16 48155 Münster Germany Email: [email protected] URI: <https://greenbytes.de/tech/webdav/>
programming_docs
http Authentication Authentication ============== HTTP authentication =================== HTTP provides a general framework for access control and authentication. This page is an introduction to the HTTP framework for authentication, and shows how to restrict access to your server using the HTTP "Basic" schema. The general HTTP authentication framework ----------------------------------------- [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235) defines the HTTP authentication framework, which can be used by a server to [challenge](https://developer.mozilla.org/en-US/docs/Glossary/challenge) a client request, and by a client to provide authentication information. The challenge and response flow works like this: 1. The server responds to a client with a [`401`](status/401) (Unauthorized) response status and provides information on how to authorize with a [`WWW-Authenticate`](headers/www-authenticate) response header containing at least one challenge. 2. A client that wants to authenticate itself with the server can then do so by including an [`Authorization`](headers/authorization) request header with the credentials. 3. Usually a client will present a password prompt to the user and will then issue the request including the correct `Authorization` header. The general message flow above is the same for most (if not all) [authentication schemes](#authentication_schemes). The actual information in the headers and the way it is encoded does change! **Warning:** The "Basic" authentication scheme used in the diagram above sends the credentials encoded but not encrypted. This would be completely insecure unless the exchange was over a secure connection (HTTPS/TLS). ### Proxy authentication The same challenge and response mechanism can be used for *proxy authentication*. As both resource authentication and proxy authentication can coexist, a different set of headers and status codes is needed. In the case of proxies, the challenging status code is [`407`](status/407) (Proxy Authentication Required), the [`Proxy-Authenticate`](headers/proxy-authenticate) response header contains at least one challenge applicable to the proxy, and the [`Proxy-Authorization`](headers/proxy-authorization) request header is used for providing the credentials to the proxy server. ### Access forbidden If a (proxy) server receives *invalid* credentials, it should respond with a [`401`](status/401) `Unauthorized` or with a [`407`](status/407) `Proxy Authentication Required`, and the user may send a new request or replace the [`Authorization`](headers/authorization) header field. If a (proxy) server receives valid credentials that are *inadequate* to access a given resource, the server should respond with the [`403`](status/403) `Forbidden` status code. Unlike [`401`](status/401) `Unauthorized` or [`407`](status/407) `Proxy Authentication Required`, authentication is impossible for this user and browsers will not propose a new attempt. In all cases, the server may prefer returning a [`404`](status/404) `Not Found` status code, to hide the existence of the page to a user without adequate privileges or not correctly authenticated. ### Authentication of cross-origin images A potential security hole (that has since been fixed in browsers) was authentication of cross-site images. From [Firefox 59](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/59) onwards, image resources loaded from different origins to the current document are no longer able to trigger HTTP authentication dialogs ([bug 1423146](https://bugzilla.mozilla.org/show_bug.cgi?id=1423146)), preventing user credentials being stolen if attackers were able to embed an arbitrary image into a third-party page. ### Character encoding of HTTP authentication Browsers use `utf-8` encoding for usernames and passwords. Firefox once used `ISO-8859-1`, but changed to `utf-8` for parity with other browsers and to avoid potential problems as described in [bug 1419658](https://bugzilla.mozilla.org/show_bug.cgi?id=1419658). ### WWW-Authenticate and Proxy-Authenticate headers The [`WWW-Authenticate`](headers/www-authenticate) and [`Proxy-Authenticate`](headers/proxy-authenticate) response headers define the authentication method that should be used to gain access to a resource. They must specify which authentication scheme is used, so that the client that wishes to authorize knows how to provide the credentials. The syntax for these headers is the following: ``` WWW-Authenticate: <type> realm=<realm> Proxy-Authenticate: <type> realm=<realm> ``` Here, `<type>` is the authentication scheme ("Basic" is the most common scheme and [introduced below](#basic_authentication_scheme)). The *realm* is used to describe the protected area or to indicate the scope of protection. This could be a message like "Access to the staging site" or similar, so that the user knows to which space they are trying to get access to. ### Authorization and Proxy-Authorization headers The [`Authorization`](headers/authorization) and [`Proxy-Authorization`](headers/proxy-authorization) request headers contain the credentials to authenticate a user agent with a (proxy) server. Here, the `<type>` is needed again followed by the credentials, which can be encoded or encrypted depending on which authentication scheme is used. ``` Authorization: <type> <credentials> Proxy-Authorization: <type> <credentials> ``` Authentication schemes ---------------------- The general HTTP authentication framework is the base for a number of authentication schemes. IANA maintains a [list of authentication schemes](https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml), but there are other schemes offered by host services, such as Amazon AWS. Some common authentication schemes include: **Basic** See [RFC 7617](https://datatracker.ietf.org/doc/html/rfc7617), base64-encoded credentials. More information below. **Bearer** See [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750), bearer tokens to access OAuth 2.0-protected resources **Digest** See [RFC 7616](https://datatracker.ietf.org/doc/html/rfc7616). Firefox 93 and later support the SHA-256 algorithm. Previous versions only support MD5 hashing (not recommended). **HOBA** See [RFC 7486](https://datatracker.ietf.org/doc/html/rfc7486), Section 3, **H**TTP **O**rigin-**B**ound **A**uthentication, digital-signature-based **Mutual** See [RFC 8120](https://datatracker.ietf.org/doc/html/rfc8120) **Negotiate** / **NTLM** See [RFC4599](https://www.ietf.org/rfc/rfc4559.txt) **VAPID** See [RFC 8292](https://datatracker.ietf.org/doc/html/rfc8292) **SCRAM** See [RFC 7804](https://datatracker.ietf.org/doc/html/rfc7804) **AWS4-HMAC-SHA256** See [AWS docs](https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-auth-using-authorization-header.html). This scheme is used for AWS3 server authentication. Schemes can differ in security strength and in their availability in client or server software. The "Basic" authentication scheme offers very poor security, but is widely supported and easy to set up. It is introduced in more detail below. Basic authentication scheme --------------------------- The "Basic" HTTP authentication scheme is defined in [RFC 7617](https://datatracker.ietf.org/doc/html/rfc7617), which transmits credentials as user ID/password pairs, encoded using base64. ### Security of basic authentication As the user ID and password are passed over the network as clear text (it is base64 encoded, but base64 is a reversible encoding), the basic authentication scheme **is not secure**. HTTPS/TLS should be used with basic authentication. Without these additional security enhancements, basic authentication should not be used to protect sensitive or valuable information. ### Restricting access with Apache and basic authentication To password-protect a directory on an Apache server, you will need a `.htaccess` and a `.htpasswd` file. The `.htaccess` file typically looks like this: ``` AuthType Basic AuthName "Access to the staging site" AuthUserFile /path/to/.htpasswd Require valid-user ``` The `.htaccess` file references a `.htpasswd` file in which each line consists of a username and a password separated by a colon (`:`). You cannot see the actual passwords as they are [hashed](https://httpd.apache.org/docs/2.4/misc/password_encryptions.html) (using MD5-based hashing, in this case). Note that you can name your `.htpasswd` file differently if you like, but keep in mind this file shouldn't be accessible to anyone. (Apache is usually configured to prevent access to `.ht*` files). ``` aladdin:$apr1$ZjTqBB3f$IF9gdYAGlMrs2fuINjHsz. user2:$apr1$O04r.y2H$/vEkesPhVInBByJUkXitA/ ``` ### Restricting access with Nginx and basic authentication For Nginx, you will need to specify a location that you are going to protect and the `auth_basic` directive that provides the name to the password-protected area. The `auth_basic_user_file` directive then points to a `.htpasswd` file containing the encrypted user credentials, just like in the Apache example above. ``` location /status { auth_basic "Access to the staging site"; auth_basic_user_file /etc/apache2/.htpasswd; } ``` ### Access using credentials in the URL Many clients also let you avoid the login prompt by using an encoded URL containing the username and the password like this: ``` https://username:[email protected]/ ``` **The use of these URLs is deprecated**. In Chrome, the `username:password@` part in URLs is even [stripped out](https://bugs.chromium.org/p/chromium/issues/detail?id=82250#c7) for security reasons. In Firefox, it is checked if the site actually requires authentication and if not, Firefox will warn the user with a prompt "You are about to log in to the site "[www.example.com](https://www.example.com)" with the username "username", but the website does not require authentication. This may be an attempt to trick you." See also -------- * [`WWW-Authenticate`](headers/www-authenticate) * [`Authorization`](headers/authorization) * [`Proxy-Authorization`](headers/proxy-authorization) * [`Proxy-Authenticate`](headers/proxy-authenticate) * [`401`](status/401), [`403`](status/403), [`407`](status/407) http The Atom Publishing Protocol Network Working Group J. Gregorio, Ed. Request for Comments: 5023 Google Category: Standards Track B. de hOra, Ed. NewBay Software October 2007 The Atom Publishing Protocol ============================ Status of This Memo This document specifies an Internet standards track protocol for the Internet community, and requests discussion and suggestions for improvements. Please refer to the current edition of the "Internet Official Protocol Standards" (STD 1) for the standardization state and status of this protocol. Distribution of this memo is unlimited. Abstract The Atom Publishing Protocol (AtomPub) is an application-level protocol for publishing and editing Web resources. The protocol is based on HTTP transfer of Atom-formatted representations. The Atom format is documented in the Atom Syndication Format. Table of Contents [1](#section-1). Introduction [2](#section-2). Notational Conventions [2.1](#section-2.1). XML-Related Conventions [2.1.1](#section-2.1.1). Referring to Information Items [2.1.2](#section-2.1.2). RELAX NG Schema [2.1.3](#section-2.1.3). Use of "xml:base" and "xml:lang" [3](#section-3). Terminology [4](#section-4). Protocol Model [4.1](#section-4.1). Identity and Naming [4.2](#section-4.2). Documents and Resource Classification [4.3](#section-4.3). Control and Publishing [4.4](#section-4.4). Client Implementation Considerations [5](#section-5). Protocol Operations [5.1](#section-5.1). Retrieving a Service Document [5.2](#section-5.2). Listing Collection Members [5.3](#section-5.3). Creating a Resource [5.4](#section-5.4). Editing a Resource [5.4.1](#section-5.4.1). Retrieving a Resource [5.4.2](#section-5.4.2). Editing a Resource [5.4.3](#section-5.4.3). Deleting a Resource [5.5](#section-5.5). Use of HTTP Response Codes [6](#section-6). Protocol Documents [6.1](#section-6.1). Document Types [6.2](#section-6.2). Document Extensibility [7](#section-7). Category Documents [7.1](#section-7.1). Example [7.2](#section-7.2). Element Definitions [7.2.1](#section-7.2.1). The "app:categories" Element [8](#section-8). Service Documents [8.1](#section-8.1). Workspaces [8.2](#section-8.2). Example [8.3](#section-8.3). Element Definitions [8.3.1](#section-8.3.1). The "app:service" Element [8.3.2](#section-8.3.2). The "app:workspace" Element [8.3.3](#section-8.3.3). The "app:collection" Element [8.3.4](#section-8.3.4). The "app:accept" Element [8.3.5](#section-8.3.5). Usage in Atom Feed Documents [8.3.6](#section-8.3.6). The "app:categories" Element [9](#section-9). Creating and Editing Resources [9.1](#section-9.1). Member URIs [9.2](#section-9.2). Creating Resources with POST [9.2.1](#section-9.2.1). Example [9.3](#section-9.3). Editing Resources with PUT [9.4](#section-9.4). Deleting Resources with DELETE [9.5](#section-9.5). Caching and Entity Tags [9.5.1](#section-9.5.1). Example ............................................ [9.6](#section-9.6). Media Resources and Media Link Entries [9.6.1](#section-9.6.1). Examples [9.7](#section-9.7). The Slug Header [9.7.1](#section-9.7.1). Slug Header Syntax [9.7.2](#section-9.7.2). Example [10](#section-10). Listing Collections [10.1](#section-10.1). Collection Partial Lists [10.2](#section-10.2). The "app:edited" Element [11](#section-11). Atom Format Link Relation Extensions [11.1](#section-11.1). The "edit" Link Relation [11.2](#section-11.2). The "edit-media" Link Relation [12](#section-12). The Atom Format Type Parameter [12.1](#section-12.1). The "type" parameter [12.1.1](#section-12.1.1). Conformance [13](#section-13). Atom Publishing Controls [13.1](#section-13.1). The "app:control" Element [13.1.1](#section-13.1.1). The "app:draft" Element [14](#section-14). Securing the Atom Publishing Protocol [15](#section-15). Security Considerations [15.1](#section-15.1). Denial of Service [15.2](#section-15.2). Replay Attacks [15.3](#section-15.3). Spoofing Attacks [15.4](#section-15.4). Linked Resources [15.5](#section-15.5). Digital Signatures and Encryption [15.6](#section-15.6). URIs and IRIs [15.7](#section-15.7). Code Injection and Cross Site Scripting [16](#section-16). IANA Considerations [16.1](#section-16.1). Content-Type Registration for 'application/atomcat+xml' ..39 [16.2](#section-16.2). Content-Type Registration for 'application/atomsvc+xml' ..40 [16.3](#section-16.3). Header Field Registration for 'SLUG' [16.4](#section-16.4). The Link Relation Registration "edit" [16.5](#section-16.5). The Link Relation Registration "edit-media" [16.6](#section-16.6). The Atom Format Media Type Parameter [17](#section-17). References [17.1](#section-17.1). Normative References [17.2](#section-17.2). Informative References [Appendix A](#appendix-A). Contributors [Appendix B](#appendix-B). RELAX NG Compact Schema ............................... 1. Introduction --------------- The Atom Publishing Protocol is an application-level protocol for publishing and editing Web Resources using HTTP [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)] and XML 1.0 [[REC-xml](#ref-REC-xml)]. The protocol supports the creation of Web Resources and provides facilities for: o Collections: Sets of Resources, which can be retrieved in whole or in part. o Services: Discovery and description of Collections. o Editing: Creating, editing, and deleting Resources. The Atom Publishing Protocol is different from many contemporary protocols in that the server is given wide latitude in processing requests from clients. See [Section 4.4](#section-4.4) for more details. 2. Notational Conventions ------------------------- The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)]. ### 2.1. XML-Related Conventions #### 2.1.1. Referring to Information Items Atom Protocol Document formats are specified in terms of the XML Information Set [[REC-xml-infoset](#ref-REC-xml-infoset)], serialized as XML 1.0 [[REC-xml](#ref-REC-xml)]. The Infoset terms "Element Information Item" and "Attribute Information Item" are shortened to "element" and "attribute" respectively. Therefore, when this specification uses the term "element", it is referring to an Element Information Item, and when it uses the term "attribute", it is referring to an Attribute Information Item. #### 2.1.2. RELAX NG Schema Some sections of this specification are illustrated with fragments of a non-normative RELAX NG Compact schema [[RNC](#ref-RNC)]. However, the text of this specification provides the definition of conformance. Complete schemas appear in [Appendix B](#appendix-B). #### 2.1.3. Use of "xml:base" and "xml:lang" XML elements defined by this specification MAY have an "xml:base" attribute [[REC-xmlbase](#ref-REC-xmlbase)]. When xml:base is used, it serves the function described in [Section 5.1.1](#section-5.1.1) of URI Generic Syntax [[RFC3986](https://datatracker.ietf.org/doc/html/rfc3986)], by establishing the base URI (or IRI, Internationalized Resource Identifier [[RFC3987](https://datatracker.ietf.org/doc/html/rfc3987)]) for resolving relative references found within the scope of the "xml:base" attribute. Any element defined by this specification MAY have an "xml:lang" attribute, whose content indicates the natural language for the element and its descendants. Requirements regarding the content and interpretation of "xml:lang" are specified in [Section 2.12](#section-2.12) of XML 1.0 [[REC-xml](#ref-REC-xml)]. 3. Terminology -------------- For convenience, this protocol can be referred to as the "Atom Protocol" or "AtomPub". The following terminology is used by this specification: o URI - A Uniform Resource Identifier as defined in [[RFC3986](https://datatracker.ietf.org/doc/html/rfc3986)]. In this specification, the phrase "the URI of a document" is shorthand for "a URI which, when dereferenced, is expected to produce that document as a representation". o IRI - An Internationalized Resource Identifier as defined in [[RFC3987](https://datatracker.ietf.org/doc/html/rfc3987)]. Before an IRI found in a document is used by HTTP, the IRI is first converted to a URI. See [Section 4.1](#section-4.1). o Resource - A network-accessible data object or service identified by an IRI, as defined in [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]. See [[REC-webarch](#ref-REC-webarch)] for further discussion on Resources. o relation (or "relation of") - Refers to the "rel" attribute value of an atom:link element. o Representation - An entity included with a request or response as defined in [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]. o Collection - A Resource that contains a set of Member Resources. Collections are represented as Atom Feeds. See [Section 9](#section-9). o Member (or Member Resource) - A Resource whose IRI is listed in a Collection by an atom:link element with a relation of "edit" or "edit-media". See [Section 9.1](#section-9.1). The protocol defines two kinds of Members: \* Entry Resource - Members of a Collection that are represented as Atom Entry Documents, as defined in [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)]. \* Media Resource - Members of a Collection that have representations other than Atom Entry Documents. o Media Link Entry - An Entry Resource that contains metadata about a Media Resource. See [Section 9.6](#section-9.6). o Workspace - A named group of Collections. See [Section 8.1](#section-8.1). o Service Document - A document that describes the location and capabilities of one or more Collections, grouped into Workspaces. See [Section 8](#section-8). o Category Document - A document that describes the categories allowed in a Collection. See [Section 7](#section-7). 4. Protocol Model ----------------- The Atom Protocol specifies operations for publishing and editing Resources using HTTP. It uses Atom-formatted representations to describe the state and metadata of those Resources. It defines how Collections of Resources can be organized, and it specifies formats to support their discovery, grouping and categorization. ### 4.1. Identity and Naming Atom Protocol documents allow the use of IRIs [[RFC3987](https://datatracker.ietf.org/doc/html/rfc3987)] as well as URIs [[RFC3986](https://datatracker.ietf.org/doc/html/rfc3986)] to identify Resources. Before an IRI in a document is used by HTTP, the IRI is first converted to a URI according to the procedure defined in [Section 3.1 of [RFC3987]](https://datatracker.ietf.org/doc/html/rfc3987#section-3.1). In accordance with that specification, the conversion SHOULD be applied as late as possible. Conversion does not imply Resource creation -- the IRI and the URI into which it is converted identify the same Resource. While the Atom Protocol specifies the formats of the representations that are exchanged and the actions that can be performed on the IRIs embedded in those representations, it does not constrain the form of the URIs that are used. HTTP [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)] specifies that the URI space of each server is controlled by that server, and this protocol imposes no further constraints on that control. ### 4.2. Documents and Resource Classification A Resource whose IRI is listed in a Collection is called a Member Resource. The protocol defines two kinds of Member Resources -- Entry Resources and Media Resources. Entry Resources are represented as Atom Entry Documents [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)]. Media Resources can have representations in any media type. A Media Resource is described within a Collection using an Entry called a Media Link Entry. This diagram shows the classification of Resources within the Atom Protocol: Member Resources | ----------------- | | Entry Resources Media Resources | Media Link Entry The Atom Protocol defines Collection Resources for managing and organizing both kinds of Member Resource. A Collection is represented by an Atom Feed Document. A Collection Feed's Entries contain the IRIs of, and metadata about, the Collection's Member Resources. A Collection Feed can contain any number of Entries, which might represent all the Members of the Collection, or an ordered subset of them (see [Section 10.1](#section-10.1)). In the diagram of a Collection below, there are two Entries. The first contains the IRI of an Entry Resource. The second contains the IRIs of both a Media Resource and a Media Link Entry, which contains the metadata for that Media Resource: Collection | o- Entry | | | o- Member Entry IRI (Entry Resource) | o- Entry | o- Member Entry IRI (Media Link Entry) | o- Media IRI (Media Resource) The Atom Protocol does not make a distinction between Feeds used for Collections and other Atom Feeds. The only mechanism that this specification supplies for indicating that a Feed is a Collection Feed is the presence of the Feed's IRI in a Service Document. Service Documents represent server-defined groups of Collections, and are used to initialize the process of creating and editing Resources. These groups of Collections are called Workspaces. Workspaces have names, but no IRIs, and no specified processing model. The Service Document can indicate which media types, and which categories, a Collection will accept. In the diagram below, there are two Workspaces each describing the IRIs, acceptable media types, and categories for a Collection: Service o- Workspace | | | o- Collection | | | o- IRI, categories, media types | o- Workspace | o- Collection | o- IRI, categories, media types ### 4.3. Control and Publishing The Atom Publishing Protocol uses HTTP methods to author Member Resources as follows: o GET is used to retrieve a representation of a known Resource. o POST is used to create a new, dynamically named, Resource. When the client submits non-Atom-Entry representations to a Collection for creation, two Resources are always created -- a Media Entry for the requested Resource, and a Media Link Entry for metadata about the Resource that will appear in the Collection. o PUT is used to edit a known Resource. It is not used for Resource creation. o DELETE is used to remove a known Resource. The Atom Protocol only covers the creating, editing, and deleting of Entry and Media Resources. Other Resources could be created, edited, and deleted as the result of manipulating a Collection, but the number of those Resources, their media types, and effects of Atom Protocol operations on them are outside the scope of this specification. Since all aspects of client-server interaction are defined in terms of HTTP, [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)] should be consulted for any areas not covered in this specification. ### 4.4. Client Implementation Considerations The Atom Protocol imposes few restrictions on the actions of servers. Unless a constraint is specified here, servers can be expected to vary in behavior, in particular around the manipulation of Atom Entries sent by clients. For example, although this specification only defines the expected behavior of Collections with respect to GET and POST, this does not imply that PUT, DELETE, PROPPATCH, and others are forbidden on Collection Resources -- only that this specification does not define what the server's response would be to those methods. Similarly, while some HTTP status codes are mentioned explicitly, clients ought to be prepared to handle any status code from a server. Servers can choose to accept, reject, delay, moderate, censor, reformat, translate, relocate, or re-categorize the content submitted to them. Only some of these choices are immediately relayed back to the client in responses to client requests; other choices may only become apparent later, in the feed or published entries. The same series of requests to two different publishing sites can result in a different series of HTTP responses, different resulting feeds, or different entry contents. As a result, client software has to be written flexibly to accept what the server decides are the results of its submissions. Any server response or server content modification not explicitly forbidden by this specification or HTTP [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)] is therefore allowed. 5. Protocol Operations ---------------------- While specific HTTP status codes are shown in the interaction diagrams below, an AtomPub client should be prepared to handle any status code. For example, a PUT to a Member URI could result in the return of a "204 No Content" status code, which still indicates success. ### 5.1. Retrieving a Service Document Client Server | | | 1.) GET to Service Document URI | |------------------------------------------>| | | | 2.) 200 Ok | | Service Document | |<------------------------------------------| | | 1. The client sends a GET request to the URI of the Service Document. 2. The server responds with a Service Document enumerating the IRIs of a group of Collections and the capabilities of those Collections supported by the server. The content of this document can vary based on aspects of the client request, including, but not limited to, authentication credentials. ### 5.2. Listing Collection Members To list the Members of a Collection, the client sends a GET request to the URI of a Collection. An Atom Feed Document is returned whose Entries contain the IRIs of Member Resources. The returned Feed may describe all, or only a partial list, of the Members in a Collection (see [Section 10](#section-10)). Client Server | | | 1.) GET to Collection URI | |------------------------------->| | | | 2.) 200 Ok | | Atom Feed Document | |<-------------------------------| | | 1. The client sends a GET request to the URI of the Collection. 2. The server responds with an Atom Feed Document containing the IRIs of the Collection Members. ### 5.3. Creating a Resource Client Server | | | 1.) POST to Collection URI | | Member Representation | |------------------------------------------>| | | | 2.) 201 Created | | Location: Member Entry URI | |<------------------------------------------| | | 1. The client POSTs a representation of the Member to the URI of the Collection. 2. If the Member Resource was created successfully, the server responds with a status code of 201 and a Location header that contains the IRI of the newly created Entry Resource. Media Resources could have also been created and their IRIs can be found through the Entry Resource. See [Section 9.6](#section-9.6) for more details. ### 5.4. Editing a Resource Once a Resource has been created and its Member URI is known, that URI can be used to retrieve, edit, and delete the Resource. [Section](#section-11) [11](#section-11) describes extensions to the Atom Syndication Format used in the Atom Protocol for editing purposes. #### 5.4.1. Retrieving a Resource Client Server | | | 1.) GET to Member URI | |------------------------------------------>| | | | 2.) 200 Ok | | Member Representation | |<------------------------------------------| | | 1. The client sends a GET request to the URI of a Member Resource to retrieve its representation. 2. The server responds with the representation of the Member Resource. #### 5.4.2. Editing a Resource Client Server | | | 1.) PUT to Member URI | | Member Representation | |------------------------------------------>| | | | 2.) 200 OK | |<------------------------------------------| 1. The client sends a PUT request to store a representation of a Member Resource. 2. If the request is successful, the server responds with a status code of 200. #### 5.4.3. Deleting a Resource Client Server | | | 1.) DELETE to Member URI | |------------------------------------------>| | | | 2.) 200 OK | |<------------------------------------------| | | 1. The client sends a DELETE request to the URI of a Member Resource. 2. If the deletion is successful, the server responds with a status code of 200. A different approach is taken for deleting Media Resources; see [Section 9.4](#section-9.4) for details. ### 5.5. Use of HTTP Response Codes The Atom Protocol uses the response status codes defined in HTTP to indicate the success or failure of an operation. Consult the HTTP specification [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)] for detailed definitions of each status code. Implementers are asked to note that according to the HTTP specification, HTTP 4xx and 5xx response entities SHOULD include a human-readable explanation of the error. 6. Protocol Documents --------------------- ### 6.1. Document Types This specification defines two kinds of documents -- Category Documents and Service Documents. A Category Document ([Section 7](#section-7)) contains lists of categories specified using the "atom:category" element from the Atom Syndication Format (see [Section 4.2.2 of [RFC4287]](https://datatracker.ietf.org/doc/html/rfc4287#section-4.2.2)). A Service Document ([Section 8](#section-8)) groups available Collections into Workspaces. The namespace name [[REC-xml-names](#ref-REC-xml-names)] for either kind of document is: [http://www.w3.org/2007/app](https://www.w3.org/2007/app) Atom Publishing Protocol XML Documents MUST be "namespace-well- formed" as specified in Section 7 of [[REC-xml-names](#ref-REC-xml-names)]. This specification uses the prefix "app:" for the namespace name. The prefix "atom:" is used for "http://www.w3.org/2005/Atom", the namespace name of the Atom Syndication Format [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)]. These namespace prefixes are not semantically significant. This specification does not define any DTDs for Atom Protocol formats, and hence does not require them to be "valid" in the sense used by [[REC-xml](#ref-REC-xml)]. ### 6.2. Document Extensibility Unrecognized markup in an Atom Publishing Protocol document is considered "foreign markup" as defined in [Section 6](#section-6) of the Atom Syndication Format [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)]. Foreign markup can be used anywhere within a Category or Service Document unless it is explicitly forbidden. Processors that encounter foreign markup MUST NOT stop processing and MUST NOT signal an error. Clients SHOULD preserve foreign markup when transmitting such documents. The namespace name "http://www.w3.org/2007/app" is reserved for forward-compatible revisions of the Category and Service Document types. This does not exclude the addition of elements and attributes that might not be recognized by processors conformant to this specification. Such unrecognized markup from the "http://www.w3.org/2007/app" namespace MUST be treated as foreign markup. 7. Category Documents --------------------- Category Documents contain lists of categories described using the "atom:category" element from the Atom Syndication Format [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)]. Categories can also appear in Service Documents, where they indicate the categories allowed in a Collection (see [Section 8.3.6](#section-8.3.6)). Category Documents are identified with the "application/atomcat+xml" media type (see [Section 16.1](#section-16.1)). ### 7.1. Example <?xml version="1.0" ?> <app:categories xmlns:app="http://www.w3.org/2007/app" xmlns:atom="http://www.w3.org/2005/Atom" fixed="yes" scheme="http://example.com/cats/big3"> <atom:category term="animal" /> <atom:category term="vegetable" /> <atom:category term="mineral" /> </app:categories> This Category Document contains atom:category elements, with the terms 'animal', 'vegetable', and 'mineral'. None of the categories use the "label" attribute defined in [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)]. They all inherit the "http://example.com/cats/big3" "scheme" attribute declared on the app:categories element. Therefore if the 'mineral' category were to appear in an Atom Entry or Feed Document, it would appear as: <atom:category scheme="http://example.com/cats/big3" term="mineral"/> ### 7.2. Element Definitions #### 7.2.1. The "app:categories" Element The root of a Category Document is the "app:categories" element. An app:categories element can contain zero or more atom:category elements from the Atom Syndication Format [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)] namespace ("http://www.w3.org/2005/Atom"). An atom:category child element that has no "scheme" attribute inherits the attribute from its app:categories parent. An atom: category child element with an existing "scheme" attribute does not inherit the "scheme" value of its app:categories parent element. atomCategory = element atom:category { atomCommonAttributes, attribute term { text }, attribute scheme { atomURI }?, attribute label { text }?, undefinedContent } appInlineCategories = element app:categories { attribute fixed { "yes" | "no" }?, attribute scheme { atomURI }?, (atomCategory\*, undefinedContent) } appOutOfLineCategories = element app:categories { attribute href { atomURI }, undefinedContent } appCategories = appInlineCategories | appOutOfLineCategories ##### 7.2.1.1. Attributes of "app:categories" The app:categories element can contain a "fixed" attribute, with a value of either "yes" or "no", indicating whether the list of categories is a fixed or an open set. The absence of the "fixed" attribute is equivalent to the presence of a "fixed" attribute with a value of "no". Alternatively, the app:categories element MAY contain an "href" attribute, whose value MUST be an IRI reference identifying a Category Document. If the "href" attribute is provided, the app: categories element MUST be empty and MUST NOT have the "fixed" or "scheme" attributes. 8. Service Documents -------------------- For authoring to commence, a client needs to discover the capabilities and locations of the available Collections. Service Documents are designed to support this discovery process. How Service Documents are discovered is not defined in this specification. Service Documents are identified with the "application/atomsvc+xml" media type (see [Section 16.2](#section-16.2)). ### 8.1. Workspaces A Service Document groups Collections into Workspaces. Operations on Workspaces, such as creation or deletion, are not defined by this specification. This specification assigns no meaning to Workspaces; that is, a Workspace does not imply any specific processing assumptions. There is no requirement that a server support multiple Workspaces. In addition, a Collection MAY appear in more than one Workspace. ### 8.2. Example <?xml version="1.0" encoding='utf-8'?> <service xmlns="http://www.w3.org/2007/app" xmlns:atom="http://www.w3.org/2005/Atom"> <workspace> <atom:title>Main Site</atom:title> <collection href="http://example.org/blog/main" > <atom:title>My Blog Entries</atom:title> <categories href="http://example.com/cats/forMain.cats" /> </collection> <collection href="http://example.org/blog/pic" > <atom:title>Pictures</atom:title> <accept>image/png</accept> <accept>image/jpeg</accept> <accept>image/gif</accept> </collection> </workspace> <workspace> <atom:title>Sidebar Blog</atom:title> <collection href="http://example.org/sidebar/list" > <atom:title>Remaindered Links</atom:title> <accept>application/atom+xml;type=entry</accept> <categories fixed="yes"> <atom:category scheme="http://example.org/extra-cats/" term="joke" /> <atom:category scheme="http://example.org/extra-cats/" term="serious" /> </categories> </collection> </workspace> </service> The Service Document above describes two Workspaces. The first Workspace is called "Main Site", and has two Collections called "My Blog Entries" and "Pictures", whose IRIs are "http://example.org/blog/main" and "http://example.org/blog/pic" respectively. The "Pictures" Collection includes three "accept" elements indicating the types of image files the client can send to the Collection to create new Media Resources (entries associated with Media Resources are discussed in [Section 9.6](#section-9.6)). The second Workspace is called "Sidebar Blog" and has a single Collection called "Remaindered Links" whose IRI is "http://example.org/sidebar/list". The Collection has an "accept" element whose content is "application/atom+xml;type=entry", indicating it will accept Atom Entries from a client. Within each of the two Entry Collections, the "categories" element provides a list of available categories for Member Entries. In the "My Blog Entries" Collection, the list of available categories is available through the "href" attribute. The "Sidebar Blog" Collection provides a category list within the Service Document, but states the list is fixed, signaling a request from the server that Entries be POSTed using only those two categories. ### 8.3. Element Definitions #### 8.3.1. The "app:service" Element The root of a Service Document is the "app:service" element. The app:service element is the container for service information associated with one or more Workspaces. An app:service element MUST contain one or more app:workspace elements. namespace app = "http://www.w3.org/2007/app" start = appService appService = element app:service { appCommonAttributes, ( appWorkspace+ & extensionElement\* ) } #### 8.3.2. The "app:workspace" Element Workspaces are server-defined groups of Collections. The "app: workspace" element contains zero or more app:collection elements describing the Collections of Resources available for editing. appWorkspace = element app:workspace { appCommonAttributes, ( atomTitle & appCollection\* & extensionSansTitleElement\* ) } atomTitle = element atom:title { atomTextConstruct } ##### 8.3.2.1. The "atom:title" Element The app:workspace element MUST contain one "atom:title" element (as defined in [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)]), giving a human-readable title for the Workspace. #### 8.3.3. The "app:collection" Element The "app:collection" element describes a Collection. The app: collection element MUST contain one atom:title element. The app:collection element MAY contain any number of app:accept elements, indicating the types of representations accepted by the Collection. The order of such elements is not significant. The app:collection element MAY contain any number of app:categories elements. appCollection = element app:collection { appCommonAttributes, attribute href { atomURI }, ( atomTitle & appAccept\* & appCategories\* & extensionSansTitleElement\* ) } ##### 8.3.3.1. The "href" Attribute The app:collection element MUST contain an "href" attribute, whose value gives the IRI of the Collection. ##### 8.3.3.2. The "atom:title" Element The "atom:title" element is defined in [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)] and gives a human- readable title for the Collection. #### 8.3.4. The "app:accept" Element The content of an "app:accept" element value is a media range as defined in [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]. The media range specifies a type of representation that can be POSTed to a Collection. The app:accept element is similar to the HTTP Accept request-header [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]. Media type parameters are allowed within app:accept, but app:accept has no notion of preference -- "accept-params" or "q" arguments, as specified in [Section 14.1 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-14.1) are not significant. White space (as defined in [[REC-xml](#ref-REC-xml)]) around the app:accept element's media range is insignificant and MUST be ignored. A value of "application/atom+xml;type=entry" MAY appear in any app: accept list of media ranges and indicates that Atom Entry Documents can be POSTed to the Collection. If no app:accept element is present, clients SHOULD treat this as equivalent to an app:accept element with the content "application/atom+xml;type=entry". If one app:accept element exists and is empty, clients SHOULD assume that the Collection does not support the creation of new Entries. appAccept = element app:accept { appCommonAttributes, ( text? ) } #### 8.3.5. Usage in Atom Feed Documents The app:collection element MAY appear as a child of an atom:feed or atom:source element in an Atom Feed Document. Its content identifies a Collection by which new Entries can be added to appear in the feed. When it appears in an atom:feed or atom:source element, the app: collection element is considered foreign markup as defined in [Section](https://datatracker.ietf.org/doc/html/rfc4287#section-6) [6 of [RFC4287]](https://datatracker.ietf.org/doc/html/rfc4287#section-6). #### 8.3.6. The "app:categories" Element The "app:categories" element provides a list of the categories that can be applied to the members of a Collection. See [Section 7.2.1](#section-7.2.1) for the detailed definition of app:categories. The server MAY reject attempts to create or store members whose categories are not present in its categories list. A Collection that indicates the category set is open SHOULD NOT reject otherwise acceptable members whose categories are not in its categories list. The absence of an app:categories element means that the category handling of the Collection is unspecified. A "fixed" category list that contains zero categories indicates the Collection does not accept category data. 9. Creating and Editing Resources --------------------------------- ### 9.1. Member URIs The Member URI allows clients to retrieve, edit, and delete a Member Resource using HTTP's GET, PUT, and DELETE methods. Entry Resources are represented as Atom Entry documents. Member URIs appear in two places. They are returned in a Location header after successful Resource creation using POST, as described in [Section 9.2](#section-9.2) below. They can also appear in a Collection Feed's Entries, as atom:link elements with a link relation of "edit". A Member Entry SHOULD contain such an atom:link element with a link relation of "edit", which indicates the Member URI. ### 9.2. Creating Resources with POST To add members to a Collection, clients send POST requests to the URI of the Collection. Successful member creation is indicated with a 201 ("Created") response code. When the Collection responds with a status code of 201, it SHOULD also return a response body, which MUST be an Atom Entry Document representing the newly created Resource. Since the server is free to alter the POSTed Entry, for example, by changing the content of the atom:id element, returning the Entry can be useful to the client, enabling it to correlate the client and server views of the new Entry. When a Member Resource is created, its Member Entry URI MUST be returned in a Location header in the Collection's response. If the creation request contained an Atom Entry Document, and the subsequent response from the server contains a Content-Location header that matches the Location header character-for-character, then the client is authorized to interpret the response entity as being a complete representation of the newly created Entry. Without a matching Content-Location header, the client MUST NOT assume the returned entity is a complete representation of the created Resource. The request body sent with the POST need not be an Atom Entry. For example, it might be a picture or a movie. Collections MAY return a response with a status code of 415 ("Unsupported Media Type") to indicate that the media type of the POSTed entity is not allowed or supported by the Collection. For a discussion of the issues in creating such content, see [Section 9.6](#section-9.6). #### 9.2.1. Example Below, the client sends a POST request containing an Atom Entry representation using the URI of the Collection: POST /edit/ HTTP/1.1 Host: example.org User-Agent: Thingio/1.0 Authorization: Basic ZGFmZnk6c2VjZXJldA== Content-Type: application/atom+xml;type=entry Content-Length: nnn Slug: First Post <?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom"> <title>Atom-Powered Robots Run Amok</title> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <author><name>John Doe</name></author> <content>Some text.</content> </entry> The server signals a successful creation with a status code of 201. The response includes a Location header indicating the Member Entry URI of the Atom Entry, and a representation of that Entry in the body of the response. HTTP/1.1 201 Created Date: Fri, 7 Oct 2005 17:17:11 GMT Content-Length: nnn Content-Type: application/atom+xml;type=entry;charset="utf-8" Location: http://example.org/edit/first-post.atom ETag: "c180de84f991g8" <?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom"> <title>Atom-Powered Robots Run Amok</title> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <author><name>John Doe</name></author> <content>Some text.</content> <link rel="edit" href="http://example.org/edit/first-post.atom"/> </entry> The Entry created and returned by the Collection might not match the Entry POSTed by the client. A server MAY change the values of various elements in the Entry, such as the atom:id, atom:updated, and atom:author values, and MAY choose to remove or add other elements and attributes, or change element content and attribute values. ### 9.3. Editing Resources with PUT To edit a Member Resource, a client sends a PUT request to its Member URI, as specified in [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]. To avoid unintentional loss of data when editing Member Entries or Media Link Entries, an Atom Protocol client SHOULD preserve all metadata that has not been intentionally modified, including unknown foreign markup as defined in [Section 6 of [RFC4287]](https://datatracker.ietf.org/doc/html/rfc4287#section-6). ### 9.4. Deleting Resources with DELETE To delete a Member Resource, a client sends a DELETE request to its Member URI, as specified in [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]. The deletion of a Media Link Entry SHOULD result in the deletion of the corresponding Media Resource. ### 9.5. Caching and Entity Tags Implementers are advised to pay attention to cache controls and to make use of the mechanisms available in HTTP when editing Resources, in particular, entity-tags as outlined in [[NOTE-detect-lost-update](#ref-NOTE-detect-lost-update)]. Clients are not assured to receive the most recent representations of Collection Members using GET if the server is authorizing intermediaries to cache them. #### 9.5.1. Example Below, the client creates a Member Entry using POST: POST /myblog/entries HTTP/1.1 Host: example.org Authorization: Basic ZGFmZnk6c2VjZXJldA== Content-Type: application/atom+xml;type=entry Content-Length: nnn Slug: First Post <?xml version="1.0" ?> <entry xmlns="http://www.w3.org/2005/Atom"> <title>Atom-Powered Robots Run Amok</title> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2007-02-123T17:09:02Z</updated> <author><name>Captain Lansing</name></author> <content>It's something moving... solid metal</content> </entry> The server signals a successful creation with a status code of 201, and returns an ETag header in the response. Because, in this case, the server returned a Content-Location header and Location header with the same value, the returned Entry representation can be understood to be a complete representation of the newly created Entry (see [Section 9.2](#section-9.2)). HTTP/1.1 201 Created Date: Fri, 23 Feb 2007 21:17:11 GMT Content-Length: nnn Content-Type: application/atom+xml;type=entry Location: http://example.org/edit/first-post.atom Content-Location: http://example.org/edit/first-post.atom ETag: "e180ee84f0671b1" <?xml version="1.0" ?> <entry xmlns="http://www.w3.org/2005/Atom"> <title>Atom-Powered Robots Run Amok</title> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2007-02-123T17:09:02Z</updated> <author><name>Captain Lansing</name></author> <content>It's something moving... solid metal</content> </entry> The client can, if it wishes, use the returned ETag value to later construct a "Conditional GET" as defined in [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)]. In this case, prior to editing, the client sends the ETag value for the Member using the If-None-Match header. GET /edit/first-post.atom HTTP/1.1 Host: example.org Authorization: Basic ZGFmZnk6c2VjZXJldA== If-None-Match: "e180ee84f0671b1" If the Entry has not been modified, the response will be a status code of 304 ("Not Modified"). This allows the client to determine whether it still has the most recent representation of the Entry at the time of editing. HTTP/1.1 304 Not Modified Date: Sat, 24 Feb 2007 13:17:11 GMT After editing, the client can PUT the Entry and send the ETag entity value in an If-Match header, informing the server to accept the entry on the condition that the entity value sent still matches the server's. PUT /edit/first-post.atom HTTP/1.1 Host: example.org Authorization: Basic ZGFmZnk6c2VjZXJldA== Content-Type: application/atom+xml;type=entry Content-Length: nnn If-Match: "e180ee84f0671b1" <?xml version="1.0" ?> <entry xmlns="http://www.w3.org/2005/Atom"> <title>Atom-Powered Robots Run Amok</title> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2007-02-24T16:34:06Z</updated> <author><name>Captain Lansing</name></author> <content>Update: it's a hoax!</content> </entry> The server however has since received a more recent copy than the client's, and it responds with a status code of 412 ("Precondition Failed"). HTTP/1.1 412 Precondition Failed Date: Sat, 24 Feb 2007 16:34:11 GMT This informs the client that the server has a more recent version of the Entry and will not allow the sent entity to be stored. ### 9.6. Media Resources and Media Link Entries A client can POST Media Resources as well as Entry Resources to a Collection. If a server accepts such a request, then it MUST create two new Resources -- one that corresponds to the entity sent in the request, called the Media Resource, and an associated Member Entry, called the Media Link Entry. Media Link Entries are represented as Atom Entries, and appear in the Collection. The Media Link Entry contains the metadata and IRI of the (perhaps non-textual) Media Resource. The Media Link Entry thus makes the metadata about the Media Resource separately available for retrieval and alteration. The server can signal the media types it will accept using the app: accept element in the Service Document, as specified in [Section](#section-8.3.4) [8.3.4](#section-8.3.4). Successful responses to creation requests MUST include the URI of the Media Link Entry in the Location header. The Media Link Entry SHOULD contain an atom:link element with a link relation of "edit-media" that contains the Media Resource IRI. The Media Link Entry MUST have an atom:content element with a "src" attribute. The value of the "src" attribute is an IRI for the newly created Media Resource. It is OPTIONAL that the IRI of the "src" attribute on the atom:content element be the same as the Media Resource IRI. For example, the "src" attribute value might instead be a link into a static cache or content distribution network and not the Media Resource IRI. Implementers are asked to note that [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)] specifies that Atom Entries MUST contain an atom:summary element. Thus, upon successful creation of a Media Link Entry, a server MAY choose to populate the atom:summary element (as well as any other mandatory elements such as atom:id, atom:author, and atom:title) with content derived from the POSTed entity or from any other source. A server might not allow a client to modify the server-selected values for these elements. For Resource creation, this specification only defines cases where the POST body has an Atom Entry entity declared as an Atom media type ("application/atom+xml"), or a non-Atom entity declared as a non-Atom media type. When a client is POSTing an Atom Entry to a Collection, it may use a media type of either "application/atom+xml" or "application/atom +xml;type=entry". This specification does not specify any request semantics or server behavior in the case where the POSTed media type is "application/atom+xml" but the body is something other than an Atom Entry. In particular, what happens on POSTing an Atom Feed Document to a Collection using the "application/ atom+xml" media type is undefined. The Atom Protocol does not specify a means to create multiple representations of the same Resource (for example, a PNG and a JPG of the same image) either on creation or editing. #### 9.6.1. Examples Below, the client sends a POST request containing a PNG image to the URI of a Collection that accepts PNG images: POST /edit/ HTTP/1.1 Host: media.example.org Content-Type: image/png Slug: The Beach Authorization: Basic ZGFmZnk6c2VjZXJldA== Content-Length: nnn ...binary data The server signals a successful creation with a status code of 201. The response includes a Location header indicating the Member URI of the Media Link Entry and a representation of that entry in the body of the response. The Media Link Entry includes a content element with a "src" attribute. It also contains a link with a link relation of "edit-media", specifying the IRI to be used for modifying the Media Resource. HTTP/1.1 201 Created Date: Fri, 7 Oct 2005 17:17:11 GMT Content-Length: nnn Content-Type: application/atom+xml;type=entry;charset="utf-8" Location: http://example.org/media/edit/the\_beach.atom <?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom"> <title>The Beach</title> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2005-10-07T17:17:08Z</updated> <author><name>Daffy</name></author> <summary type="text" /> <content type="image/png" src="http://media.example.org/the\_beach.png"/> <link rel="edit-media" href="http://media.example.org/edit/the\_beach.png" /> <link rel="edit" href="http://example.org/media/edit/the\_beach.atom" /> </entry> Later, the client sends a PUT request containing the new PNG using the URI indicated in the Media Link Entry's "edit-media" link: PUT /edit/the\_beach.png HTTP/1.1 Host: media.example.org Content-Type: image/png Authorization: Basic ZGFmZnk6c2VjZXJldA== Content-Length: nnn ...binary data The server signals a successful edit with a status code of 200. HTTP/1.1 200 Ok Date: Fri, 8 Oct 2006 17:17:11 GMT The client can edit the metadata for the picture. First GET the Media Link Entry: GET /media/edit/the\_beach.atom HTTP/1.1 Host: example.org Authorization: Basic ZGFmZnk6c2VjZXJldA== The Media Link Entry is returned. HTTP/1.1 200 Ok Date: Fri, 7 Oct 2005 17:18:11 GMT Content-Length: nnn Content-Type: application/atom+xml;type=entry;charset="utf-8" ETag: "c181bb840673b5" <?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom"> <title>The Beach</title> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2005-10-07T17:17:08Z</updated> <author><name>Daffy</name></author> <summary type="text" /> <content type="image/png" src="http://media.example.org/the\_beach.png"/> <link rel="edit-media" href="http://media.example.org/edit/the\_beach.png" /> <link rel="edit" href="http://example.org/media/edit/the\_beach.atom" /> </entry> The metadata can be updated, in this case to add a summary, and then PUT back to the server. PUT /media/edit/the\_beach.atom HTTP/1.1 Host: example.org Authorization: Basic ZGFmZnk6c2VjZXJldA== Content-Type: application/atom+xml;type=entry Content-Length: nnn If-Match: "c181bb840673b5" <?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom"> <title>The Beach</title> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2005-10-07T17:17:08Z</updated> <author><name>Daffy</name></author> <summary type="text"> A nice sunset picture over the water. </summary> <content type="image/png" src="http://media.example.org/the\_beach.png"/> <link rel="edit-media" href="http://media.example.org/edit/the\_beach.png" /> <link rel="edit" href="http://example.org/media/edit/the\_beach.atom" /> </entry> The update was successful. HTTP/1.1 200 Ok Date: Fri, 7 Oct 2005 17:19:11 GMT Content-Length: 0 Multiple Media Resources can be added to the Collection. POST /edit/ HTTP/1.1 Host: media.example.org Content-Type: image/png Slug: The Pier Authorization: Basic ZGFmZnk6c2VjZXJldA== Content-Length: nnn ...binary data The Resource is created successfully. HTTP/1.1 201 Created Date: Fri, 7 Oct 2005 17:17:11 GMT Content-Length: nnn Content-Type: application/atom+xml;type=entry;charset="utf-8" Location: http://example.org/media/edit/the\_pier.atom <?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom"> <title>The Pier</title> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efe6b</id> <updated>2005-10-07T17:26:43Z</updated> <author><name>Daffy</name></author> <summary type="text" /> <content type="image/png" src="http://media.example.org/the\_pier.png"/> <link rel="edit-media" href="http://media.example.org/edit/the\_pier.png" /> <link rel="edit" href="http://example.org/media/edit/the\_pier.atom" /> </entry> The client can now create a new Atom Entry in the blog Entry Collection that references the two newly created Media Resources. POST /blog/ HTTP/1.1 Host: example.org Content-Type: application/atom+xml;type=entry Slug: A day at the beach Authorization: Basic ZGFmZnk6c2VjZXJldA== Content-Length: nnn <?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom"> <title>A fun day at the beach</title> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6b</id> <updated>2005-10-07T17:40:02Z</updated> <author><name>Daffy</name></author> <content type="xhtml"> <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"> <xhtml:p>We had a good day at the beach. <xhtml:img alt="the beach" src="http://media.example.org/the\_beach.png"/> </xhtml:p> <xhtml:p>Later we walked down to the pier. <xhtml:img alt="the pier" src="http://media.example.org/the\_pier.png"/> </xhtml:p> </xhtml:div> </content> </entry> The Resource is created successfully. HTTP/1.1 200 Ok Date: Fri, 7 Oct 2005 17:20:11 GMT Content-Length: nnn Content-Type: application/atom+xml;type=entry;charset="utf-8" Location: http://example.org/blog/atom/a-day-at-the-beach.atom <?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom"> <title>A fun day at the beach</title> <id>http://example.org/blog/a-day-at-the-beach.xhtml</id> <updated>2005-10-07T17:43:07Z</updated> <author><name>Daffy</name></author> <content type="xhtml"> <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"> <xhtml:p>We had a good day at the beach. <xhtml:img alt="the beach" src="http://media.example.org/the\_beach.png"/> </xhtml:p> <xhtml:p>Later we walked down to the pier. <xhtml:img alt="the pier" src="http://media.example.org/the\_pier.png"/> </xhtml:p> </xhtml:div> </content> <link rel="edit" href="http://example.org/blog/edit/a-day-at-the-beach.atom"/> <link rel="alternate" type="text/html" href="http://example.org/blog/a-day-at-the-beach.html"/> </entry> Note that the returned Entry contains a link with a relation of "alternate" that points to the associated HTML page that was created -- this is not required by this specification, but is included to show the kinds of changes a server can make to an Entry. ### 9.7. The Slug Header Slug is an HTTP entity-header whose presence in a POST to a Collection constitutes a request by the client to use the header's value as part of any URIs that would normally be used to retrieve the to-be-created Entry or Media Resources. Servers MAY use the value of the Slug header when creating the Member URI of the newly created Resource, for instance, by using some or all of the words in the value for the last URI segment. Servers MAY also use the value when creating the atom:id, or as the title of a Media Link Entry (see [Section 9.6](#section-9.6)). Servers MAY choose to ignore the Slug entity-header. Servers MAY alter the header value before using it. For instance, a server might filter out some characters or replace accented letters with non- accented ones, replace spaces with underscores, change case, and so on. #### 9.7.1. Slug Header Syntax The syntax of the Slug header is defined using the augmented BNF syntax defined in [Section 2.1 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-2.1): LWS = <defined in [Section 2.2 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-2.2)> slugtext = %x20-7E | LWS Slug = "Slug" ":" \*slugtext The field value is the percent-encoded value of the UTF-8 encoding of the character sequence to be included (see [Section 2.1 of [RFC3986]](https://datatracker.ietf.org/doc/html/rfc3986#section-2.1) for the definition of percent encoding, and [[RFC3629](https://datatracker.ietf.org/doc/html/rfc3629)] for the definition of the UTF-8 encoding). Implementation note: to produce the field value from a character sequence, first encode it using the UTF-8 encoding, then encode all octets outside the ranges %20-24 and %26-7E using percent encoding (%25 is the ASCII encoding of "%", thus it needs to be escaped). To consume the field value, first reverse the percent encoding, then run the resulting octet sequence through a UTF-8 decoding process. #### 9.7.2. Example Here is an example of the Slug header that uses percent-encoding to represent the Unicode character U+00E8 (LATIN SMALL LETTER E WITH GRAVE): POST /myblog/entries HTTP/1.1 Host: example.org Content-Type: image/png Slug: The Beach at S%C3%A8te Authorization: Basic ZGFmZnk6c2VjZXJldA== Content-Length: nnn ...binary data See [Section 9.2.1](#section-9.2.1) for an example of the Slug header applied to the creation of an Entry Resource. 10. Listing Collections ----------------------- Collection Resources MUST provide representations in the form of Atom Feed Documents whose Entries contain the IRIs of the Members in the Collection. No distinction is made between Collection Feeds and other kinds of Feeds -- a Feed might act both as a 'public' feed for subscription purposes and as a Collection Feed. Each Entry in the Feed Document SHOULD have an atom:link element with a relation of "edit" (see [Section 11.1](#section-11.1)). The Entries in the returned Atom Feed SHOULD be ordered by their "app:edited" property, with the most recently edited Entries coming first in the document order. The app:edited value is not equivalent to the HTTP Last-Modified header and cannot be used to determine the freshness of cached responses. Clients MUST NOT assume that an Atom Entry returned in the Feed is a full representation of an Entry Resource and SHOULD perform a GET on the URI of the Member Entry before editing it. See [Section 9.5](#section-9.5) for a discussion on the implications of cache control directives when obtaining entries. ### 10.1. Collection Partial Lists Collections can contain large numbers of Resources. A client such as a web spider or web browser might be overwhelmed if the response to a GET contained every Entry in a Collection -- in turn the server might also waste bandwidth and processing time on generating a response that cannot be handled. For this reason, servers MAY respond to Collection GET requests with a Feed Document containing a partial list of the Collection's members, and a link to the next partial list feed, if it exists. The first such partial list returned MUST contain the most recently edited member Resources and MUST have an atom:link with a "next" relation whose "href" value is the URI of the next partial list of the Collection. This next partial list will contain the next most recently edited set of Member Resources (and an atom:link to the following partial list if it exists). In addition to the "next" relation, partial list feeds MAY contain link elements with "rel" attribute values of "previous", "first", and "last", that can be used to navigate through the complete set of entries in the Collection. For instance, suppose a client is supplied the URI "http://example.org/entries/go" of a Collection of Member Entries, where the server as a matter of policy avoids generating Feed Documents containing more than 10 Entries. The Atom Feed Document for the Collection will then represent the first partial list of a set of 10 linked Feed Documents. The "first" relation references the initial Feed Document in the set and the "last" relation references the final Feed Document in the set. Within each document, the "previous" and "next" link relations reference the preceding and subsequent documents. <feed xmlns="http://www.w3.org/2005/Atom"> <link rel="first" href="http://example.org/entries/go" /> <link rel="next" href="http://example.org/entries/2" /> <link rel="last" href="http://example.org/entries/10" /> </feed> The "previous" and "next" link elements for the partial list feed located at "http://example.org/entries/2" would look like this: <feed xmlns="http://www.w3.org/2005/Atom"> <link rel="first" href="http://example.org/entries/go" /> <link rel="previous" href="http://example.org/entries/go" /> <link rel="next" href="http://example.org/entries/3" /> <link rel="last" href="http://example.org/entries/10" /> </feed> ### 10.2. The "app:edited" Element The "app:edited" element is a Date construct (as defined by [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)]), whose content indicates the last time an Entry was edited. If the entry has not been edited yet, the content indicates the time it was created. Atom Entry elements in Collection Documents SHOULD contain one app:edited element, and MUST NOT contain more than one. appEdited = element app:edited ( atomDateConstruct ) The server SHOULD change the value of this element every time an Entry Resource or an associated Media Resource has been edited. 11. Atom Format Link Relation Extensions ---------------------------------------- ### 11.1. The "edit" Link Relation This specification adds the value "edit" to the Atom Registry of Link Relations (see [Section 7.1 of [RFC4287]](https://datatracker.ietf.org/doc/html/rfc4287#section-7.1)). The value of "edit" specifies that the value of the href attribute is the IRI of an editable Member Entry. When appearing within an atom:entry, the href IRI can be used to retrieve, update, and delete the Resource represented by that Entry. An atom:entry MUST NOT contain more than one "edit" link relation. ### 11.2. The "edit-media" Link Relation This specification adds the value "edit-media" to the Atom Registry of Link Relations (see [Section 7.1 of [RFC4287]](https://datatracker.ietf.org/doc/html/rfc4287#section-7.1)). When appearing within an atom:entry, the value of the href attribute is an IRI that can be used to modify a Media Resource associated with that Entry. An atom:entry element MAY contain zero or more "edit-media" link relations. An atom:entry MUST NOT contain more than one atom:link element with a "rel" attribute value of "edit-media" that has the same "type" and "hreflang" attribute values. All "edit-media" link relations in the same Entry reference the same Resource. If a client encounters multiple "edit-media" link relations in an Entry then it SHOULD choose a link based on the client preferences for "type" and "hreflang". If a client encounters multiple "edit-media" link relations in an Entry and has no preference based on the "type" and "hreflang" attributes then the client SHOULD pick the first "edit- media" link relation in document order. 12. The Atom Format Type Parameter ---------------------------------- The Atom Syndication Format [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)] defines the "application/ atom+xml" media type to identify both Atom Feed and Atom Entry Documents. Implementation experience has demonstrated that Atom Feed and Entry Documents can have different processing models and that there are situations where they need to be differentiated. This specification defines a "type" parameter used to differentiate the two types of Atom documents. ### 12.1. The "type" parameter This specification defines a new "type" parameter for use with the "application/atom+xml" media type. The "type" parameter has a value of "entry" or "feed". Neither the parameter name nor its value are case sensitive. The value "entry" indicates that the media type identifies an Atom Entry Document. The root element of the document MUST be atom:entry. The value "feed" indicates that the media type identifies an Atom Feed Document. The root element of the document MUST be atom:feed. If not specified, the type is assumed to be unspecified, requiring Atom processors to examine the root element to determine the type of Atom document. #### 12.1.1. Conformance New specifications MAY require that the "type" parameter be used to identify the Atom Document type. Producers of Atom Entry Documents SHOULD use the "type" parameter regardless of whether or not it is mandatory. Producers of Atom Feed Documents MAY use the parameter. Atom processors that do not recognize the "type" parameter MUST ignore its value and examine the root element to determine the document type. Atom processors that do recognize the "type" parameter SHOULD detect and report inconsistencies between the parameter's value and the actual type of the document's root element. 13. Atom Publishing Controls ---------------------------- This specification defines an Atom Format Structured Extension, as defined in [Section 6 of [RFC4287]](https://datatracker.ietf.org/doc/html/rfc4287#section-6), for publishing control within the "http://www.w3.org/2007/app" namespace. ### 13.1. The "app:control" Element namespace app = "http://www.w3.org/2007/app" pubControl = element app:control { atomCommonAttributes, pubDraft? & extensionElement } pubDraft = element app:draft { "yes" | "no" } The "app:control" element MAY appear as a child of an atom:entry that is being created or updated via the Atom Publishing Protocol. The app:control element MUST appear only once in an Entry. The app: control element is considered foreign markup as defined in [Section 6 of [RFC4287]](https://datatracker.ietf.org/doc/html/rfc4287#section-6). The app:control element and its child elements MAY be included in Atom Feed or Entry Documents. The app:control element can contain an "app:draft" element as defined below, and it can contain extension elements as defined in [Section 6 of [RFC4287]](https://datatracker.ietf.org/doc/html/rfc4287#section-6). #### 13.1.1. The "app:draft" Element The inclusion of the "app:draft" element represents a request by the client to control the visibility of a Member Resource. The app:draft element MAY be ignored by the server. The number of app:draft elements in app:control MUST be zero or one. The content of an app:draft element MUST be one of "yes" or "no". If the element contains "no", this indicates a client request that the Member Resource be made publicly visible. If the app:draft element is not present, then servers that support the extension MUST behave as though an app:draft element containing "no" was sent. 14. Securing the Atom Publishing Protocol ----------------------------------------- The Atom Publishing Protocol is based on HTTP. Authentication requirements for HTTP are covered in [Section 11 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-11). The use of authentication mechanisms to prevent POSTing or editing by unknown or unauthorized clients is RECOMMENDED but not required. When authentication is not used, clients and servers are vulnerable to trivial spoofing, denial-of-service, and defacement attacks. However, in some contexts, this is an acceptable risk. The type of authentication deployed is a local decision made by the server operator. Clients are likely to face authentication schemes that vary across server deployments. At a minimum, client and server implementations MUST be capable of being configured to use HTTP Basic Authentication [[RFC2617](https://datatracker.ietf.org/doc/html/rfc2617)] in conjunction with a connection made with TLS 1.0 [[RFC2246](https://datatracker.ietf.org/doc/html/rfc2246)] or a subsequent standards-track version of TLS (such as [[RFC4346](https://datatracker.ietf.org/doc/html/rfc4346)]), supporting the conventions for using HTTP over TLS described in [[RFC2818](https://datatracker.ietf.org/doc/html/rfc2818)]. The choice of authentication mechanism will impact interoperability. The minimum level of security referenced above (Basic Authentication with TLS) is considered good practice for Internet applications at the time of publication of this specification and sufficient for establishing a baseline for interoperability. Implementers are encouraged to investigate and use alternative mechanisms regarded as equivalently good or better at the time of deployment. It is RECOMMENDED that clients be implemented in such a way that new authentication schemes can be deployed. Because this protocol uses HTTP response status codes as the primary means of reporting the result of a request, servers are advised to respond to unauthorized or unauthenticated requests using an appropriate 4xx HTTP response code (e.g., 401 "Unauthorized" or 403 "Forbidden") in accordance with [[RFC2617](https://datatracker.ietf.org/doc/html/rfc2617)]. 15. Security Considerations --------------------------- The Atom Publishing Protocol is based on HTTP and thus subject to the security considerations found in [Section 15 of [RFC2616]](https://datatracker.ietf.org/doc/html/rfc2616#section-15). The threats listed in this section apply to many protocols that run under HTTP. The Atompub Working Group decided that the protection afforded by running authenticated HTTP under TLS (as described in [Section 14](#section-14)) was sufficient to mitigate many of the problems presented by the attacks listed in this section. ### 15.1. Denial of Service Atom Publishing Protocol server implementations need to take adequate precautions to ensure malicious clients cannot consume excessive server resources (CPU, memory, disk, etc.). ### 15.2. Replay Attacks Atom Publishing Protocol server implementations are susceptible to replay attacks. Specifically, this specification does not define a means of detecting duplicate requests. Accidentally sent duplicate requests are indistinguishable from intentional and malicious replay attacks. ### 15.3. Spoofing Attacks Atom Publishing Protocol implementations are susceptible to a variety of spoofing attacks. Malicious clients might send Atom Entries containing inaccurate information anywhere in the document. ### 15.4. Linked Resources Atom Feed and Entry Documents can contain XML External Entities as defined in Section 4.2.2 of [[REC-xml](#ref-REC-xml)]. Atom implementations are not required to load external entities. External entities are subject to the same security concerns as any network operation and can alter the semantics of an Atom document. The same issues exist for Resources linked to by Atom elements such as atom:link and atom:content. ### 15.5. Digital Signatures and Encryption Atom Entry and Feed Documents can contain XML Digital Signatures [[REC-xmldsig-core](#ref-REC-xmldsig-core)] and can be encrypted using XML Encryption [[REC-xmlenc-core](#ref-REC-xmlenc-core)] as specified in [Section 5 of [RFC4287]](https://datatracker.ietf.org/doc/html/rfc4287#section-5). Handling of signatures and encrypted elements in Atom documents is discussed in Sections [5](#section-5) and [6.3](#section-6.3) of [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)]. Neither servers nor clients are under any obligation to support encryption and digital signature of Entries or Feeds, although it is certainly possible that in some installations, clients or servers might require signing or encrypting of the documents exchanged in the Atom Protocol. Because servers are allowed (and in some cases, expected) to modify the contents of an Entry Document before publishing it, signatures within an entry are only likely to be useful to the server to which the entry is being sent. Clients cannot assume that the signature will be valid when viewed by a third party, or even that the server will publish the client's signature. A server is allowed to strip client-applied signatures, to strip client-applied signatures and then re-sign with its own public key, and to oversign an entry with its own public key. The meaning to a third party of a signature applied by a server is the same as a signature from anyone, as described in [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)]. It is RECOMMENDED that a server that is aware that it has changed any part of an Entry Document that was signed by the client should strip that signature before publishing the entry in order to prevent third parties from trying to interpret a signature that cannot be validated. ### 15.6. URIs and IRIs Atom Publishing Protocol implementations handle URIs and IRIs. See [Section 7 of [RFC3986]](https://datatracker.ietf.org/doc/html/rfc3986#section-7) and [Section 8 of [RFC3987]](https://datatracker.ietf.org/doc/html/rfc3987#section-8) for security considerations related to their handling and use. The Atom Publishing Protocol leaves the server in control of minting URIs. The use of any client-supplied data for creating new URIs is subject to the same concerns as described in the next section. ### 15.7. Code Injection and Cross Site Scripting Atom Feed and Entry Documents can contain a broad range of content types including code that might be executable in some contexts. Malicious clients could attempt to attack servers or other clients by injecting code into a Collection Document's Entry or Media Resources. Server implementations are strongly encouraged to verify that client- supplied content is safe prior to accepting, processing, or publishing it. In the case of HTML, experience indicates that verification based on a white list of acceptable content is more effective than a black list of forbidden content. Additional information about XHTML and HTML content safety can be found in [Section 8.1 of [RFC4287]](https://datatracker.ietf.org/doc/html/rfc4287#section-8.1). 16. IANA Considerations ----------------------- This specification uses two new media types that conform to the registry mechanism described in [[RFC4288](https://datatracker.ietf.org/doc/html/rfc4288)], a new message header that conforms to the registry mechanism described in [[RFC3864](https://datatracker.ietf.org/doc/html/rfc3864)], and two new link relations that conform to the registry mechanism described in [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)]. ### 16.1. Content-Type Registration for 'application/atomcat+xml' An Atom Publishing Protocol Category Document, when serialized as XML 1.0, can be identified with the following media type: MIME media type name: application MIME subtype name: atomcat+xml Required parameters: None. Optional parameters: "charset": This parameter has identical semantics to the charset parameter of the "application/xml" media type as specified in [[RFC3023](https://datatracker.ietf.org/doc/html/rfc3023)]. Encoding considerations: Identical to those of "application/xml" as described in [[RFC3023], Section 3.2](https://datatracker.ietf.org/doc/html/rfc3023#section-3.2). Security considerations: As defined in [RFC 5023](https://datatracker.ietf.org/doc/html/rfc5023). In addition, as this media type uses the "+xml" convention, it shares the same security considerations as described in [[RFC3023], Section 10](https://datatracker.ietf.org/doc/html/rfc3023#section-10). Interoperability considerations: There are no known interoperability issues. Published specification: [RFC 5023](https://datatracker.ietf.org/doc/html/rfc5023). Applications that use this media type: No known applications currently use this media type. Additional information: Magic number(s): As specified for "application/xml" in [[RFC3023], Section 3.2](https://datatracker.ietf.org/doc/html/rfc3023#section-3.2). File extension: .atomcat Fragment identifiers: As specified for "application/xml" in [[RFC3023], Section 5](https://datatracker.ietf.org/doc/html/rfc3023#section-5). Base URI: As specified in [[RFC3023], Section 6](https://datatracker.ietf.org/doc/html/rfc3023#section-6). Macintosh file type code: TEXT Person & email address to contact for further information: Joe Gregorio <[email protected]> Intended usage: COMMON Author/Change controller: IETF ([email protected]) Internet Engineering Task Force ### 16.2. Content-Type Registration for 'application/atomsvc+xml' An Atom Publishing Protocol Service Document, when serialized as XML 1.0, can be identified with the following media type: MIME media type name: application MIME subtype name: atomsvc+xml Required parameters: None. Optional parameters: "charset": This parameter has identical semantics to the charset parameter of the "application/xml" media type as specified in [[RFC3023](https://datatracker.ietf.org/doc/html/rfc3023)]. Encoding considerations: Identical to those of "application/xml" as described in [[RFC3023], Section 3.2](https://datatracker.ietf.org/doc/html/rfc3023#section-3.2). Security considerations: As defined in [RFC 5023](https://datatracker.ietf.org/doc/html/rfc5023). In addition, as this media type uses the "+xml" convention, it shares the same security considerations as described in [[RFC3023], Section 10](https://datatracker.ietf.org/doc/html/rfc3023#section-10). Interoperability considerations: There are no known interoperability issues. Published specification: [RFC 5023](https://datatracker.ietf.org/doc/html/rfc5023). Applications that use this media type: No known applications currently use this media type. Additional information: Magic number(s): As specified for "application/xml" in [[RFC3023], Section 3.2](https://datatracker.ietf.org/doc/html/rfc3023#section-3.2). File extension: .atomsvc Fragment identifiers: As specified for "application/xml" in [[RFC3023], Section 5](https://datatracker.ietf.org/doc/html/rfc3023#section-5). Base URI: As specified in [[RFC3023], Section 6](https://datatracker.ietf.org/doc/html/rfc3023#section-6). Macintosh file type code: TEXT Person and email address to contact for further information: Joe Gregorio <[email protected]> Intended usage: COMMON Author/Change controller: IETF ([email protected]) Internet Engineering Task Force ### 16.3. Header Field Registration for 'SLUG' Header field name: SLUG Applicable protocol: http [[RFC2616](https://datatracker.ietf.org/doc/html/rfc2616)] Status: standard. Author/Change controller: IETF ([email protected]) Internet Engineering Task Force Specification document(s): [RFC 5023](https://datatracker.ietf.org/doc/html/rfc5023). Related information: None. ### 16.4. The Link Relation Registration "edit" Attribute Value: edit Description: An IRI of an editable Member Entry. When appearing within an atom:entry, the href IRI can be used to retrieve, update, and delete the Resource represented by that Entry. Expected display characteristics: Undefined; this relation can be used for background processing or to provide extended functionality without displaying its value. Security considerations: Automated agents should take care when this relation crosses administrative domains (e.g., the URI has a different authority than the current document). ### 16.5. The Link Relation Registration "edit-media" Attribute Value: edit-media Description: An IRI of an editable Media Resource. When appearing within an atom:entry, the href IRI can be used to retrieve, update, and delete the Media Resource associated with that Entry. Expected display characteristics: Undefined; this relation can be used for background processing or to provide extended functionality without displaying its value. Security considerations: Automated agents should take care when this relation crosses administrative domains (e.g., the URI has a different authority than the current document). ### 16.6. The Atom Format Media Type Parameter IANA has added a reference to this specification in the 'application/atom+xml' media type registration. 17. References -------------- ### 17.1. Normative References [REC-xml] Yergeau, F., Paoli, J., Bray, T., Sperberg-McQueen, C., and E. Maler, "Extensible Markup Language (XML) 1.0 (Fourth Edition)", World Wide Web Consortium Recommendation REC-xml-20060816, August 2006, <[http://www.w3.org/TR/2006/REC-xml-20060816](https://www.w3.org/TR/2006/REC-xml-20060816)>. [REC-xml-infoset] Cowan, J. and R. Tobin, "XML Information Set (Second Edition)", World Wide Web Consortium Recommendation REC- xml-infoset-20040204, February 2004, <[http://www.w3.org/TR/2004/REC-xml-infoset-20040204](https://www.w3.org/TR/2004/REC-xml-infoset-20040204)>. [REC-xml-names] Hollander, D., Bray, T., Tobin, R., and A. Layman, "Namespaces in XML 1.0 (Second Edition)", World Wide Web Consortium Recommendation REC-xml-names-20060816, August 2006, <[http://www.w3.org/TR/2006/REC-xml-names-20060816](https://www.w3.org/TR/2006/REC-xml-names-20060816)>. [REC-xmlbase] Marsh, J., "XML Base", W3C REC W3C.REC-xmlbase-20010627, June 2001, <[http://www.w3.org/TR/2001/REC-xmlbase-20010627](https://www.w3.org/TR/2001/REC-xmlbase-20010627)>. [REC-xmldsig-core] Solo, D., Reagle, J., and D. Eastlake, "XML-Signature Syntax and Processing", World Wide Web Consortium Recommendation REC-xmldsig-core-20020212, February 2002, <[http://www.w3.org/TR/2002/REC-xmldsig-core-20020212](https://www.w3.org/TR/2002/REC-xmldsig-core-20020212)>. [REC-xmlenc-core] Eastlake, D. and J. Reagle, "XML Encryption Syntax and Processing", World Wide Web Consortium Recommendation REC- xmlenc-core-20021210, December 2002, <[http://www.w3.org/TR/2002/REC-xmlenc-core-20021210](https://www.w3.org/TR/2002/REC-xmlenc-core-20021210)>. [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", [BCP 14](https://datatracker.ietf.org/doc/html/bcp14), [RFC 2119](https://datatracker.ietf.org/doc/html/rfc2119), March 1997. [RFC2246] Dierks, T. and C. Allen, "The TLS Protocol Version 1.0", [RFC 2246](https://datatracker.ietf.org/doc/html/rfc2246), January 1999. [RFC2616] Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, "Hypertext Transfer Protocol -- HTTP/1.1", [RFC 2616](https://datatracker.ietf.org/doc/html/rfc2616), June 1999. [RFC2617] Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, "HTTP Authentication: Basic and Digest Access Authentication", [RFC 2617](https://datatracker.ietf.org/doc/html/rfc2617), June 1999. [RFC2818] Rescorla, E., "HTTP Over TLS", [RFC 2818](https://datatracker.ietf.org/doc/html/rfc2818), May 2000. [RFC3023] Murata, M., St. Laurent, S., and D. Kohn, "XML Media Types", [RFC 3023](https://datatracker.ietf.org/doc/html/rfc3023), January 2001. [RFC3629] Yergeau, F., "UTF-8, a transformation format of ISO 10646", STD 63, [RFC 3629](https://datatracker.ietf.org/doc/html/rfc3629), November 2003. [RFC3864] Klyne, G., Nottingham, M., and J. Mogul, "Registration Procedures for Message Header Fields", [BCP 90](https://datatracker.ietf.org/doc/html/bcp90), [RFC 3864](https://datatracker.ietf.org/doc/html/rfc3864), September 2004. [RFC3986] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform Resource Identifier (URI): Generic Syntax", STD 66, [RFC](https://datatracker.ietf.org/doc/html/rfc3986) [3986](https://datatracker.ietf.org/doc/html/rfc3986), January 2005. [RFC3987] Duerst, M. and M. Suignard, "Internationalized Resource Identifiers (IRIs)", [RFC 3987](https://datatracker.ietf.org/doc/html/rfc3987), January 2005. [RFC4287] Nottingham, M. and R. Sayre, "The Atom Syndication Format", [RFC 4287](https://datatracker.ietf.org/doc/html/rfc4287), December 2005. [RFC4288] Freed, N. and J. Klensin, "Media Type Specifications and Registration Procedures", [BCP 13](https://datatracker.ietf.org/doc/html/bcp13), [RFC 4288](https://datatracker.ietf.org/doc/html/rfc4288), December 2005. [RFC4346] Dierks, T. and E. Rescorla, "The Transport Layer Security (TLS) Protocol Version 1.1", [RFC 4346](https://datatracker.ietf.org/doc/html/rfc4346), April 2006. ### 17.2. Informative References [NOTE-detect-lost-update] Nielsen, H. and D. LaLiberte, "Editing the Web: Detecting the Lost Update Problem Using Unreserved Checkout", World Wide Web Consortium NOTE NOTE-detect-lost-update, May 1999, <[http://www.w3.org/1999/04/Editing/](https://www.w3.org/1999/04/Editing/)>. [REC-webarch] Walsh, N. and I. Jacobs, "Architecture of the World Wide Web, Volume One", W3C REC REC-webarch-20041215, December 2004, <[http://www.w3.org/TR/2004/REC-webarch-20041215](https://www.w3.org/TR/2004/REC-webarch-20041215)>. [RNC] Clark, J., "RELAX NG Compact Syntax", December 2001, <[http://www.oasis-open.org/committees/relax-ng/](http://www.oasis-open.org/committees/relax-ng/compact-20021121.html) [compact-20021121.html](http://www.oasis-open.org/committees/relax-ng/compact-20021121.html)>. Appendix A. Contributors ------------------------ The content and concepts within are a product of the Atom community and the Atompub Working Group. Appendix B. RELAX NG Compact Schema ----------------------------------- This appendix is informative. The Relax NG schema explicitly excludes elements in the Atom Protocol namespace that are not defined in this revision of the specification. Requirements for Atom Protocol processors encountering such markup are given in Sections [6.2](#section-6.2) and [6.3](#section-6.3) of [[RFC4287](https://datatracker.ietf.org/doc/html/rfc4287)]. The Schema for Service Documents: # -\*- rnc -\*- # RELAX NG Compact Syntax Grammar for the Atom Protocol namespace app = "http://www.w3.org/2007/app" namespace atom = "http://www.w3.org/2005/Atom" namespace xsd = "http://www.w3.org/2001/XMLSchema" namespace xhtml = "http://www.w3.org/1999/xhtml" namespace local = "" start = appService # common:attrs atomURI = text appCommonAttributes = attribute xml:base { atomURI }?, attribute xml:lang { atomLanguageTag }?, attribute xml:space {"default"|"preserved"}?, undefinedAttribute\* atomCommonAttributes = appCommonAttributes undefinedAttribute = attribute \* - (xml:base | xml:space | xml:lang | local:\*) { text } atomLanguageTag = xsd:string { pattern = "([A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})\*)?" } atomDateConstruct = appCommonAttributes, xsd:dateTime # app:service appService = element app:service { appCommonAttributes, ( appWorkspace+ & extensionElement\* ) } # app:workspace appWorkspace = element app:workspace { appCommonAttributes, ( atomTitle & appCollection\* & extensionSansTitleElement\* ) } atomTitle = element atom:title { atomTextConstruct } # app:collection appCollection = element app:collection { appCommonAttributes, attribute href { atomURI }, ( atomTitle & appAccept\* & appCategories\* & extensionSansTitleElement\* ) } # app:categories atomCategory = element atom:category { atomCommonAttributes, attribute term { text }, attribute scheme { atomURI }?, attribute label { text }?, undefinedContent } appInlineCategories = element app:categories { attribute fixed { "yes" | "no" }?, attribute scheme { atomURI }?, (atomCategory\*, undefinedContent) } appOutOfLineCategories = element app:categories { attribute href { atomURI }, undefinedContent } appCategories = appInlineCategories | appOutOfLineCategories # app:accept appAccept = element app:accept { appCommonAttributes, ( text? ) } # Simple Extension simpleSansTitleExtensionElement = element \* - (app:\*|atom:title) { text } simpleExtensionElement = element \* - (app:\*) { text } # Structured Extension structuredSansTitleExtensionElement = element \* - (app:\*|atom:title) { (attribute \* { text }+, (text|anyElement)\*) | (attribute \* { text }\*, (text?, anyElement+, (text|anyElement)\*)) } structuredExtensionElement = element \* - (app:\*) { (attribute \* { text }+, (text|anyElement)\*) | (attribute \* { text }\*, (text?, anyElement+, (text|anyElement)\*)) } # Other Extensibility extensionSansTitleElement = simpleSansTitleExtensionElement|structuredSansTitleExtensionElement extensionElement = simpleExtensionElement | structuredExtensionElement undefinedContent = (text|anyForeignElement)\* # Extensions anyElement = element \* { (attribute \* { text } | text | anyElement)\* } anyForeignElement = element \* - app:\* { (attribute \* { text } | text | anyElement)\* } atomPlainTextConstruct = atomCommonAttributes, attribute type { "text" | "html" }?, text atomXHTMLTextConstruct = atomCommonAttributes, attribute type { "xhtml" }, xhtmlDiv atomTextConstruct = atomPlainTextConstruct | atomXHTMLTextConstruct anyXHTML = element xhtml:\* { (attribute \* { text } | text | anyXHTML)\* } xhtmlDiv = element xhtml:div { (attribute \* { text } | text | anyXHTML)\* } # EOF The Schema for Category Documents: # -\*- rnc -\*- # RELAX NG Compact Syntax Grammar for the Atom Protocol namespace app = "http://www.w3.org/2007/app" namespace atom = "http://www.w3.org/2005/Atom" namespace xsd = "http://www.w3.org/2001/XMLSchema" namespace local = "" start = appCategories atomCommonAttributes = attribute xml:base { atomURI }?, attribute xml:lang { atomLanguageTag }?, undefinedAttribute\* undefinedAttribute = attribute \* - (xml:base | xml:lang | local:\*) { text } atomURI = text atomLanguageTag = xsd:string { pattern = "([A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})\*)?" } atomCategory = element atom:category { atomCommonAttributes, attribute term { text }, attribute scheme { atomURI }?, attribute label { text }?, undefinedContent } appInlineCategories = element app:categories { attribute fixed { "yes" | "no" }?, attribute scheme { atomURI }?, (atomCategory\*, undefinedContent) } appOutOfLineCategories = element app:categories { attribute href { atomURI }, (empty) } appCategories = appInlineCategories | appOutOfLineCategories # Extensibility undefinedContent = (text|anyForeignElement)\* anyElement = element \* { (attribute \* { text } | text | anyElement)\* } anyForeignElement = element \* - atom:\* { (attribute \* { text } | text | anyElement)\* } # EOF Authors' Addresses Joe Gregorio (editor) Google EMail: [email protected] URI: <http://bitworking.org/> Bill de hOra (editor) NewBay Software EMail: [email protected] URI: <http://dehora.net/> Full Copyright Statement Copyright (C) The IETF Trust (2007). This document is subject to the rights, licenses and restrictions contained in [BCP 78](https://datatracker.ietf.org/doc/html/bcp78), and except as set forth therein, the authors retain all their rights. This document and the information contained herein are provided on an "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY, THE IETF TRUST AND THE INTERNET ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Intellectual Property The IETF takes no position regarding the validity or scope of any Intellectual Property Rights or other rights that might be claimed to pertain to the implementation or use of the technology described in this document or the extent to which any license under such rights might or might not be available; nor does it represent that it has made any independent effort to identify any such rights. Information on the procedures with respect to rights in RFC documents can be found in [BCP 78](https://datatracker.ietf.org/doc/html/bcp78) and [BCP 79](https://datatracker.ietf.org/doc/html/bcp79). Copies of IPR disclosures made to the IETF Secretariat and any assurances of licenses to be made available, or the result of an attempt made to obtain a general license or permission for the use of such proprietary rights by implementers or users of this specification can be obtained from the IETF on-line IPR repository at [http://www.ietf.org/ipr](https://www.ietf.org/ipr). The IETF invites any interested party to bring to its attention any copyrights, patents or patent applications, or other proprietary rights that may cover technology that may be required to implement this standard. Please address the information to the IETF at [email protected]. Gregorio & de hOra Standards Track [Page 53]
programming_docs
http CORS CORS ==== Cross-Origin Resource Sharing (CORS) ==================================== **Cross-Origin Resource Sharing** ([CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS)) is an [HTTP](https://developer.mozilla.org/en-US/docs/Glossary/HTTP)-header based mechanism that allows a server to indicate any [origins](https://developer.mozilla.org/en-US/docs/Glossary/Origin) (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which browsers make a "preflight" request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request. An example of a cross-origin request: the front-end JavaScript code served from `https://domain-a.com` uses [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) to make a request for `https://domain-b.com/data.json`. For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, `XMLHttpRequest` and the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) follow the [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers. The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers. Modern browsers use CORS in APIs such as `XMLHttpRequest` or [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to mitigate the risks of cross-origin HTTP requests. What requests use CORS? ----------------------- This [cross-origin sharing standard](https://fetch.spec.whatwg.org/#http-cors-protocol) can enable cross-origin HTTP requests for: * Invocations of the [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) or [Fetch APIs](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API), as discussed above. * Web Fonts (for cross-domain font usage in `@font-face` within CSS), [so that servers can deploy TrueType fonts that can only be loaded cross-origin and used by web sites that are permitted to do so.](https://www.w3.org/TR/css-fonts-3/#font-fetching-requirements) * [WebGL textures](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL). * Images/video frames drawn to a canvas using [`drawImage()`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage). * [CSS Shapes from images.](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Shapes/Shapes_From_Images) This is a general article about Cross-Origin Resource Sharing and includes a discussion of the necessary HTTP headers. Functional overview ------------------- The Cross-Origin Resource Sharing standard works by adding new [HTTP headers](headers) that let servers describe which origins are permitted to read that information from a web browser. Additionally, for HTTP request methods that can cause side-effects on server data (in particular, HTTP methods other than [`GET`](methods/get), or [`POST`](methods/post) with certain [MIME types](basics_of_http/mime_types)), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with the HTTP [`OPTIONS`](methods/options) request method, and then, upon "approval" from the server, sending the actual request. Servers can also inform clients whether "credentials" (such as [Cookies](cookies) and [HTTP Authentication](authentication)) should be sent with requests. CORS failures result in errors but for security reasons, specifics about the error *are not available to JavaScript*. All the code knows is that an error occurred. The only way to determine what specifically went wrong is to look at the browser's console for details. Subsequent sections discuss scenarios, as well as provide a breakdown of the HTTP headers used. Examples of access control scenarios ------------------------------------ We present three scenarios that demonstrate how Cross-Origin Resource Sharing works. All these examples use [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), which can make cross-origin requests in any supporting browser. ### Simple requests Some requests don't trigger a [CORS preflight](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request). Those are called *simple requests* from the obsolete [CORS spec](https://www.w3.org/TR/2014/REC-cors-20140116/#terminology), though the [Fetch spec](https://fetch.spec.whatwg.org/) (which now defines CORS) doesn't use that term. The motivation is that the [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) element from HTML 4.0 (which predates cross-site [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) and [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch)) can submit simple requests to any origin, so anyone writing a server must already be protecting against [cross-site request forgery](https://developer.mozilla.org/en-US/docs/Glossary/CSRF) (CSRF). Under this assumption, the server doesn't have to opt-in (by responding to a preflight request) to receive any request that looks like a form submission, since the threat of CSRF is no worse than that of form submission. However, the server still must opt-in using [`Access-Control-Allow-Origin`](headers/access-control-allow-origin) to *share* the response with the script. A *simple request* is one that **meets all the following conditions**: * One of the allowed methods: + [`GET`](methods/get) + [`HEAD`](methods/head) + [`POST`](methods/post) * Apart from the headers automatically set by the user agent (for example, [`Connection`](headers/connection), [`User-Agent`](headers/user-agent), or [the other headers defined in the Fetch spec as a *forbidden header name*](https://fetch.spec.whatwg.org/#forbidden-header-name)), the only headers which are allowed to be manually set are [those which the Fetch spec defines as a CORS-safelisted request-header](https://fetch.spec.whatwg.org/#cors-safelisted-request-header), which are: + [`Accept`](headers/accept) + [`Accept-Language`](headers/accept-language) + [`Content-Language`](headers/content-language) + [`Content-Type`](headers/content-type) (please note the additional requirements below) + [`Range`](headers/range) (only with a [simple range header value](https://fetch.spec.whatwg.org/#simple-range-header-value); e.g., `bytes=256-` or `bytes=127-255`) **Note:** Firefox has not implemented `Range` as a safelisted request-header yet. See [bug 1733981](https://bugzilla.mozilla.org/show_bug.cgi?id=1733981). * The only type/subtype combinations allowed for the [media type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) specified in the [`Content-Type`](headers/content-type) header are: + `application/x-www-form-urlencoded` + `multipart/form-data` + `text/plain` * If the request is made using an [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) object, no event listeners are registered on the object returned by the [`XMLHttpRequest.upload`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/upload) property used in the request; that is, given an [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) instance `xhr`, no code has called `xhr.upload.addEventListener()` to add an event listener to monitor the upload. * No [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) object is used in the request. **Note:** WebKit Nightly and Safari Technology Preview place additional restrictions on the values allowed in the [`Accept`](headers/accept), [`Accept-Language`](headers/accept-language), and [`Content-Language`](headers/content-language) headers. If any of those headers have "nonstandard" values, WebKit/Safari does not consider the request to be a "simple request". What values WebKit/Safari consider "nonstandard" is not documented, except in the following WebKit bugs: * [Require preflight for non-standard CORS-safelisted request headers Accept, Accept-Language, and Content-Language](https://bugs.webkit.org/show_bug.cgi?id=165178) * [Allow commas in Accept, Accept-Language, and Content-Language request headers for simple CORS](https://bugs.webkit.org/show_bug.cgi?id=165566) * [Switch to a blacklist model for restricted Accept headers in simple CORS requests](https://bugs.webkit.org/show_bug.cgi?id=166363) No other browsers implement these extra restrictions because they're not part of the spec. For example, suppose web content at `https://foo.example` wishes to invoke content on domain `https://bar.other`. Code of this sort might be used in JavaScript deployed on `foo.example`: ``` const xhr = new XMLHttpRequest(); const url = "https://bar.other/resources/public-data/"; xhr.open("GET", url); xhr.onreadystatechange = someHandler; xhr.send(); ``` This operation performs a simple exchange between the client and the server, using CORS headers to handle the privileges: Let's look at what the browser will send to the server in this case: ``` GET /resources/public-data/ HTTP/1.1 Host: bar.other User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,\*/\*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Connection: keep-alive Origin: https://foo.example ``` The request header of note is [`Origin`](headers/origin), which shows that the invocation is coming from `https://foo.example`. Now let's see how the server responds: ``` HTTP/1.1 200 OK Date: Mon, 01 Dec 2008 00:23:53 GMT Server: Apache/2 Access-Control-Allow-Origin: \* Keep-Alive: timeout=2, max=100 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: application/xml […XML Data…] ``` In response, the server returns a [`Access-Control-Allow-Origin`](headers/access-control-allow-origin) header with `Access-Control-Allow-Origin: *`, which means that the resource can be accessed by **any** origin. ``` Access-Control-Allow-Origin: \* ``` This pattern of the [`Origin`](headers/origin) and [`Access-Control-Allow-Origin`](headers/access-control-allow-origin) headers is the simplest use of the access control protocol. If the resource owners at `https://bar.other` wished to restrict access to the resource to requests *only* from `https://foo.example` (i.e., no domain other than `https://foo.example` can access the resource in a cross-origin manner), they would send: ``` Access-Control-Allow-Origin: https://foo.example ``` **Note:** When responding to a [credentialed requests](#requests_with_credentials) request, the server **must** specify an origin in the value of the `Access-Control-Allow-Origin` header, instead of specifying the "`*`" wildcard. ### Preflighted requests Unlike [*simple requests*](#simple_requests), for "preflighted" requests the browser first sends an HTTP request using the [`OPTIONS`](methods/options) method to the resource on the other origin, in order to determine if the actual request is safe to send. Such cross-origin requests are preflighted since they may have implications for user data. The following is an example of a request that will be preflighted: ``` const xhr = new XMLHttpRequest(); xhr.open("POST", "https://bar.other/doc"); xhr.setRequestHeader("X-PINGOTHER", "pingpong"); xhr.setRequestHeader("Content-Type", "text/xml"); xhr.onreadystatechange = handler; xhr.send("<person><name>Arun</name></person>"); ``` The example above creates an XML body to send with the `POST` request. Also, a non-standard HTTP `X-PINGOTHER` request header is set. Such headers are not part of HTTP/1.1, but are generally useful to web applications. Since the request uses a `Content-Type` of `text/xml`, and since a custom header is set, this request is preflighted. **Note:** As described below, the actual `POST` request does not include the `Access-Control-Request-*` headers; they are needed only for the `OPTIONS` request. Let's look at the full exchange between client and server. The first exchange is the *preflight request/response*: ``` OPTIONS /doc HTTP/1.1 Host: bar.other User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,\*/\*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Connection: keep-alive Origin: https://foo.example Access-Control-Request-Method: POST Access-Control-Request-Headers: X-PINGOTHER, Content-Type HTTP/1.1 204 No Content Date: Mon, 01 Dec 2008 01:15:39 GMT Server: Apache/2 Access-Control-Allow-Origin: https://foo.example Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Allow-Headers: X-PINGOTHER, Content-Type Access-Control-Max-Age: 86400 Vary: Accept-Encoding, Origin Keep-Alive: timeout=2, max=100 Connection: Keep-Alive ``` Lines 1 - 10 above represent the preflight request with the [`OPTIONS`](methods/options) method. The browser determines that it needs to send this based on the request parameters that the JavaScript code snippet above was using, so that the server can respond whether it is acceptable to send the request with the actual request parameters. OPTIONS is an HTTP/1.1 method that is used to determine further information from servers, and is a [safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) method, meaning that it can't be used to change the resource. Note that along with the OPTIONS request, two other request headers are sent (lines 9 and 10 respectively): ``` Access-Control-Request-Method: POST Access-Control-Request-Headers: X-PINGOTHER, Content-Type ``` The [`Access-Control-Request-Method`](headers/access-control-request-method) header notifies the server as part of a preflight request that when the actual request is sent, it will do so with a `POST` request method. The [`Access-Control-Request-Headers`](headers/access-control-request-headers) header notifies the server that when the actual request is sent, it will do so with `X-PINGOTHER` and `Content-Type` custom headers. Now the server has an opportunity to determine whether it can accept a request under these conditions. Lines 12 - 21 above are the response that the server returns, which indicate that the request method (`POST`) and request headers (`X-PINGOTHER`) are acceptable. Let's have a closer look at lines 15-18: ``` Access-Control-Allow-Origin: https://foo.example Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Allow-Headers: X-PINGOTHER, Content-Type Access-Control-Max-Age: 86400 ``` The server responds with `Access-Control-Allow-Origin: https://foo.example`, restricting access to the requesting origin domain only. It also responds with `Access-Control-Allow-Methods`, which says that `POST` and `GET` are valid methods to query the resource in question (this header is similar to the [`Allow`](headers/allow) response header, but used strictly within the context of access control). The server also sends `Access-Control-Allow-Headers` with a value of "`X-PINGOTHER, Content-Type`", confirming that these are permitted headers to be used with the actual request. Like `Access-Control-Allow-Methods`, `Access-Control-Allow-Headers` is a comma-separated list of acceptable headers. Finally, [`Access-Control-Max-Age`](headers/access-control-max-age) gives the value in seconds for how long the response to the preflight request can be cached without sending another preflight request. The default value is 5 seconds. In the present case, the max age is 86400 seconds (= 24 hours). Note that each browser has a [maximum internal value](headers/access-control-max-age) that takes precedence when the `Access-Control-Max-Age` exceeds it. Once the preflight request is complete, the real request is sent: ``` POST /doc HTTP/1.1 Host: bar.other User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,\*/\*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Connection: keep-alive X-PINGOTHER: pingpong Content-Type: text/xml; charset=UTF-8 Referer: https://foo.example/examples/preflightInvocation.html Content-Length: 55 Origin: https://foo.example Pragma: no-cache Cache-Control: no-cache <person><name>Arun</name></person> HTTP/1.1 200 OK Date: Mon, 01 Dec 2008 01:15:40 GMT Server: Apache/2 Access-Control-Allow-Origin: https://foo.example Vary: Accept-Encoding, Origin Content-Encoding: gzip Content-Length: 235 Keep-Alive: timeout=2, max=99 Connection: Keep-Alive Content-Type: text/plain [Some XML payload] ``` #### Preflighted requests and redirects Not all browsers currently support following redirects after a preflighted request. If a redirect occurs after such a request, some browsers currently will report an error message such as the following: > The request was redirected to '<https://example.com/foo>', which is disallowed for cross-origin requests that require preflight. Request requires preflight, which is disallowed to follow cross-origin redirects. > > The CORS protocol originally required that behavior but [was subsequently changed to no longer require it](https://github.com/whatwg/fetch/commit/0d9a4db8bc02251cc9e391543bb3c1322fb882f2). However, not all browsers have implemented the change, and thus still exhibit the originally required behavior. Until browsers catch up with the spec, you may be able to work around this limitation by doing one or both of the following: * Change the server-side behavior to avoid the preflight and/or to avoid the redirect * Change the request such that it is a [simple request](#simple_requests) that doesn't cause a preflight If that's not possible, then another way is to: 1. Make a [simple request](#simple_requests) (using [`Response.url`](https://developer.mozilla.org/en-US/docs/Web/API/Response/url) for the Fetch API, or [`XMLHttpRequest.responseURL`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseURL)) to determine what URL the real preflighted request would end up at. 2. Make another request (the *real* request) using the URL you obtained from `Response.url` or `XMLHttpRequest.responseURL` in the first step. However, if the request is one that triggers a preflight due to the presence of the `Authorization` header in the request, you won't be able to work around the limitation using the steps above. And you won't be able to work around it at all unless you have control over the server the request is being made to. ### Requests with credentials **Note:** When making credentialed requests to a different domain, third-party cookie policies will still apply. The policy is always enforced regardless of any setup on the server and the client as described in this chapter. The most interesting capability exposed by both [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) or [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and CORS is the ability to make "credentialed" requests that are aware of [HTTP cookies](cookies) and HTTP Authentication information. By default, in cross-origin `XMLHttpRequest` or [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) invocations, browsers will **not** send credentials. A specific flag has to be set on the `XMLHttpRequest` object or the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) constructor when it is invoked. In this example, content originally loaded from `https://foo.example` makes a simple GET request to a resource on `https://bar.other` which sets Cookies. Content on foo.example might contain JavaScript like this: ``` const invocation = new XMLHttpRequest(); const url = "https://bar.other/resources/credentialed-content/"; function callOtherDomain() { if (invocation) { invocation.open("GET", url, true); invocation.withCredentials = true; invocation.onreadystatechange = handler; invocation.send(); } } ``` Line 7 shows the flag on [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) that has to be set in order to make the invocation with Cookies, namely the `withCredentials` boolean value. By default, the invocation is made without Cookies. Since this is a simple `GET` request, it is not preflighted but the browser will **reject** any response that does not have the [`Access-Control-Allow-Credentials`](headers/access-control-allow-credentials)`: true` header, and **not** make the response available to the invoking web content. Here is a sample exchange between client and server: ``` GET /resources/credentialed-content/ HTTP/1.1 Host: bar.other User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,\*/\*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Connection: keep-alive Referer: https://foo.example/examples/credential.html Origin: https://foo.example Cookie: pageAccess=2 HTTP/1.1 200 OK Date: Mon, 01 Dec 2008 01:34:52 GMT Server: Apache/2 Access-Control-Allow-Origin: https://foo.example Access-Control-Allow-Credentials: true Cache-Control: no-cache Pragma: no-cache Set-Cookie: pageAccess=3; expires=Wed, 31-Dec-2008 01:34:53 GMT Vary: Accept-Encoding, Origin Content-Encoding: gzip Content-Length: 106 Keep-Alive: timeout=2, max=100 Connection: Keep-Alive Content-Type: text/plain [text/plain payload] ``` Although line 10 contains the Cookie destined for the content on `https://bar.other`, if bar.other did not respond with an [`Access-Control-Allow-Credentials`](headers/access-control-allow-credentials)`: true` (line 16), the response would be ignored and not made available to the web content. #### Preflight requests and credentials CORS-preflight requests must never include credentials. The *response* to a preflight request must specify `Access-Control-Allow-Credentials: true` to indicate that the actual request can be made with credentials. **Note:** Some enterprise authentication services require that TLS client certificates be sent in preflight requests, in contravention of the [Fetch](https://fetch.spec.whatwg.org/#cors-protocol-and-credentials) specification. Firefox 87 allows this non-compliant behavior to be enabled by setting the preference: `network.cors_preflight.allow_client_cert` to `true` ([bug 1511151](https://bugzilla.mozilla.org/show_bug.cgi?id=1511151)). Chromium-based browsers currently always send TLS client certificates in CORS preflight requests ([Chrome bug 775438](https://bugs.chromium.org/p/chromium/issues/detail?id=775438)). #### Credentialed requests and wildcards When responding to a credentialed request: * The server **must not** specify the "`*`" wildcard for the `Access-Control-Allow-Origin` response-header value, but must instead specify an explicit origin; for example: `Access-Control-Allow-Origin: https://example.com` * The server **must not** specify the "`*`" wildcard for the `Access-Control-Allow-Headers` response-header value, but must instead specify an explicit list of header names; for example, `Access-Control-Allow-Headers: X-PINGOTHER, Content-Type` * The server **must not** specify the "`*`" wildcard for the `Access-Control-Allow-Methods` response-header value, but must instead specify an explicit list of method names; for example, `Access-Control-Allow-Methods: POST, GET` If a request includes a credential (most commonly a `Cookie` header) and the response includes an `Access-Control-Allow-Origin: *` header (that is, with the wildcard), the browser will block access to the response, and report a CORS error in the devtools console. But if a request does include a credential (like the `Cookie` header) and the response includes an actual origin rather than the wildcard (like, for example, `Access-Control-Allow-Origin: https://example.com`), then the browser will allow access to the response from the specified origin. Also note that any `Set-Cookie` response header in a response would not set a cookie if the `Access-Control-Allow-Origin` value in that response is the "`*`" wildcard rather an actual origin. #### Third-party cookies Note that cookies set in CORS responses are subject to normal third-party cookie policies. In the example above, the page is loaded from `foo.example` but the cookie on line 19 is sent by `bar.other`, and would thus not be saved if the user's browser is configured to reject all third-party cookies. Cookie in the request (line 10) may also be suppressed in normal third-party cookie policies. The enforced cookie policy may therefore nullify the capability described in this chapter, effectively preventing you from making credentialed requests whatsoever. Cookie policy around the [SameSite](headers/set-cookie/samesite) attribute would apply. The HTTP response headers ------------------------- This section lists the HTTP response headers that servers return for access control requests as defined by the Cross-Origin Resource Sharing specification. The previous section gives an overview of these in action. ### Access-Control-Allow-Origin A returned resource may have one [`Access-Control-Allow-Origin`](headers/access-control-allow-origin) header with the following syntax: ``` Access-Control-Allow-Origin: <origin> | \* ``` `Access-Control-Allow-Origin` specifies either a single origin which tells browsers to allow that origin to access the resource; or else — for requests **without** credentials — the "`*`" wildcard tells browsers to allow any origin to access the resource. For example, to allow code from the origin `https://mozilla.org` to access the resource, you can specify: ``` Access-Control-Allow-Origin: https://mozilla.org Vary: Origin ``` If the server specifies a single origin (that may dynamically change based on the requesting origin as part of an allowlist) rather than the "`*`" wildcard, then the server should also include `Origin` in the [`Vary`](headers/vary) response header to indicate to clients that server responses will differ based on the value of the [`Origin`](headers/origin) request header. ### Access-Control-Expose-Headers The [`Access-Control-Expose-Headers`](headers/access-control-expose-headers) header adds the specified headers to the allowlist that JavaScript (such as [`getResponseHeader()`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getResponseHeader)) in browsers is allowed to access. ``` Access-Control-Expose-Headers: <header-name>[, <header-name>]\* ``` For example, the following: ``` Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header ``` …would allow the `X-My-Custom-Header` and `X-Another-Custom-Header` headers to be exposed to the browser. ### Access-Control-Max-Age The [`Access-Control-Max-Age`](headers/access-control-max-age) header indicates how long the results of a preflight request can be cached. For an example of a preflight request, see the above examples. ``` Access-Control-Max-Age: <delta-seconds> ``` The `delta-seconds` parameter indicates the number of seconds the results can be cached. ### Access-Control-Allow-Credentials The [`Access-Control-Allow-Credentials`](headers/access-control-allow-credentials) header indicates whether or not the response to the request can be exposed when the `credentials` flag is true. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. Note that simple `GET` requests are not preflighted, and so if a request is made for a resource with credentials, if this header is not returned with the resource, the response is ignored by the browser and not returned to web content. ``` Access-Control-Allow-Credentials: true ``` [Credentialed requests](#requests_with_credentials) are discussed above. ### Access-Control-Allow-Methods The [`Access-Control-Allow-Methods`](headers/access-control-allow-methods) header specifies the method or methods allowed when accessing the resource. This is used in response to a preflight request. The conditions under which a request is preflighted are discussed above. ``` Access-Control-Allow-Methods: <method>[, <method>]\* ``` An example of a [preflight request](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request) is given above, including an example which sends this header to the browser. ### Access-Control-Allow-Headers The [`Access-Control-Allow-Headers`](headers/access-control-allow-headers) header is used in response to a [preflight request](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request) to indicate which HTTP headers can be used when making the actual request. This header is the server side response to the browser's [`Access-Control-Request-Headers`](headers/access-control-request-headers) header. ``` Access-Control-Allow-Headers: <header-name>[, <header-name>]\* ``` The HTTP request headers ------------------------ This section lists headers that clients may use when issuing HTTP requests in order to make use of the cross-origin sharing feature. Note that these headers are set for you when making invocations to servers. Developers using cross-origin [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) capability do not have to set any cross-origin sharing request headers programmatically. ### Origin The [`Origin`](headers/origin) header indicates the origin of the cross-origin access request or preflight request. ``` Origin: <origin> ``` The origin is a URL indicating the server from which the request is initiated. It does not include any path information, only the server name. **Note:** The `origin` value can be `null`. Note that in any access control request, the [`Origin`](headers/origin) header is **always** sent. ### Access-Control-Request-Method The [`Access-Control-Request-Method`](headers/access-control-request-method) is used when issuing a preflight request to let the server know what HTTP method will be used when the actual request is made. ``` Access-Control-Request-Method: <method> ``` Examples of this usage can be [found above.](#preflighted_requests) ### Access-Control-Request-Headers The [`Access-Control-Request-Headers`](headers/access-control-request-headers) header is used when issuing a preflight request to let the server know what HTTP headers will be used when the actual request is made (such as with [`setRequestHeader()`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader)). This browser-side header will be answered by the complementary server-side header of [`Access-Control-Allow-Headers`](headers/access-control-allow-headers). ``` Access-Control-Request-Headers: <field-name>[, <field-name>]\* ``` Examples of this usage can be [found above](#preflighted_requests). Specifications -------------- | Specification | | --- | | [Fetch Standard # http-access-control-allow-origin](https://fetch.spec.whatwg.org/#http-access-control-allow-origin) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `CORS` | 4 | 12 | 3.5 | 10 | 12 | 4 | 2 | Yes | 4 | 12 | 3.2 | Yes | See also -------- * [CORS errors](cors/errors) * [Enable CORS: I want to add CORS support to my server](https://enable-cors.org/server.html) * [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) * [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) * [Will it CORS?](https://httptoolkit.tech/will-it-cors/) - an interactive CORS explainer & generator * [How to run Chrome browser without CORS](https://alfilatov.com/posts/run-chrome-without-cors/) * [Using CORS with All (Modern) Browsers](https://www.telerik.com/blogs/using-cors-with-all-modern-browsers) * [Stack Overflow answer with "how to" info for dealing with common problems](https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe/43881141#43881141): + How to avoid the CORS preflight + How to use a CORS proxy to get around *"No Access-Control-Allow-Origin header"* + How to fix *"Access-Control-Allow-Origin header must not be the wildcard"*
programming_docs
http Connection management in HTTP 1.x Connection management in HTTP 1.x ================================= Connection management in HTTP/1.x ================================= Connection management is a key topic in HTTP: opening and maintaining connections largely impacts the performance of Web sites and Web applications. In HTTP/1.x, there are several models: *short-lived connections*, *persistent connections*, and *HTTP pipelining.* HTTP mostly relies on TCP for its transport protocol, providing a connection between the client and the server. In its infancy, HTTP used a single model to handle such connections. These connections were short-lived: a new one created each time a request needed sending, and closed once the answer had been received. This simple model held an innate limitation on performance: opening each TCP connection is a resource-consuming operation. Several messages must be exchanged between the client and the server. Network latency and bandwidth affect performance when a request needs sending. Modern Web pages require many requests (a dozen or more) to serve the amount of information needed, proving this earlier model inefficient. Two newer models were created in HTTP/1.1. The persistent-connection model keeps connections opened between successive requests, reducing the time needed to open new connections. The HTTP pipelining model goes one step further, by sending several successive requests without even waiting for an answer, reducing much of the latency in the network. **Note:** HTTP/2 adds additional models for connection management. It's important to note that connection management in HTTP applies to the connection between two consecutive nodes, which is [hop-by-hop](headers#hop-by-hop_headers) and not [end-to-end](headers#end-to-end_headers). The model used in connections between a client and its first proxy may differ from the model between a proxy and the destination server (or any intermediate proxies). The HTTP headers involved in defining the connection model, like [`Connection`](headers/connection) and [`Keep-Alive`](headers/keep-alive), are [hop-by-hop](headers#hop-by-hop_headers) headers with their values able to be changed by intermediary nodes. A related topic is the concept of HTTP connection upgrades, wherein an HTTP/1.1 connection is upgraded to a different protocol, such as TLS/1.0, WebSocket, or even HTTP/2 in cleartext. This [protocol upgrade mechanism](protocol_upgrade_mechanism) is documented in more detail elsewhere. Short-lived connections ----------------------- The original model of HTTP, and the default one in HTTP/1.0, is *short-lived connections*. Each HTTP request is completed on its own connection; this means a TCP handshake happens before each HTTP request, and these are serialized. The TCP handshake itself is time-consuming, but a TCP connection adapts to its load, becoming more efficient with more sustained (or warm) connections. Short-lived connections do not make use of this efficiency feature of TCP, and performance degrades from optimum by persisting to transmit over a new, cold connection. This model is the default model used in HTTP/1.0 (if there is no [`Connection`](headers/connection) header, or if its value is set to `close`). In HTTP/1.1, this model is only used when the [`Connection`](headers/connection) header is sent with a value of `close`. **Note:** Unless dealing with a very old system, which doesn't support a persistent connection, there is no compelling reason to use this model. Persistent connections ---------------------- Short-lived connections have two major hitches: the time taken to establish a new connection is significant, and performance of the underlying TCP connection gets better only when this connection has been in use for some time (warm connection). To ease these problems, the concept of a *persistent connection* has been designed, even prior to HTTP/1.1. Alternatively this may be called a *keep-alive connection*. A persistent connection is one which remains open for a period of time, and can be reused for several requests, saving the need for a new TCP handshake, and utilizing TCP's performance enhancing capabilities. This connection will not stay open forever: idle connections are closed after some time (a server may use the [`Keep-Alive`](headers/keep-alive) header to specify a minimum time the connection should be kept open). Persistent connections also have drawbacks; even when idling they consume server resources, and under heavy load, [DoS attacks](https://developer.mozilla.org/en-US/docs/Glossary/DOS_attack) can be conducted. In such cases, using non-persistent connections, which are closed as soon as they are idle, can provide better performance. HTTP/1.0 connections are not persistent by default. Setting [`Connection`](headers/connection) to anything other than `close`, usually `retry-after`, will make them persistent. In HTTP/1.1, persistence is the default, and the header is no longer needed (but it is often added as a defensive measure against cases requiring a fallback to HTTP/1.0). HTTP pipelining --------------- **Note:** HTTP pipelining is not activated by default in modern browsers: * Buggy [proxies](https://en.wikipedia.org/wiki/Proxy_server) are still common and these lead to strange and erratic behaviors that Web developers cannot foresee and diagnose easily. * Pipelining is complex to implement correctly: the size of the resource being transferred, the effective [RTT](https://en.wikipedia.org/wiki/Round-trip_delay_time) that will be used, as well as the effective bandwidth, have a direct incidence on the improvement provided by the pipeline. Without knowing these, important messages may be delayed behind unimportant ones. The notion of important even evolves during page layout! HTTP pipelining therefore brings a marginal improvement in most cases only. * Pipelining is subject to the [HOL](https://en.wikipedia.org/wiki/Head-of-line_blocking) problem. For these reasons, pipelining has been superseded by a better algorithm, *multiplexing*, that is used by HTTP/2. By default, [HTTP](index) requests are issued sequentially. The next request is only issued once the response to the current request has been received. As they are affected by network latencies and bandwidth limitations, this can result in significant delay before the next request is *seen* by the server. Pipelining is the process to send successive requests, over the same persistent connection, without waiting for the answer. This avoids latency of the connection. Theoretically, performance could also be improved if two HTTP requests were to be packed into the same TCP message. The typical [MSS](https://en.wikipedia.org/wiki/Maximum_segment_size) (Maximum Segment Size), is big enough to contain several simple requests, although the demand in size of HTTP requests continues to grow. Not all types of HTTP requests can be pipelined: only [idempotent](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent) methods, that is [`GET`](methods/get), [`HEAD`](methods/head), [`PUT`](methods/put) and [`DELETE`](methods/delete), can be replayed safely. Should a failure happen, the pipeline content can be repeated. Today, every HTTP/1.1-compliant proxy and server should support pipelining, though many have limitations in practice: a significant reason no modern browser activates this feature by default. Domain sharding --------------- **Note:** Unless you have a very specific immediate need, don't use this deprecated technique; switch to HTTP/2 instead. In HTTP/2, domain sharding is no longer useful: the HTTP/2 connection is able to handle parallel unprioritized requests very well. Domain sharding is even detrimental to performance. Most HTTP/2 implementations use a technique called [connection coalescing](https://daniel.haxx.se/blog/2016/08/18/http2-connection-coalescing/) to revert eventual domain sharding. As an HTTP/1.x connection is serializing requests, even without any ordering, it can't be optimal without large enough available bandwidth. As a solution, browsers open several connections to each domain, sending parallel requests. Default was once 2 to 3 connections, but this has now increased to a more common use of 6 parallel connections. There is a risk of triggering [DoS](https://developer.mozilla.org/en-US/docs/Glossary/DOS_attack) protection on the server side if attempting more than this number. If the server wishes a faster Web site or application response, it is possible for the server to force the opening of more connections. For example, instead of having all resources on the same domain, say `www.example.com`, it could split over several domains, `www1.example.com`, `www2.example.com`, `www3.example.com`. Each of these domains resolves to the *same* server, and the Web browser will open 6 connections to each (in our example, boosting the connections to 18). This technique is called *domain sharding*. Conclusion ---------- Improved connection management allows considerable boosting of performance in HTTP. With HTTP/1.1 or HTTP/1.0, using a persistent connection – at least until it becomes idle – leads to the best performance. However, the failure of pipelining has lead to designing superior connection management models, which have been incorporated into HTTP/2. http Messages Messages ======== HTTP Messages ============= HTTP messages are how data is exchanged between a server and a client. There are two types of messages: *requests* sent by the client to trigger an action on the server, and *responses*, the answer from the server. HTTP messages are composed of textual information encoded in ASCII, and span over multiple lines. In HTTP/1.1, and earlier versions of the protocol, these messages were openly sent across the connection. In HTTP/2, the once human-readable message is now divided up into HTTP frames, providing optimization and performance improvements. Web developers, or webmasters, rarely craft these textual HTTP messages themselves: software, a Web browser, proxy, or Web server, perform this action. They provide HTTP messages through config files (for proxies or servers), APIs (for browsers), or other interfaces. The HTTP/2 binary framing mechanism has been designed to not require any alteration of the APIs or config files applied: it is broadly transparent to the user. HTTP requests, and responses, share similar structure and are composed of: 1. A *start-line* describing the requests to be implemented, or its status of whether successful or a failure. This start-line is always a single line. 2. An optional set of *HTTP headers* specifying the request, or describing the body included in the message. 3. A blank line indicating all meta-information for the request has been sent. 4. An optional *body* containing data associated with the request (like content of an HTML form), or the document associated with a response. The presence of the body and its size is specified by the start-line and HTTP headers. The start-line and HTTP headers of the HTTP message are collectively known as the *head* of the requests, whereas its payload is known as the *body*. HTTP Requests ------------- ### Start line HTTP requests are messages sent by the client to initiate an action on the server. Their *start-line* contain three elements: 1. An *[HTTP method](methods)*, a verb (like [`GET`](methods/get), [`PUT`](methods/put) or [`POST`](methods/post)) or a noun (like [`HEAD`](methods/head) or [`OPTIONS`](methods/options)), that describes the action to be performed. For example, `GET` indicates that a resource should be fetched or `POST` means that data is pushed to the server (creating or modifying a resource, or generating a temporary document to send back). 2. The *request target*, usually a [URL](https://developer.mozilla.org/en-US/docs/Glossary/URL), or the absolute path of the protocol, port, and domain are usually characterized by the request context. The format of this request target varies between different HTTP methods. It can be * An absolute path, ultimately followed by a `'?'` and query string. This is the most common form, known as the *origin form*, and is used with `GET`, `POST`, `HEAD`, and `OPTIONS` methods. + `POST / HTTP/1.1` + `GET /background.png HTTP/1.0` + `HEAD /test.html?query=alibaba HTTP/1.1` + `OPTIONS /anypage.html HTTP/1.0` * A complete URL, known as the *absolute form*, is mostly used with `GET` when connected to a proxy. `GET https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages HTTP/1.1` * The authority component of a URL, consisting of the domain name and optionally the port (prefixed by a `':'`), is called the *authority form*. It is only used with `CONNECT` when setting up an HTTP tunnel. `CONNECT developer.mozilla.org:80 HTTP/1.1` * The *asterisk form*, a simple asterisk (`'*'`) is used with `OPTIONS`, representing the server as a whole. `OPTIONS * HTTP/1.1` 3. The *HTTP version*, which defines the structure of the remaining message, acting as an indicator of the expected version to use for the response. ### Headers [HTTP headers](headers) from a request follow the same basic structure of an HTTP header: a case-insensitive string followed by a colon (`':'`) and a value whose structure depends upon the header. The whole header, including the value, consists of one single line, which can be quite long. Many different headers can appear in requests. They can be divided in several groups: * [General headers](https://developer.mozilla.org/en-US/docs/Glossary/General_header), like [`Via`](headers/via), apply to the message as a whole. * [Request headers](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), like [`User-Agent`](headers/user-agent) or [`Accept`](headers/accept), modify the request by specifying it further (like [`Accept-Language`](headers/accept-language)), by giving context (like [`Referer`](headers/referer)), or by conditionally restricting it (like [`If-None`](headers/if-none)). * [Representation headers](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header) like [`Content-Type`](headers/content-type) that describe the original format of the message data and any encoding applied (only present if the message has a body). ### Body The final part of the request is its body. Not all requests have one: requests fetching resources, like `GET`, `HEAD`, `DELETE`, or `OPTIONS`, usually don't need one. Some requests send data to the server in order to update it: as often the case with `POST` requests (containing HTML form data). Bodies can be broadly divided into two categories: * Single-resource bodies, consisting of one single file, defined by the two headers: [`Content-Type`](headers/content-type) and [`Content-Length`](headers/content-length). * [Multiple-resource bodies](basics_of_http/mime_types#multipartform-data), consisting of a multipart body, each containing a different bit of information. This is typically associated with [HTML Forms](https://developer.mozilla.org/en-US/docs/Learn/Forms). HTTP Responses -------------- ### Status line The start line of an HTTP response, called the *status line*, contains the following information: 1. The *protocol version*, usually `HTTP/1.1`. 2. A *status code*, indicating success or failure of the request. Common status codes are [`200`](status/200), [`404`](status/404), or [`302`](status/302) 3. A *status text*. A brief, purely informational, textual description of the status code to help a human understand the HTTP message. A typical status line looks like: `HTTP/1.1 404 Not Found`. ### Headers [HTTP headers](headers) for responses follow the same structure as any other header: a case-insensitive string followed by a colon (`':'`) and a value whose structure depends upon the type of the header. The whole header, including its value, presents as a single line. Many different headers can appear in responses. These can be divided into several groups: * [General headers](https://developer.mozilla.org/en-US/docs/Glossary/General_header), like [`Via`](headers/via), apply to the whole message. * [Response headers](https://developer.mozilla.org/en-US/docs/Glossary/Response_header), like [`Vary`](headers/vary) and [`Accept-Ranges`](headers/accept-ranges), give additional information about the server which doesn't fit in the status line. * [Representation headers](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header) like [`Content-Type`](headers/content-type) that describe the original format of the message data and any encoding applied (only present if the message has a body). ### Body The last part of a response is the body. Not all responses have one: responses with a status code that sufficiently answers the request without the need for corresponding payload (like [`201`](status/201) `Created` or [`204`](status/204) `No Content`) usually don't. Bodies can be broadly divided into three categories: * Single-resource bodies, consisting of a single file of known length, defined by the two headers: [`Content-Type`](headers/content-type) and [`Content-Length`](headers/content-length). * Single-resource bodies, consisting of a single file of unknown length, encoded by chunks with [`Transfer-Encoding`](headers/transfer-encoding) set to `chunked`. * [Multiple-resource bodies](basics_of_http/mime_types#multipartform-data), consisting of a multipart body, each containing a different section of information. These are relatively rare. HTTP/2 Frames ------------- HTTP/1.x messages have a few drawbacks for performance: * Headers, unlike bodies, are uncompressed. * Headers are often very similar from one message to the next one, yet still repeated across connections. * No multiplexing can be done. Several connections need opening on the same server: and warm TCP connections are more efficient than cold ones. HTTP/2 introduces an extra step: it divides HTTP/1.x messages into frames which are embedded in a stream. Data and header frames are separated, which allows header compression. Several streams can be combined together, a process called *multiplexing*, allowing more efficient use of underlying TCP connections. HTTP frames are now transparent to Web developers. This is an additional step in HTTP/2, between HTTP/1.1 messages and the underlying transport protocol. No changes are needed in the APIs used by Web developers to utilize HTTP frames; when available in both the browser and the server, HTTP/2 is switched on and used. Conclusion ---------- HTTP messages are the key in using HTTP; their structure is simple, and they are highly extensible. The HTTP/2 framing mechanism adds a new intermediate layer between the HTTP/1.x syntax and the underlying transport protocol, without fundamentally modifying it: building upon proven mechanisms. http Feature Policy Feature Policy ============== Feature Policy ============== Feature Policy allows web developers to selectively enable, disable, and modify the behavior of certain features and APIs in the browser. It is similar to [Content Security Policy](https://developer.mozilla.org/en-US/docs/Glossary/CSP) but controls features instead of security behavior. **Warning:** The [`Feature-Policy`](headers/feature-policy) header has now been renamed to `Permissions-Policy` in the spec, and this article will eventually be updated to reflect that change. In a nutshell ------------- Feature Policy provides a mechanism to explicitly declare what functionality is used (or not used), throughout your website. This allows you to lock in best practices, even as the codebase evolves over time — as well as to more safely compose third-party content — by limiting which features are available. With Feature Policy, you opt-in to a set of "policies" for the browser to enforce on specific features used throughout a website. These policies restrict what APIs the site can access or modify the browser's default behavior for certain features. Examples of what you can do with Feature Policy: * Change the default behavior of autoplay on mobile and third party videos. * Restrict a site from using sensitive devices like the camera, microphone, or speakers. * Allow iframes to use the [fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API). * Block the use of outdated APIs like [synchronous XHR](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) and [`document.write()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/write). * Ensure images are sized properly and are not too big for the viewport. Concepts and usage ------------------ Feature Policy allows you to control which origins can use which features, both in the top-level page and in embedded frames. Essentially, you write a policy, which is an allowed list of origins for each feature. For every feature controlled by Feature Policy, the feature is only enabled in the current document or frame if its origin matches the allowed list of origins. For each policy-controlled feature, the browser maintains a list of origins for which the feature is enabled, known as an allowlist. If you do not specify a policy for a feature, then a default allowlist will be used. The default allowlist is specific to each feature. ### Writing a policy A policy is described using a set of individual policy directives. A policy directive is a combination of a defined feature name, and an allowlist of origins that can use the feature. ### Specifying your policy Feature Policy provides two ways to specify policies to control features: * The [`Feature-Policy`](headers/feature-policy) HTTP header. * The [`allow`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attributes) attribute on iframes. The primary difference between the HTTP header and the `allow` attribute is that the allow attribute only controls features within an iframe. The header controls features in the response and any embedded content within the page. For more details see [Using Feature Policy](feature_policy/using_feature_policy). ### Inferring the policy Scripts can programmatically query information about the feature policy via the [`FeaturePolicy`](https://developer.mozilla.org/en-US/docs/Web/API/FeaturePolicy) object located at either [`Document.featurePolicy`](https://developer.mozilla.org/en-US/docs/Web/API/Document/featurePolicy) or [`HTMLIFrameElement.featurePolicy`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/featurePolicy). Types of policy-controlled features ----------------------------------- Though Feature Policy provides control of multiple features using a consistent syntax, the behavior of policy controlled features varies and depends on several factors. The general principle is that there should be an intuitive or non-breaking way for web developers to detect or handle the case when the feature is disabled. Newly introduced features may have an explicit API to signal the state. Existing features that later integrate with Feature Policy will typically use existing mechanisms. Some approaches include: * Return "permission denied" for JavaScript APIs that require user permission grants. * Return `false` or error from an existing JavaScript API that provides access to feature. * Change the default values or options that control the feature behavior. The current set of policy-controlled features fall into two broad categories: * Enforcing best practices for good user experiences. * Providing granular control over sensitive or powerful features. ### Best practices for good user experiences There are several policy-controlled features to help enforce best practices for providing good performance and user experiences. In most cases, the policy-controlled features represent functionality that when used will negatively impact the user experience. To avoid breaking existing web content, the default for such policy-controlled features is to allow the functionality to be used by all origins. Best practices are then enforced by using policies that disable the policy-controlled features. For more details see [Enforcing best practices for good user experiences](feature_policy/using_feature_policy#enforcing_best_practices_for_good_user_experiences) The features include: * Layout-inducing animations * Legacy image formats * Oversized images * Synchronous scripts * Synchronous XMLHTTPRequest * Unoptimized images * Unsized media ### Granular control over certain features The web provides functionality and APIs that may have privacy or security risks if abused. In some cases, you may wish to strictly limit how such functionality is used on a website. There are policy-controlled features to allow functionality to be enabled/disabled for specific origins or frames within a website. Where available, the feature integrates with the Permissions API, or feature-specific mechanisms to check if the feature is available. The features include (see [Features list](headers/feature-policy#directives)): * Accelerometer * Ambient light sensor * Autoplay * Camera * Encrypted media * Fullscreen * Gamepad * Geolocation * Gyroscope * Magnetometer * Microphone * Midi * PaymentRequest * Picture-in-picture * Speakers * USB * Web Share API * VR / XR Examples -------- * [Using Feature Policy](feature_policy/using_feature_policy) * See [Feature Policy Demos](https://feature-policy-demos.appspot.com/) for example usage of many policies. Specifications -------------- | Specification | | --- | | [Permissions Policy # permissions-policy-http-header-field](https://w3c.github.io/webappsec-permissions-policy/#permissions-policy-http-header-field) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Feature_Policy` | 60 | 79 | 74 Only supported through the `allow` attribute on `<iframe>` elements. | No | 47 | 11.1 Only supported through the `allow` attribute on `<iframe>` elements. | 60 | 60 | 79 Only supported through the `allow` attribute on `<iframe>` elements. | 44 | 11.3 Only supported through the `allow` attribute on `<iframe>` elements. | 8.0 | | `accelerometer` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 | | `ambient-light-sensor` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 | | `autoplay` | 64 | 79 | 74 | No | 51 | No | 64 | 64 | No | 47 | No | 9.0 | | `battery` | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | No | No | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | No | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | No | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | No | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | | `camera` | 60 | 79 | 74 Only supported through the `allow` attribute on `<iframe>` elements. | No | 48 | 11.1 | 60 | 60 | 79 Only supported through the `allow` attribute on `<iframe>` elements. | 45 | 11.3 | 8.0 | | `display-capture` | 94 | 94 | 74 Only supported through the `allow` attribute on `<iframe>` elements. | No | 80 | 13 Only supported through the `allow` attribute on `<iframe>` elements. | No | No | No | No | No | No | | `document-domain` | 77 | 79 | 74 | No | 64 | No | No | No | No | No | No | No | | `encrypted-media` | 60 | 79 | 74 | No | 48 | No | 60 | 60 | No | 45 | No | 8.0 | | `fullscreen` | 62 | 79 | 74 ["Only supported through the `allow` attribute on `<iframe>` elements.", "Before Firefox 80, applying `fullscreen` to an `<iframe>` (i.e. via the `allow` attribute) does not work unless the `allowfullscreen` attribute is also present."] | No | 49 | No | 62 | 62 | 79 ["Only supported through the `allow` attribute on `<iframe>` elements.", "Before Firefox 80, applying `fullscreen` to an `<iframe>` (i.e. via the `allow` attribute) does not work unless the `allowfullscreen` attribute is also present."] | 46 | No | 8.0 | | `gamepad` | 86 | 86 | 91 ["Only supported through the `allow` attribute on `<iframe>` elements.", "The default allowlist is `*` instead of `self` (as required by the specification)."] | No | 72 | No | No | 86 | 91 ["Only supported through the `allow` attribute on `<iframe>` elements.", "The default allowlist is `*` instead of `self` (as required by the specification)."] | No | No | No | | `geolocation` | 60 | 79 | 74 Only supported through the `allow` attribute on `<iframe>` elements. | No | 47 | No | 60 | 60 | 79 Only supported through the `allow` attribute on `<iframe>` elements. | 44 | No | 8.0 | | `gyroscope` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 | | `layout-animations` | No | No | No | No | No | No | No | No | No | No | No | No | | `legacy-image-formats` | No | No | No | No | No | No | No | No | No | No | No | No | | `magnetometer` | 67 | 79 | No | No | 54 | No | No | 67 | No | 48 | No | 9.0 | | `microphone` | 60 | 79 | 74 Only supported through the `allow` attribute on `<iframe>` elements. | No | 48 | 11.1 | 60 | 60 | 79 Only supported through the `allow` attribute on `<iframe>` elements. | 45 | 11.3 | 8.0 | | `midi` | 60 | 79 | 74 | No | 47 | No | 60 | 60 | No | 44 | No | 8.0 | | `oversized-images` | No | No | No | No | No | No | No | No | No | No | No | No | | `payment` | 60 | 79 | 74 | No | 47 | No | 60 | 60 | No | 44 | No | 8.0 | | `picture-in-picture` | 71 | No | No | No | No | No | No | No | No | No | No | No | | `publickey-credentials-get` | 84 | 84 | No | No | No | No | 84 | 84 | No | No | No | 14.0 | | `screen-wake-lock` | No | No | No | No | No | No | No | No | No | No | No | No | | `speaker-selection` | No | No | 92 Only supported through the `allow` attribute on `<iframe>` elements. | No | No | No | No | No | No | No | No | No | | `sync-xhr` | 65 | 79 | No | No | 52 | No | 65 | 65 | No | 47 | No | 9.0 | | `unoptimized-images` | No | No | No | No | No | No | No | No | No | No | No | No | | `unsized-media` | No | No | No | No | No | No | No | No | No | No | No | No | | `usb` | 60 | 79 | No | No | 47 | No | No | 60 | No | 44 | No | 8.0 | | `web-share` | No | No | 81 ["Only supported through the `allow` attribute on `<iframe>` elements.", "Firefox recognizes the `web-share` permissions policy, but this has no effect in versions of Firefox that do not support the [`share()`](https://developer.mozilla.org/docs/Web/API/Navigator/share) method."] | No | No | No | No | No | 81 Only supported through the `allow` attribute on `<iframe>` elements. | No | No | No | | `xr-spatial-tracking` | 79 | 79 | No | No | 66 | No | No | 79 | No | No | No | 12.0 | See also -------- * [Using Feature Policy](feature_policy/using_feature_policy) * [`Feature-Policy`](headers/feature-policy) HTTP header * [allow](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attributes) attribute on iframes * [Introduction to Feature Policy](https://developer.chrome.com/blog/feature-policy/) * [Feature policies on www.chromestatus.com](https://chromestatus.com/features#component%3A%20Blink%3EFeaturePolicy) * [Feature-Policy Tester (Chrome Developer Tools extension)](https://chrome.google.com/webstore/detail/feature-policy-tester-dev/pchamnkhkeokbpahnocjaeednpbpacop) * [Privacy, permissions, and information security](https://developer.mozilla.org/en-US/docs/Web/Privacy)
programming_docs
http CSP CSP === Content Security Policy (CSP) ============================= **Content Security Policy** ([CSP](https://developer.mozilla.org/en-US/docs/Glossary/CSP)) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting ([XSS](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting)) and data injection attacks. These attacks are used for everything from data theft, to site defacement, to malware distribution. CSP is designed to be fully backward compatible (except CSP version 2 where there are some explicitly-mentioned inconsistencies in backward compatibility; more details [here](https://www.w3.org/TR/CSP2/) section 1.1). Browsers that don't support it still work with servers that implement it, and vice versa: browsers that don't support CSP ignore it, functioning as usual, defaulting to the standard same-origin policy for web content. If the site doesn't offer the CSP header, browsers likewise use the standard [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). To enable CSP, you need to configure your web server to return the [`Content-Security-Policy`](headers/content-security-policy) HTTP header. (Sometimes you may see mentions of the `X-Content-Security-Policy` header, but that's an older version and you don't need to specify it anymore.) Alternatively, the [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) element can be used to configure a policy, for example: ``` <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://\*; child-src 'none';" /> ``` Threats ------- ### Mitigating cross-site scripting A primary goal of CSP is to mitigate and report XSS attacks. XSS attacks exploit the browser's trust in the content received from the server. Malicious scripts are executed by the victim's browser because the browser trusts the source of the content, even when it's not coming from where it seems to be coming from. CSP makes it possible for server administrators to reduce or eliminate the vectors by which XSS can occur by specifying the domains that the browser should consider to be valid sources of executable scripts. A CSP compatible browser will then only execute scripts loaded in source files received from those allowed domains, ignoring all other scripts (including inline scripts and event-handling HTML attributes). As an ultimate form of protection, sites that want to never allow scripts to be executed can opt to globally disallow script execution. ### Mitigating packet sniffing attacks In addition to restricting the domains from which content can be loaded, the server can specify which protocols are allowed to be used; for example (and ideally, from a security standpoint), a server can specify that all content must be loaded using HTTPS. A complete data transmission security strategy includes not only enforcing HTTPS for data transfer, but also marking all [cookies with the `secure` attribute](cookies) and providing automatic redirects from HTTP pages to their HTTPS counterparts. Sites may also use the [`Strict-Transport-Security`](headers/strict-transport-security) HTTP header to ensure that browsers connect to them only over an encrypted channel. Using CSP --------- Configuring Content Security Policy involves adding the [`Content-Security-Policy`](headers/content-security-policy) HTTP header to a web page and giving it values to control what resources the user agent is allowed to load for that page. For example, a page that uploads and displays images could allow images from anywhere, but restrict a form action to a specific endpoint. A properly designed Content Security Policy helps protect a page against a cross-site scripting attack. This article explains how to construct such headers properly, and provides examples. ### Specifying your policy You can use the [`Content-Security-Policy`](headers/content-security-policy) HTTP header to specify your policy, like this: ``` Content-Security-Policy: policy ``` The policy is a string containing the policy directives describing your Content Security Policy. ### Writing a policy A policy is described using a series of policy directives, each of which describes the policy for a certain resource type or policy area. Your policy should include a [`default-src`](headers/content-security-policy/default-src) policy directive, which is a fallback for other resource types when they don't have policies of their own (for a complete list, see the description of the [`default-src`](headers/content-security-policy/default-src) directive). A policy needs to include a [`default-src`](headers/content-security-policy/default-src) or [`script-src`](headers/content-security-policy/script-src) directive to prevent inline scripts from running, as well as blocking the use of `eval()`. A policy needs to include a [`default-src`](headers/content-security-policy/default-src) or [`style-src`](headers/content-security-policy/style-src) directive to restrict inline styles from being applied from a [`<style>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style) element or a `style` attribute. There are specific directives for a wide variety of types of items, so that each type can have its own policy, including fonts, frames, images, audio and video media, scripts, and workers. For a complete list of policy directives, see the reference page for the [Content-Security-Policy header](headers/content-security-policy). Examples: Common use cases -------------------------- This section provides examples of some common security policy scenarios. ### Example 1 A web site administrator wants all content to come from the site's own origin (this excludes subdomains.) ``` Content-Security-Policy: default-src 'self' ``` ### Example 2 A web site administrator wants to allow content from a trusted domain and all its subdomains (it doesn't have to be the same domain that the CSP is set on.) ``` Content-Security-Policy: default-src 'self' example.com \*.example.com ``` ### Example 3 A web site administrator wants to allow users of a web application to include images from any origin in their own content, but to restrict audio or video media to trusted providers, and all scripts only to a specific server that hosts trusted code. ``` Content-Security-Policy: default-src 'self'; img-src \*; media-src example.org example.net; script-src userscripts.example.com ``` Here, by default, content is only permitted from the document's origin, with the following exceptions: * Images may load from anywhere (note the "\*" wildcard). * Media is only allowed from example.org and example.net (and not from subdomains of those sites). * Executable script is only allowed from userscripts.example.com. ### Example 4 A web site administrator for an online banking site wants to ensure that all its content is loaded using TLS, in order to prevent attackers from eavesdropping on requests. ``` Content-Security-Policy: default-src https://onlinebanking.example.com ``` The server permits access only to documents being loaded specifically over HTTPS through the single origin onlinebanking.example.com. ### Example 5 A web site administrator of a web mail site wants to allow HTML in email, as well as images loaded from anywhere, but not JavaScript or other potentially dangerous content. ``` Content-Security-Policy: default-src 'self' \*.example.com; img-src \* ``` Note that this example doesn't specify a [`script-src`](headers/content-security-policy/script-src); with the example CSP, this site uses the setting specified by the [`default-src`](headers/content-security-policy/default-src) directive, which means that scripts can be loaded only from the originating server. Testing your policy ------------------- To ease deployment, CSP can be deployed in report-only mode. The policy is not enforced, but any violations are reported to a provided URI. Additionally, a report-only header can be used to test a future revision to a policy without actually deploying it. You can use the [`Content-Security-Policy-Report-Only`](headers/content-security-policy-report-only) HTTP header to specify your policy, like this: ``` Content-Security-Policy-Report-Only: policy ``` If both a [`Content-Security-Policy-Report-Only`](headers/content-security-policy-report-only) header and a [`Content-Security-Policy`](headers/content-security-policy) header are present in the same response, both policies are honored. The policy specified in `Content-Security-Policy` headers is enforced while the `Content-Security-Policy-Report-Only` policy generates reports but is not enforced. Enabling reporting ------------------ By default, violation reports aren't sent. To enable violation reporting, you need to specify the [`report-uri`](headers/content-security-policy/report-uri) policy directive, providing at least one URI to which to deliver the reports: ``` Content-Security-Policy: default-src 'self'; report-uri http://reportcollector.example.com/collector.cgi ``` Then you need to set up your server to receive the reports; it can store or process them in whatever manner you determine is appropriate. Violation report syntax ----------------------- The report JSON object contains the following data: `blocked-uri` The URI of the resource that was blocked from loading by the Content Security Policy. If the blocked URI is from a different origin than the `document-uri`, then the blocked URI is truncated to contain just the scheme, host, and port. `disposition` Either `"enforce"` or `"report"` depending on whether the [`Content-Security-Policy-Report-Only`](headers/content-security-policy-report-only) header or the `Content-Security-Policy` header is used. `document-uri` The URI of the document in which the violation occurred. `effective-directive` The directive whose enforcement caused the violation. Some browsers may provide different values, such as Chrome providing `style-src-elem`/`style-src-attr`, even when the actually enforced directive was `style-src`. `original-policy` The original policy as specified by the `Content-Security-Policy` HTTP header. `referrer` Deprecated Non-standard The referrer of the document in which the violation occurred. `script-sample` The first 40 characters of the inline script, event handler, or style that caused the violation. Only applicable to `script-src*` and `style-src*` violations, when they contain the `'report-sample'` `status-code` The HTTP status code of the resource on which the global object was instantiated. `violated-directive` The name of the policy section that was violated. Sample violation report ----------------------- Let's consider a page located at `http://example.com/signup.html`. It uses the following policy, disallowing everything but stylesheets from `cdn.example.com`. ``` Content-Security-Policy: default-src 'none'; style-src cdn.example.com; report-uri /\_/csp-reports ``` The HTML of `signup.html` looks like this: ``` <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>Sign Up</title> <link rel="stylesheet" href="css/style.css" /> </head> <body> Here be content. </body> </html> ``` Can you spot the mistake? Stylesheets are allowed to be loaded only from `cdn.example.com`, yet the website tries to load one from its own origin (`http://example.com`). A browser capable of enforcing CSP would send the following violation report as a POST request to `http://example.com/_/csp-reports`, when the document is visited: ``` { "csp-report": { "document-uri": "http://example.com/signup.html", "referrer": "", "blocked-uri": "http://example.com/css/style.css", "violated-directive": "style-src cdn.example.com", "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri /\_/csp-reports" } } ``` As you can see, the report includes the full path to the violating resource in `blocked-uri`. This is not always the case. For example, if the `signup.html` attempted to load CSS from `http://anothercdn.example.com/stylesheet.css`, the browser would *not* include the full path, but only the origin (`http://anothercdn.example.com`). The CSP specification [gives an explanation](https://www.w3.org/TR/CSP/#security-violation-reports) of this odd behavior. In summary, this is done to prevent leaking sensitive information about cross-origin resources. Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `CSP` | 25 14 | 14 | 23 4 | 10 Only supporting 'sandbox' directive. | 15 | 7 6 | Yes | Yes | 23 | Yes | 7 6 | Yes | | `base-uri` | 40 | 79 | 35 | No | 27 | 10 | Yes | Yes | 35 | Yes | 9.3 | Yes | | `block-all-mixed-content` | Yes | ≤79 | 48 | No | Yes | No | Yes | Yes | 48 | Yes | No | Yes | | `child-src` | 40 | 15 | 45 | No | 27 | 10 | Yes | Yes | 45 | Yes | 9.3 | Yes | | `connect-src` | 25 | 14 | 23 Before Firefox 50, ping attributes of <a> elements weren't covered by connect-src. | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `default-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `font-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `form-action` | 40 | 15 | 36 | No | 27 | 10 | Yes | Yes | 36 | Yes | 9.3 | Yes | | `frame-ancestors` | 40 | 15 | 33 Before Firefox 58, `frame-ancestors` is ignored in `Content-Security-Policy-Report-Only`. | No | 26 | 10 | Yes | Yes | 33 Before Firefox for Android 58, `frame-ancestors` is ignored in `Content-Security-Policy-Report-Only`. | Yes | 9.3 | Yes | | `frame-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `img-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `manifest-src` | Yes | 79 | 41 | No | Yes | No | Yes | Yes | 41 | Yes | No | Yes | | `media-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `meta-element-support` | Yes | ≤18 | 45 | No | Yes | Yes | Yes | Yes | 45 | Yes | Yes | Yes | | `object-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `plugin-types` | 40-90 | 15-90 | No | No | 27-76 | 10 | Yes-90 | Yes-90 | No | Yes-64 | 9.3 | Yes-15.0 | | `prefetch-src` | No See [bug 801561](https://crbug.com/801561). | No See [bug 801561](https://crbug.com/801561). | No See [bug 1457204](https://bugzil.la/1457204). | No | No See [bug 801561](https://crbug.com/801561). | No See [bug 185070](https://webkit.org/b/185070). | No See [bug 801561](https://crbug.com/801561). | No See [bug 801561](https://crbug.com/801561). | No See [bug 1457204](https://bugzil.la/1457204). | No See [bug 801561](https://crbug.com/801561). | No See [bug 185070](https://webkit.org/b/185070). | No See [bug 801561](https://crbug.com/801561). | | `referrer` | 33-56 | No | 37-62 | No | 20-43 | No | 4.4.3-56 | 33-56 | 37-62 | 20-43 | No | 2.0-6.0 | | `report-sample` | 59 | ≤79 | No | No | 46 | 15.4 | 59 | 59 | No | 43 | 15.4 | 7.0 | | `report-to` | 70 | 79 | No | No | 57 | No | 70 | 70 | No | 49 | No | 10.0 | | `report-uri` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `require-sri-for` | 54 | 79 | No | No | 41 | No | 54 | 54 | No | 41 | No | 6.0 | | `require-trusted-types-for` | 83 | 83 | No | No | 69 | No | 83 | 83 | No | 59 | No | 13.0 | | `sandbox` | 25 | 14 | 50 | 10 | 15 | 7 | Yes | Yes | 50 | Yes | 7 | Yes | | `script-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `script-src-attr` | 75 | 79 | 105 preview | No | 62 | No | 75 | 75 | No | 54 | No | 11.0 | | `script-src-elem` | 75 | 79 | 105 preview | No | 62 | No | 75 | 75 | No | 54 | No | 11.0 | | `strict-dynamic` | 52 | 79 | 52 | No | 39 | 15.4 | 52 | 52 | No | 41 | 15.4 | 6.0 | | `style-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `style-src-attr` | 75 | 79 | 105 preview | No | 62 | No | 75 | 75 | No | 54 | No | 11.0 | | `style-src-elem` | 75 | 79 | 105 preview | No | 62 | No | 75 | 75 | No | 54 | No | 11.0 | | `trusted-types` | 83 | 83 | No | No | 69 | No | 83 | 83 | No | No | No | 13.0 | | `unsafe-hashes` | 69 | 79 | No See [bug 1343950](https://bugzil.la/1343950). | No | 56 | 15.4 | 69 | 69 | No See [bug 1343950](https://bugzil.la/1343950). | 48 | 15.4 | 10.0 | | `upgrade-insecure-requests` | 43 | 17 | 42 | No | 30 | 10.1 | 43 | 43 | 42 | 30 | 10.3 | 4.0 | | `worker-src` | 59 Chrome 59 and higher skips the deprecated `child-src` directive. | 79 | 58 | No | 46 Opera 46 and higher skips the deprecated `child-src` directive. | 15.5 | 59 Chrome 59 and higher skips the deprecated `child-src` directive. | 59 Chrome 59 and higher skips the deprecated `child-src` directive. | 58 | 43 Opera 43 and higher skips the deprecated `child-src` directive. | 15.5 | 7.0 | | `worker_support` | Yes | ≤79 | 50 | No | Yes | 10 | Yes | Yes | 50 | Yes | 10 | Yes | ### Compatibility notes A specific incompatibility exists in some versions of the Safari web browser, whereby if a Content Security Policy header is set, but not a Same Origin header, the browser will block self-hosted content and off-site content, and incorrectly report that this is due to the Content Security Policy not allowing the content. See also -------- * [`Content-Security-Policy`](headers/content-security-policy) HTTP Header * [`Content-Security-Policy-Report-Only`](headers/content-security-policy-report-only) HTTP Header * [Content Security in WebExtensions](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy) * [CSP in Web Workers](headers/content-security-policy#csp_in_workers) * [Privacy, permissions, and information security](https://developer.mozilla.org/en-US/docs/Web/Privacy) * [CSP Evaluator](https://github.com/google/csp-evaluator) - Evaluate your Content Security Policy http HTTP/2 Internet Engineering Task Force (IETF) M. Thomson, Ed. Request for Comments: 9113 Mozilla Obsoletes: [7540](https://datatracker.ietf.org/doc/html/rfc7540), [8740](https://datatracker.ietf.org/doc/html/rfc8740) C. Benfield, Ed. Category: Standards Track Apple Inc. ISSN: 2070-1721 June 2022 HTTP/2 ====== Abstract This specification describes an optimized expression of the semantics of the Hypertext Transfer Protocol (HTTP), referred to as HTTP version 2 (HTTP/2). HTTP/2 enables a more efficient use of network resources and a reduced latency by introducing field compression and allowing multiple concurrent exchanges on the same connection. This document obsoletes RFCs 7540 and 8740. Status of This Memo This is an Internet Standards Track document. This document is a product of the Internet Engineering Task Force (IETF). It represents the consensus of the IETF community. It has received public review and has been approved for publication by the Internet Engineering Steering Group (IESG). Further information on Internet Standards is available in [Section 2 of RFC 7841](https://datatracker.ietf.org/doc/html/rfc7841#section-2). Information about the current status of this document, any errata, and how to provide feedback on it may be obtained at <https://www.rfc-editor.org/info/rfc9113>. Copyright Notice Copyright (c) 2022 IETF Trust and the persons identified as the document authors. All rights reserved. This document is subject to [BCP 78](https://datatracker.ietf.org/doc/html/bcp78) and the IETF Trust's Legal Provisions Relating to IETF Documents (<https://trustee.ietf.org/license-info>) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Revised BSD License text as described in [Section 4](#section-4).e of the Trust Legal Provisions and are provided without warranty as described in the Revised BSD License. Table of Contents 1. Introduction 2. HTTP/2 Protocol Overview 2.1. Document Organization 2.2. Conventions and Terminology 3. Starting HTTP/2 3.1. HTTP/2 Version Identification 3.2. Starting HTTP/2 for "https" URIs 3.3. Starting HTTP/2 with Prior Knowledge 3.4. HTTP/2 Connection Preface 4. HTTP Frames 4.1. Frame Format 4.2. Frame Size 4.3. Field Section Compression and Decompression 4.3.1. Compression State 5. Streams and Multiplexing 5.1. Stream States 5.1.1. Stream Identifiers 5.1.2. Stream Concurrency 5.2. Flow Control 5.2.1. Flow-Control Principles 5.2.2. Appropriate Use of Flow Control 5.2.3. Flow-Control Performance 5.3. Prioritization 5.3.1. Background on Priority in [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) 5.3.2. Priority Signaling in This Document 5.4. Error Handling 5.4.1. Connection Error Handling 5.4.2. Stream Error Handling 5.4.3. Connection Termination 5.5. Extending HTTP/2 6. Frame Definitions 6.1. DATA 6.2. HEADERS 6.3. PRIORITY 6.4. RST\_STREAM 6.5. SETTINGS 6.5.1. SETTINGS Format 6.5.2. Defined Settings 6.5.3. Settings Synchronization 6.6. PUSH\_PROMISE 6.7. PING 6.8. GOAWAY 6.9. WINDOW\_UPDATE 6.9.1. The Flow-Control Window 6.9.2. Initial Flow-Control Window Size 6.9.3. Reducing the Stream Window Size 6.10. CONTINUATION 7. Error Codes 8. Expressing HTTP Semantics in HTTP/2 8.1. HTTP Message Framing 8.1.1. Malformed Messages 8.2. HTTP Fields 8.2.1. Field Validity 8.2.2. Connection-Specific Header Fields 8.2.3. Compressing the Cookie Header Field 8.3. HTTP Control Data 8.3.1. Request Pseudo-Header Fields 8.3.2. Response Pseudo-Header Fields 8.4. Server Push 8.4.1. Push Requests 8.4.2. Push Responses 8.5. The CONNECT Method 8.6. The Upgrade Header Field 8.7. Request Reliability 8.8. Examples 8.8.1. Simple Request 8.8.2. Simple Response 8.8.3. Complex Request 8.8.4. Response with Body 8.8.5. Informational Responses 9. HTTP/2 Connections 9.1. Connection Management 9.1.1. Connection Reuse 9.2. Use of TLS Features 9.2.1. TLS 1.2 Features 9.2.2. TLS 1.2 Cipher Suites 9.2.3. TLS 1.3 Features 10. Security Considerations 10.1. Server Authority 10.2. Cross-Protocol Attacks 10.3. Intermediary Encapsulation Attacks 10.4. Cacheability of Pushed Responses 10.5. Denial-of-Service Considerations 10.5.1. Limits on Field Block Size 10.5.2. CONNECT Issues 10.6. Use of Compression 10.7. Use of Padding 10.8. Privacy Considerations 10.9. Remote Timing Attacks 11. IANA Considerations 11.1. HTTP2-Settings Header Field Registration 11.2. The h2c Upgrade Token 12. References 12.1. Normative References 12.2. Informative References [Appendix A](#appendix-A). Prohibited TLS 1.2 Cipher Suites [Appendix B](#appendix-B). Changes from [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) Acknowledgments Contributors Authors' Addresses 1. Introduction --------------- The performance of applications using the Hypertext Transfer Protocol (HTTP, [[HTTP](#ref-HTTP)]) is linked to how each version of HTTP uses the underlying transport, and the conditions under which the transport operates. Making multiple concurrent requests can reduce latency and improve application performance. HTTP/1.0 allowed only one request to be outstanding at a time on a given TCP [[TCP](#ref-TCP)] connection. HTTP/1.1 [HTTP/1.1] added request pipelining, but this only partially addressed request concurrency and still suffers from application- layer head-of-line blocking. Therefore, HTTP/1.0 and HTTP/1.1 clients use multiple connections to a server to make concurrent requests. Furthermore, HTTP fields are often repetitive and verbose, causing unnecessary network traffic as well as causing the initial TCP congestion window to quickly fill. This can result in excessive latency when multiple requests are made on a new TCP connection. HTTP/2 addresses these issues by defining an optimized mapping of HTTP's semantics to an underlying connection. Specifically, it allows interleaving of messages on the same connection and uses an efficient coding for HTTP fields. It also allows prioritization of requests, letting more important requests complete more quickly, further improving performance. The resulting protocol is more friendly to the network because fewer TCP connections can be used in comparison to HTTP/1.x. This means less competition with other flows and longer-lived connections, which in turn lead to better utilization of available network capacity. Note, however, that TCP head-of-line blocking is not addressed by this protocol. Finally, HTTP/2 also enables more efficient processing of messages through use of binary message framing. This document obsoletes RFCs 7540 and 8740. [Appendix B](#appendix-B) lists notable changes. 2. HTTP/2 Protocol Overview --------------------------- HTTP/2 provides an optimized transport for HTTP semantics. HTTP/2 supports all of the core features of HTTP but aims to be more efficient than HTTP/1.1. HTTP/2 is a connection-oriented application-layer protocol that runs over a TCP connection ([[TCP](#ref-TCP)]). The client is the TCP connection initiator. The basic protocol unit in HTTP/2 is a frame ([Section 4.1](#section-4.1)). Each frame type serves a different purpose. For example, HEADERS and DATA frames form the basis of HTTP requests and responses ([Section 8.1](#section-8.1)); other frame types like SETTINGS, WINDOW\_UPDATE, and PUSH\_PROMISE are used in support of other HTTP/2 features. Multiplexing of requests is achieved by having each HTTP request/ response exchange associated with its own stream ([Section 5](#section-5)). Streams are largely independent of each other, so a blocked or stalled request or response does not prevent progress on other streams. Effective use of multiplexing depends on flow control and prioritization. Flow control ([Section 5.2](#section-5.2)) ensures that it is possible to efficiently use multiplexed streams by restricting data that is transmitted to what the receiver is able to handle. Prioritization ([Section 5.3](#section-5.3)) ensures that limited resources are used most effectively. This revision of HTTP/2 deprecates the priority signaling scheme from [[RFC7540](https://datatracker.ietf.org/doc/html/rfc7540)]. Because HTTP fields used in a connection can contain large amounts of redundant data, frames that contain them are compressed ([Section 4.3](#section-4.3)). This has especially advantageous impact upon request sizes in the common case, allowing many requests to be compressed into one packet. Finally, HTTP/2 adds a new, optional interaction mode whereby a server can push responses to a client ([Section 8.4](#section-8.4)). This is intended to allow a server to speculatively send data to a client that the server anticipates the client will need, trading off some network usage against a potential latency gain. The server does this by synthesizing a request, which it sends as a PUSH\_PROMISE frame. The server is then able to send a response to the synthetic request on a separate stream. ### 2.1. Document Organization The HTTP/2 specification is split into four parts: \* Starting HTTP/2 ([Section 3](#section-3)) covers how an HTTP/2 connection is initiated. \* The frame ([Section 4](#section-4)) and stream ([Section 5](#section-5)) layers describe the way HTTP/2 frames are structured and formed into multiplexed streams. \* Frame ([Section 6](#section-6)) and error ([Section 7](#section-7)) definitions include details of the frame and error types used in HTTP/2. \* HTTP mappings ([Section 8](#section-8)) and additional requirements ([Section 9](#section-9)) describe how HTTP semantics are expressed using frames and streams. While some of the frame- and stream-layer concepts are isolated from HTTP, this specification does not define a completely generic frame layer. The frame and stream layers are tailored to the needs of HTTP. ### 2.2. Conventions and Terminology The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://datatracker.ietf.org/doc/html/bcp14) [[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)] [[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when, and only when, they appear in all capitals, as shown here. All numeric values are in network byte order. Values are unsigned unless otherwise indicated. Literal values are provided in decimal or hexadecimal as appropriate. Hexadecimal literals are prefixed with "0x" to distinguish them from decimal literals. This specification describes binary formats using the conventions described in [Section 1.3 of RFC 9000](https://datatracker.ietf.org/doc/html/rfc9000#section-1.3) [[QUIC](#ref-QUIC)]. Note that this format uses network byte order and that high-valued bits are listed before low-valued bits. The following terms are used: client: The endpoint that initiates an HTTP/2 connection. Clients send HTTP requests and receive HTTP responses. connection: A transport-layer connection between two endpoints. connection error: An error that affects the entire HTTP/2 connection. endpoint: Either the client or server of the connection. frame: The smallest unit of communication within an HTTP/2 connection, consisting of a header and a variable-length sequence of octets structured according to the frame type. peer: An endpoint. When discussing a particular endpoint, "peer" refers to the endpoint that is remote to the primary subject of discussion. receiver: An endpoint that is receiving frames. sender: An endpoint that is transmitting frames. server: The endpoint that accepts an HTTP/2 connection. Servers receive HTTP requests and send HTTP responses. stream: A bidirectional flow of frames within the HTTP/2 connection. stream error: An error on the individual HTTP/2 stream. Finally, the terms "gateway", "intermediary", "proxy", and "tunnel" are defined in Section 3.7 of [[HTTP](#ref-HTTP)]. Intermediaries act as both client and server at different times. The term "content" as it applies to message bodies is defined in Section 6.4 of [[HTTP](#ref-HTTP)]. 3. Starting HTTP/2 ------------------ Implementations that generate HTTP requests need to discover whether a server supports HTTP/2. HTTP/2 uses the "http" and "https" URI schemes defined in Section 4.2 of [[HTTP](#ref-HTTP)], with the same default port numbers as HTTP/1.1 [HTTP/1.1]. These URIs do not include any indication about what HTTP versions an upstream server (the immediate peer to which the client wishes to establish a connection) supports. The means by which support for HTTP/2 is determined is different for "http" and "https" URIs. Discovery for "https" URIs is described in [Section 3.2](#section-3.2). HTTP/2 support for "http" URIs can only be discovered by out-of-band means and requires prior knowledge of the support as described in [Section 3.3](#section-3.3). ### 3.1. HTTP/2 Version Identification The protocol defined in this document has two identifiers. Creating a connection based on either implies the use of the transport, framing, and message semantics described in this document. \* The string "h2" identifies the protocol where HTTP/2 uses Transport Layer Security (TLS); see [Section 9.2](#section-9.2). This identifier is used in the TLS Application-Layer Protocol Negotiation (ALPN) extension [[TLS-ALPN](#ref-TLS-ALPN)] field and in any place where HTTP/2 over TLS is identified. The "h2" string is serialized into an ALPN protocol identifier as the two-octet sequence: 0x68, 0x32. \* The "h2c" string was previously used as a token for use in the HTTP Upgrade mechanism's Upgrade header field (Section 7.8 of [[HTTP](#ref-HTTP)]). This usage was never widely deployed and is deprecated by this document. The same applies to the HTTP2-Settings header field, which was used with the upgrade to "h2c". ### 3.2. Starting HTTP/2 for "https" URIs A client that makes a request to an "https" URI uses TLS [[TLS13](#ref-TLS13)] with the ALPN extension [[TLS-ALPN](#ref-TLS-ALPN)]. HTTP/2 over TLS uses the "h2" protocol identifier. The "h2c" protocol identifier MUST NOT be sent by a client or selected by a server; the "h2c" protocol identifier describes a protocol that does not use TLS. Once TLS negotiation is complete, both the client and the server MUST send a connection preface ([Section 3.4](#section-3.4)). ### 3.3. Starting HTTP/2 with Prior Knowledge A client can learn that a particular server supports HTTP/2 by other means. For example, a client could be configured with knowledge that a server supports HTTP/2. A client that knows that a server supports HTTP/2 can establish a TCP connection and send the connection preface ([Section 3.4](#section-3.4)) followed by HTTP/2 frames. Servers can identify these connections by the presence of the connection preface. This only affects the establishment of HTTP/2 connections over cleartext TCP; HTTP/2 connections over TLS MUST use protocol negotiation in TLS [[TLS-ALPN](#ref-TLS-ALPN)]. Likewise, the server MUST send a connection preface ([Section 3.4](#section-3.4)). Without additional information, prior support for HTTP/2 is not a strong signal that a given server will support HTTP/2 for future connections. For example, it is possible for server configurations to change, for configurations to differ between instances in clustered servers, or for network conditions to change. ### 3.4. HTTP/2 Connection Preface In HTTP/2, each endpoint is required to send a connection preface as a final confirmation of the protocol in use and to establish the initial settings for the HTTP/2 connection. The client and server each send a different connection preface. The client connection preface starts with a sequence of 24 octets, which in hex notation is: 0x505249202a20485454502f322e300d0a0d0a534d0d0a0d0a That is, the connection preface starts with the string "PRI \* HTTP/2.0\r\n\r\nSM\r\n\r\n". This sequence MUST be followed by a SETTINGS frame ([Section 6.5](#section-6.5)), which MAY be empty. The client sends the client connection preface as the first application data octets of a connection. | Note: The client connection preface is selected so that a large | proportion of HTTP/1.1 or HTTP/1.0 servers and intermediaries | do not attempt to process further frames. Note that this does | not address the concerns raised in [[TALKING](#ref-TALKING)]. The server connection preface consists of a potentially empty SETTINGS frame ([Section 6.5](#section-6.5)) that MUST be the first frame the server sends in the HTTP/2 connection. The SETTINGS frames received from a peer as part of the connection preface MUST be acknowledged (see [Section 6.5.3](#section-6.5.3)) after sending the connection preface. To avoid unnecessary latency, clients are permitted to send additional frames to the server immediately after sending the client connection preface, without waiting to receive the server connection preface. It is important to note, however, that the server connection preface SETTINGS frame might include settings that necessarily alter how a client is expected to communicate with the server. Upon receiving the SETTINGS frame, the client is expected to honor any settings established. In some configurations, it is possible for the server to transmit SETTINGS before the client sends additional frames, providing an opportunity to avoid this issue. Clients and servers MUST treat an invalid connection preface as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. A GOAWAY frame ([Section 6.8](#section-6.8)) MAY be omitted in this case, since an invalid preface indicates that the peer is not using HTTP/2. 4. HTTP Frames -------------- Once the HTTP/2 connection is established, endpoints can begin exchanging frames. ### 4.1. Frame Format All frames begin with a fixed 9-octet header followed by a variable- length frame payload. HTTP Frame { Length (24), Type (8), Flags (8), Reserved (1), Stream Identifier (31), Frame Payload (..), } Figure 1: Frame Layout The fields of the frame header are defined as: Length: The length of the frame payload expressed as an unsigned 24-bit integer in units of octets. Values greater than 2^14 (16,384) MUST NOT be sent unless the receiver has set a larger value for SETTINGS\_MAX\_FRAME\_SIZE. The 9 octets of the frame header are not included in this value. Type: The 8-bit type of the frame. The frame type determines the format and semantics of the frame. Frames defined in this document are listed in [Section 6](#section-6). Implementations MUST ignore and discard frames of unknown types. Flags: An 8-bit field reserved for boolean flags specific to the frame type. Flags are assigned semantics specific to the indicated frame type. Unused flags are those that have no defined semantics for a particular frame type. Unused flags MUST be ignored on receipt and MUST be left unset (0x00) when sending. Reserved: A reserved 1-bit field. The semantics of this bit are undefined, and the bit MUST remain unset (0x00) when sending and MUST be ignored when receiving. Stream Identifier: A stream identifier (see [Section 5.1.1](#section-5.1.1)) expressed as an unsigned 31-bit integer. The value 0x00 is reserved for frames that are associated with the connection as a whole as opposed to an individual stream. The structure and content of the frame payload are dependent entirely on the frame type. ### 4.2. Frame Size The size of a frame payload is limited by the maximum size that a receiver advertises in the SETTINGS\_MAX\_FRAME\_SIZE setting. This setting can have any value between 2^14 (16,384) and 2^24-1 (16,777,215) octets, inclusive. All implementations MUST be capable of receiving and minimally processing frames up to 2^14 octets in length, plus the 9-octet frame header ([Section 4.1](#section-4.1)). The size of the frame header is not included when describing frame sizes. | Note: Certain frame types, such as PING ([Section 6.7](#section-6.7)), impose | additional limits on the amount of frame payload data allowed. An endpoint MUST send an error code of FRAME\_SIZE\_ERROR if a frame exceeds the size defined in SETTINGS\_MAX\_FRAME\_SIZE, exceeds any limit defined for the frame type, or is too small to contain mandatory frame data. A frame size error in a frame that could alter the state of the entire connection MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)); this includes any frame carrying a field block ([Section 4.3](#section-4.3)) (that is, HEADERS, PUSH\_PROMISE, and CONTINUATION), a SETTINGS frame, and any frame with a stream identifier of 0. Endpoints are not obligated to use all available space in a frame. Responsiveness can be improved by using frames that are smaller than the permitted maximum size. Sending large frames can result in delays in sending time-sensitive frames (such as RST\_STREAM, WINDOW\_UPDATE, or PRIORITY), which, if blocked by the transmission of a large frame, could affect performance. ### 4.3. Field Section Compression and Decompression Field section compression is the process of compressing a set of field lines (Section 5.2 of [[HTTP](#ref-HTTP)]) to form a field block. Field section decompression is the process of decoding a field block into a set of field lines. Details of HTTP/2 field section compression and decompression are defined in [[COMPRESSION](#ref-COMPRESSION)], which, for historical reasons, refers to these processes as header compression and decompression. Each field block carries all of the compressed field lines of a single field section. Header sections also include control data associated with the message in the form of pseudo-header fields ([Section 8.3](#section-8.3)) that use the same format as a field line. | Note: [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) [[RFC7540](https://datatracker.ietf.org/doc/html/rfc7540)] used the term "header block" in place | of the more generic "field block". Field blocks carry control data and header sections for requests, responses, promised requests, and pushed responses (see [Section 8.4](#section-8.4)). All these messages, except for interim responses and requests contained in PUSH\_PROMISE ([Section 6.6](#section-6.6)) frames, can optionally include a field block that carries a trailer section. A field section is a collection of field lines. Each of the field lines in a field block carries a single value. The serialized field block is then divided into one or more octet sequences, called field block fragments. The first field block fragment is transmitted within the frame payload of HEADERS ([Section 6.2](#section-6.2)) or PUSH\_PROMISE ([Section 6.6](#section-6.6)), each of which could be followed by CONTINUATION ([Section 6.10](#section-6.10)) frames to carry subsequent field block fragments. The Cookie header field [[COOKIE](#ref-COOKIE)] is treated specially by the HTTP mapping (see [Section 8.2.3](#section-8.2.3)). A receiving endpoint reassembles the field block by concatenating its fragments and then decompresses the block to reconstruct the field section. A complete field section consists of either: \* a single HEADERS or PUSH\_PROMISE frame, with the END\_HEADERS flag set, or \* a HEADERS or PUSH\_PROMISE frame with the END\_HEADERS flag unset and one or more CONTINUATION frames, where the last CONTINUATION frame has the END\_HEADERS flag set. Each field block is processed as a discrete unit. Field blocks MUST be transmitted as a contiguous sequence of frames, with no interleaved frames of any other type or from any other stream. The last frame in a sequence of HEADERS or CONTINUATION frames has the END\_HEADERS flag set. The last frame in a sequence of PUSH\_PROMISE or CONTINUATION frames has the END\_HEADERS flag set. This allows a field block to be logically equivalent to a single frame. Field block fragments can only be sent as the frame payload of HEADERS, PUSH\_PROMISE, or CONTINUATION frames because these frames carry data that can modify the compression context maintained by a receiver. An endpoint receiving HEADERS, PUSH\_PROMISE, or CONTINUATION frames needs to reassemble field blocks and perform decompression even if the frames are to be discarded. A receiver MUST terminate the connection with a connection error ([Section 5.4.1](#section-5.4.1)) of type COMPRESSION\_ERROR if it does not decompress a field block. A decoding error in a field block MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type COMPRESSION\_ERROR. #### 4.3.1. Compression State Field compression is stateful. Each endpoint has an HPACK encoder context and an HPACK decoder context that are used for encoding and decoding all field blocks on a connection. Section 4 of [[COMPRESSION](#ref-COMPRESSION)] defines the dynamic table, which is the primary state for each context. The dynamic table has a maximum size that is set by an HPACK decoder. An endpoint communicates the size chosen by its HPACK decoder context using the SETTINGS\_HEADER\_TABLE\_SIZE setting; see [Section 6.5.2](#section-6.5.2). When a connection is established, the dynamic table size for the HPACK decoder and encoder at both endpoints starts at 4,096 bytes, the initial value of the SETTINGS\_HEADER\_TABLE\_SIZE setting. Any change to the maximum value set using SETTINGS\_HEADER\_TABLE\_SIZE takes effect when the endpoint acknowledges settings ([Section 6.5.3](#section-6.5.3)). The HPACK encoder at that endpoint can set the dynamic table to any size up to the maximum value set by the decoder. An HPACK encoder declares the size of the dynamic table with a Dynamic Table Size Update instruction (Section 6.3 of [[COMPRESSION](#ref-COMPRESSION)]). Once an endpoint acknowledges a change to SETTINGS\_HEADER\_TABLE\_SIZE that reduces the maximum below the current size of the dynamic table, its HPACK encoder MUST start the next field block with a Dynamic Table Size Update instruction that sets the dynamic table to a size that is less than or equal to the reduced maximum; see Section 4.2 of [[COMPRESSION](#ref-COMPRESSION)]. An endpoint MUST treat a field block that follows an acknowledgment of the reduction to the maximum dynamic table size as a connection error ([Section 5.4.1](#section-5.4.1)) of type COMPRESSION\_ERROR if it does not start with a conformant Dynamic Table Size Update instruction. | Implementers are advised that reducing the value of | SETTINGS\_HEADER\_TABLE\_SIZE is not widely interoperable. Use of | the connection preface to reduce the value below the initial | value of 4,096 is somewhat better supported, but this might | fail with some implementations. 5. Streams and Multiplexing --------------------------- A "stream" is an independent, bidirectional sequence of frames exchanged between the client and server within an HTTP/2 connection. Streams have several important characteristics: \* A single HTTP/2 connection can contain multiple concurrently open streams, with either endpoint interleaving frames from multiple streams. \* Streams can be established and used unilaterally or shared by either endpoint. \* Streams can be closed by either endpoint. \* The order in which frames are sent is significant. Recipients process frames in the order they are received. In particular, the order of HEADERS and DATA frames is semantically significant. \* Streams are identified by an integer. Stream identifiers are assigned to streams by the endpoint initiating the stream. ### 5.1. Stream States The lifecycle of a stream is shown in Figure 2. +--------+ send PP | | recv PP ,--------+ idle +--------. / | | \ v +--------+ v +----------+ | +----------+ | | | send H / | | ,------+ reserved | | recv H | reserved +------. | | (local) | | | (remote) | | | +---+------+ v +------+---+ | | | +--------+ | | | | recv ES | | send ES | | | send H | ,-------+ open +-------. | recv H | | | / | | \ | | | v v +---+----+ v v | | +----------+ | +----------+ | | | half- | | | half- | | | | closed | | send R / | closed | | | | (remote) | | recv R | (local) | | | +----+-----+ | +-----+----+ | | | | | | | | send ES / | recv ES / | | | | send R / v send R / | | | | recv R +--------+ recv R | | | send R / `----------->| |<-----------' send R / | | recv R | closed | recv R | `----------------------->| |<-----------------------' +--------+ Figure 2: Stream States send: endpoint sends this frame recv: endpoint receives this frame H: HEADERS frame (with implied CONTINUATION frames) ES: END\_STREAM flag R: RST\_STREAM frame PP: PUSH\_PROMISE frame (with implied CONTINUATION frames); state transitions are for the promised stream Note that this diagram shows stream state transitions and the frames and flags that affect those transitions only. In this regard, CONTINUATION frames do not result in state transitions; they are effectively part of the HEADERS or PUSH\_PROMISE that they follow. For the purpose of state transitions, the END\_STREAM flag is processed as a separate event to the frame that bears it; a HEADERS frame with the END\_STREAM flag set can cause two state transitions. Both endpoints have a subjective view of the state of a stream that could be different when frames are in transit. Endpoints do not coordinate the creation of streams; they are created unilaterally by either endpoint. The negative consequences of a mismatch in states are limited to the "closed" state after sending RST\_STREAM, where frames might be received for some time after closing. Streams have the following states: idle: All streams start in the "idle" state. The following transitions are valid from this state: \* Sending a HEADERS frame as a client, or receiving a HEADERS frame as a server, causes the stream to become "open". The stream identifier is selected as described in [Section 5.1.1](#section-5.1.1). The same HEADERS frame can also cause a stream to immediately become "half-closed". \* Sending a PUSH\_PROMISE frame on another stream reserves the idle stream that is identified for later use. The stream state for the reserved stream transitions to "reserved (local)". Only a server may send PUSH\_PROMISE frames. \* Receiving a PUSH\_PROMISE frame on another stream reserves an idle stream that is identified for later use. The stream state for the reserved stream transitions to "reserved (remote)". Only a client may receive PUSH\_PROMISE frames. \* Note that the PUSH\_PROMISE frame is not sent on the idle stream but references the newly reserved stream in the Promised Stream ID field. \* Opening a stream with a higher-valued stream identifier causes the stream to transition immediately to a "closed" state; note that this transition is not shown in the diagram. Receiving any frame other than HEADERS or PRIORITY on a stream in this state MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. If this stream is initiated by the server, as described in [Section 5.1.1](#section-5.1.1), then receiving a HEADERS frame MUST also be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. reserved (local): A stream in the "reserved (local)" state is one that has been promised by sending a PUSH\_PROMISE frame. A PUSH\_PROMISE frame reserves an idle stream by associating the stream with an open stream that was initiated by the remote peer (see [Section 8.4](#section-8.4)). In this state, only the following transitions are possible: \* The endpoint can send a HEADERS frame. This causes the stream to open in a "half-closed (remote)" state. \* Either endpoint can send a RST\_STREAM frame to cause the stream to become "closed". This releases the stream reservation. An endpoint MUST NOT send any type of frame other than HEADERS, RST\_STREAM, or PRIORITY in this state. A PRIORITY or WINDOW\_UPDATE frame MAY be received in this state. Receiving any type of frame other than RST\_STREAM, PRIORITY, or WINDOW\_UPDATE on a stream in this state MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. reserved (remote): A stream in the "reserved (remote)" state has been reserved by a remote peer. In this state, only the following transitions are possible: \* Receiving a HEADERS frame causes the stream to transition to "half-closed (local)". \* Either endpoint can send a RST\_STREAM frame to cause the stream to become "closed". This releases the stream reservation. An endpoint MUST NOT send any type of frame other than RST\_STREAM, WINDOW\_UPDATE, or PRIORITY in this state. Receiving any type of frame other than HEADERS, RST\_STREAM, or PRIORITY on a stream in this state MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. open: A stream in the "open" state may be used by both peers to send frames of any type. In this state, sending peers observe advertised stream-level flow-control limits ([Section 5.2](#section-5.2)). From this state, either endpoint can send a frame with an END\_STREAM flag set, which causes the stream to transition into one of the "half-closed" states. An endpoint sending an END\_STREAM flag causes the stream state to become "half-closed (local)"; an endpoint receiving an END\_STREAM flag causes the stream state to become "half-closed (remote)". Either endpoint can send a RST\_STREAM frame from this state, causing it to transition immediately to "closed". half-closed (local): A stream that is in the "half-closed (local)" state cannot be used for sending frames other than WINDOW\_UPDATE, PRIORITY, and RST\_STREAM. A stream transitions from this state to "closed" when a frame is received with the END\_STREAM flag set or when either peer sends a RST\_STREAM frame. An endpoint can receive any type of frame in this state. Providing flow-control credit using WINDOW\_UPDATE frames is necessary to continue receiving flow-controlled frames. In this state, a receiver can ignore WINDOW\_UPDATE frames, which might arrive for a short period after a frame with the END\_STREAM flag set is sent. PRIORITY frames can be received in this state. half-closed (remote): A stream that is "half-closed (remote)" is no longer being used by the peer to send frames. In this state, an endpoint is no longer obligated to maintain a receiver flow- control window. If an endpoint receives additional frames, other than WINDOW\_UPDATE, PRIORITY, or RST\_STREAM, for a stream that is in this state, it MUST respond with a stream error ([Section 5.4.2](#section-5.4.2)) of type STREAM\_CLOSED. A stream that is "half-closed (remote)" can be used by the endpoint to send frames of any type. In this state, the endpoint continues to observe advertised stream-level flow-control limits ([Section 5.2](#section-5.2)). A stream can transition from this state to "closed" by sending a frame with the END\_STREAM flag set or when either peer sends a RST\_STREAM frame. closed: The "closed" state is the terminal state. A stream enters the "closed" state after an endpoint both sends and receives a frame with an END\_STREAM flag set. A stream also enters the "closed" state after an endpoint either sends or receives a RST\_STREAM frame. An endpoint MUST NOT send frames other than PRIORITY on a closed stream. An endpoint MAY treat receipt of any other type of frame on a closed stream as a connection error ([Section 5.4.1](#section-5.4.1)) of type STREAM\_CLOSED, except as noted below. An endpoint that sends a frame with the END\_STREAM flag set or a RST\_STREAM frame might receive a WINDOW\_UPDATE or RST\_STREAM frame from its peer in the time before the peer receives and processes the frame that closes the stream. An endpoint that sends a RST\_STREAM frame on a stream that is in the "open" or "half-closed (local)" state could receive any type of frame. The peer might have sent or enqueued for sending these frames before processing the RST\_STREAM frame. An endpoint MUST minimally process and then discard any frames it receives in this state. This means updating header compression state for HEADERS and PUSH\_PROMISE frames. Receiving a PUSH\_PROMISE frame also causes the promised stream to become "reserved (remote)", even when the PUSH\_PROMISE frame is received on a closed stream. Additionally, the content of DATA frames counts toward the connection flow-control window. An endpoint can perform this minimal processing for all streams that are in the "closed" state. Endpoints MAY use other signals to detect that a peer has received the frames that caused the stream to enter the "closed" state and treat receipt of any frame other than PRIORITY as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. Endpoints can use frames that indicate that the peer has received the closing signal to drive this. Endpoints SHOULD NOT use timers for this purpose. For example, an endpoint that sends a SETTINGS frame after closing a stream can safely treat receipt of a DATA frame on that stream as an error after receiving an acknowledgment of the settings. Other things that might be used are PING frames, receiving data on streams that were created after closing the stream, or responses to requests created after closing the stream. In the absence of more specific rules, implementations SHOULD treat the receipt of a frame that is not expressly permitted in the description of a state as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. Note that PRIORITY can be sent and received in any stream state. The rules in this section only apply to frames defined in this document. Receipt of frames for which the semantics are unknown cannot be treated as an error, as the conditions for sending and receiving those frames are also unknown; see [Section 5.5](#section-5.5). An example of the state transitions for an HTTP request/response exchange can be found in [Section 8.8](#section-8.8). An example of the state transitions for server push can be found in Sections [8.4.1](#section-8.4.1) and [8.4.2](#section-8.4.2). #### 5.1.1. Stream Identifiers Streams are identified by an unsigned 31-bit integer. Streams initiated by a client MUST use odd-numbered stream identifiers; those initiated by the server MUST use even-numbered stream identifiers. A stream identifier of zero (0x00) is used for connection control messages; the stream identifier of zero cannot be used to establish a new stream. The identifier of a newly established stream MUST be numerically greater than all streams that the initiating endpoint has opened or reserved. This governs streams that are opened using a HEADERS frame and streams that are reserved using PUSH\_PROMISE. An endpoint that receives an unexpected stream identifier MUST respond with a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. A HEADERS frame will transition the client-initiated stream identified by the stream identifier in the frame header from "idle" to "open". A PUSH\_PROMISE frame will transition the server-initiated stream identified by the Promised Stream ID field in the frame payload from "idle" to "reserved (local)" or "reserved (remote)". When a stream transitions out of the "idle" state, all streams in the "idle" state that might have been opened by the peer with a lower- valued stream identifier immediately transition to "closed". That is, an endpoint may skip a stream identifier, with the effect being that the skipped stream is immediately closed. Stream identifiers cannot be reused. Long-lived connections can result in an endpoint exhausting the available range of stream identifiers. A client that is unable to establish a new stream identifier can establish a new connection for new streams. A server that is unable to establish a new stream identifier can send a GOAWAY frame so that the client is forced to open a new connection for new streams. #### 5.1.2. Stream Concurrency A peer can limit the number of concurrently active streams using the SETTINGS\_MAX\_CONCURRENT\_STREAMS parameter (see [Section 6.5.2](#section-6.5.2)) within a SETTINGS frame. The maximum concurrent streams setting is specific to each endpoint and applies only to the peer that receives the setting. That is, clients specify the maximum number of concurrent streams the server can initiate, and servers specify the maximum number of concurrent streams the client can initiate. Streams that are in the "open" state or in either of the "half- closed" states count toward the maximum number of streams that an endpoint is permitted to open. Streams in any of these three states count toward the limit advertised in the SETTINGS\_MAX\_CONCURRENT\_STREAMS setting. Streams in either of the "reserved" states do not count toward the stream limit. Endpoints MUST NOT exceed the limit set by their peer. An endpoint that receives a HEADERS frame that causes its advertised concurrent stream limit to be exceeded MUST treat this as a stream error ([Section 5.4.2](#section-5.4.2)) of type PROTOCOL\_ERROR or REFUSED\_STREAM. The choice of error code determines whether the endpoint wishes to enable automatic retry (see [Section 8.7](#section-8.7) for details). An endpoint that wishes to reduce the value of SETTINGS\_MAX\_CONCURRENT\_STREAMS to a value that is below the current number of open streams can either close streams that exceed the new value or allow streams to complete. ### 5.2. Flow Control Using streams for multiplexing introduces contention over use of the TCP connection, resulting in blocked streams. A flow-control scheme ensures that streams on the same connection do not destructively interfere with each other. Flow control is used for both individual streams and the connection as a whole. HTTP/2 provides for flow control through use of the WINDOW\_UPDATE frame ([Section 6.9](#section-6.9)). #### 5.2.1. Flow-Control Principles HTTP/2 stream flow control aims to allow a variety of flow-control algorithms to be used without requiring protocol changes. Flow control in HTTP/2 has the following characteristics: 1. Flow control is specific to a connection. HTTP/2 flow control operates between the endpoints of a single hop and not over the entire end-to-end path. 2. Flow control is based on WINDOW\_UPDATE frames. Receivers advertise how many octets they are prepared to receive on a stream and for the entire connection. This is a credit-based scheme. 3. Flow control is directional with overall control provided by the receiver. A receiver MAY choose to set any window size that it desires for each stream and for the entire connection. A sender MUST respect flow-control limits imposed by a receiver. Clients, servers, and intermediaries all independently advertise their flow-control window as a receiver and abide by the flow-control limits set by their peer when sending. 4. The initial value for the flow-control window is 65,535 octets for both new streams and the overall connection. 5. The frame type determines whether flow control applies to a frame. Of the frames specified in this document, only DATA frames are subject to flow control; all other frame types do not consume space in the advertised flow-control window. This ensures that important control frames are not blocked by flow control. 6. An endpoint can choose to disable its own flow control, but an endpoint cannot ignore flow-control signals from its peer. 7. HTTP/2 defines only the format and semantics of the WINDOW\_UPDATE frame ([Section 6.9](#section-6.9)). This document does not stipulate how a receiver decides when to send this frame or the value that it sends, nor does it specify how a sender chooses to send packets. Implementations are able to select any algorithm that suits their needs. Implementations are also responsible for prioritizing the sending of requests and responses, choosing how to avoid head-of-line blocking for requests, and managing the creation of new streams. Algorithm choices for these could interact with any flow-control algorithm. #### 5.2.2. Appropriate Use of Flow Control Flow control is defined to protect endpoints that are operating under resource constraints. For example, a proxy needs to share memory between many connections and also might have a slow upstream connection and a fast downstream one. Flow control addresses cases where the receiver is unable to process data on one stream yet wants to continue to process other streams in the same connection. Deployments that do not require this capability can advertise a flow- control window of the maximum size (2^31-1) and can maintain this window by sending a WINDOW\_UPDATE frame when any data is received. This effectively disables flow control for that receiver. Conversely, a sender is always subject to the flow-control window advertised by the receiver. Deployments with constrained resources (for example, memory) can employ flow control to limit the amount of memory a peer can consume. Note, however, that this can lead to suboptimal use of available network resources if flow control is enabled without knowledge of the bandwidth \* delay product (see [[RFC7323](https://datatracker.ietf.org/doc/html/rfc7323)]). Even with full awareness of the current bandwidth \* delay product, implementation of flow control can be difficult. Endpoints MUST read and process HTTP/2 frames from the TCP receive buffer as soon as data is available. Failure to read promptly could lead to a deadlock when critical frames, such as WINDOW\_UPDATE, are not read and acted upon. Reading frames promptly does not expose endpoints to resource exhaustion attacks, as HTTP/2 flow control limits resource commitments. #### 5.2.3. Flow-Control Performance If an endpoint cannot ensure that its peer always has available flow- control window space that is greater than the peer's bandwidth \* delay product on this connection, its receive throughput will be limited by HTTP/2 flow control. This will result in degraded performance. Sending timely WINDOW\_UPDATE frames can improve performance. Endpoints will want to balance the need to improve receive throughput with the need to manage resource exhaustion risks and should take careful note of [Section 10.5](#section-10.5) in defining their strategy to manage window sizes. ### 5.3. Prioritization In a multiplexed protocol like HTTP/2, prioritizing allocation of bandwidth and computation resources to streams can be critical to attaining good performance. A poor prioritization scheme can result in HTTP/2 providing poor performance. With no parallelism at the TCP layer, performance could be significantly worse than HTTP/1.1. A good prioritization scheme benefits from the application of contextual knowledge such as the content of resources, how resources are interrelated, and how those resources will be used by a peer. In particular, clients can possess knowledge about the priority of requests that is relevant to server prioritization. In those cases, having clients provide priority information can improve performance. #### 5.3.1. Background on Priority in [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) defined a rich system for signaling priority of requests. However, this system proved to be complex, and it was not uniformly implemented. The flexible scheme meant that it was possible for clients to express priorities in very different ways, with little consistency in the approaches that were adopted. For servers, implementing generic support for the scheme was complex. Implementation of priorities was uneven in both clients and servers. Many server deployments ignored client signals when prioritizing their handling of requests. In short, the prioritization signaling in [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) [[RFC7540](https://datatracker.ietf.org/doc/html/rfc7540)] was not successful. #### 5.3.2. Priority Signaling in This Document This update to HTTP/2 deprecates the priority signaling defined in [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) [[RFC7540](https://datatracker.ietf.org/doc/html/rfc7540)]. The bulk of the text related to priority signals is not included in this document. The description of frame fields and some of the mandatory handling is retained to ensure that implementations of this document remain interoperable with implementations that use the priority signaling described in [RFC](https://datatracker.ietf.org/doc/html/rfc7540) [7540](https://datatracker.ietf.org/doc/html/rfc7540). A thorough description of the [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) priority scheme remains in [Section 5.3 of [RFC7540]](https://datatracker.ietf.org/doc/html/rfc7540#section-5.3). Signaling priority information is necessary to attain good performance in many cases. Where signaling priority information is important, endpoints are encouraged to use an alternative scheme, such as the scheme described in [[HTTP-PRIORITY](#ref-HTTP-PRIORITY)]. Though the priority signaling from [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) was not widely adopted, the information it provides can still be useful in the absence of better information. Endpoints that receive priority signals in HEADERS or PRIORITY frames can benefit from applying that information. In particular, implementations that consume these signals would not benefit from discarding these priority signals in the absence of alternatives. Servers SHOULD use other contextual information in determining priority of requests in the absence of any priority signals. Servers MAY interpret the complete absence of signals as an indication that the client has not implemented the feature. The defaults described in [Section 5.3.5 of [RFC7540]](https://datatracker.ietf.org/doc/html/rfc7540#section-5.3.5) are known to have poor performance under most conditions, and their use is unlikely to be deliberate. ### 5.4. Error Handling HTTP/2 framing permits two classes of errors: \* An error condition that renders the entire connection unusable is a connection error. \* An error in an individual stream is a stream error. A list of error codes is included in [Section 7](#section-7). It is possible that an endpoint will encounter frames that would cause multiple errors. Implementations MAY discover multiple errors during processing, but they SHOULD report at most one stream and one connection error as a result. The first stream error reported for a given stream prevents any other errors on that stream from being reported. In comparison, the protocol permits multiple GOAWAY frames, though an endpoint SHOULD report just one type of connection error unless an error is encountered during graceful shutdown. If this occurs, an endpoint MAY send an additional GOAWAY frame with the new error code, in addition to any prior GOAWAY that contained NO\_ERROR. If an endpoint detects multiple different errors, it MAY choose to report any one of those errors. If a frame causes a connection error, that error MUST be reported. Additionally, an endpoint MAY use any applicable error code when it detects an error condition; a generic error code (such as PROTOCOL\_ERROR or INTERNAL\_ERROR) can always be used in place of more specific error codes. #### 5.4.1. Connection Error Handling A connection error is any error that prevents further processing of the frame layer or corrupts any connection state. An endpoint that encounters a connection error SHOULD first send a GOAWAY frame ([Section 6.8](#section-6.8)) with the stream identifier of the last stream that it successfully received from its peer. The GOAWAY frame includes an error code ([Section 7](#section-7)) that indicates why the connection is terminating. After sending the GOAWAY frame for an error condition, the endpoint MUST close the TCP connection. It is possible that the GOAWAY will not be reliably received by the receiving endpoint. In the event of a connection error, GOAWAY only provides a best-effort attempt to communicate with the peer about why the connection is being terminated. An endpoint can end a connection at any time. In particular, an endpoint MAY choose to treat a stream error as a connection error. Endpoints SHOULD send a GOAWAY frame when ending a connection, providing that circumstances permit it. #### 5.4.2. Stream Error Handling A stream error is an error related to a specific stream that does not affect processing of other streams. An endpoint that detects a stream error sends a RST\_STREAM frame ([Section 6.4](#section-6.4)) that contains the stream identifier of the stream where the error occurred. The RST\_STREAM frame includes an error code that indicates the type of error. A RST\_STREAM is the last frame that an endpoint can send on a stream. The peer that sends the RST\_STREAM frame MUST be prepared to receive any frames that were sent or enqueued for sending by the remote peer. These frames can be ignored, except where they modify connection state (such as the state maintained for field section compression ([Section 4.3](#section-4.3)) or flow control). Normally, an endpoint SHOULD NOT send more than one RST\_STREAM frame for any stream. However, an endpoint MAY send additional RST\_STREAM frames if it receives frames on a closed stream after more than a round-trip time. This behavior is permitted to deal with misbehaving implementations. To avoid looping, an endpoint MUST NOT send a RST\_STREAM in response to a RST\_STREAM frame. #### 5.4.3. Connection Termination If the TCP connection is closed or reset while streams remain in the "open" or "half-closed" states, then the affected streams cannot be automatically retried (see [Section 8.7](#section-8.7) for details). ### 5.5. Extending HTTP/2 HTTP/2 permits extension of the protocol. Within the limitations described in this section, protocol extensions can be used to provide additional services or alter any aspect of the protocol. Extensions are effective only within the scope of a single HTTP/2 connection. This applies to the protocol elements defined in this document. This does not affect the existing options for extending HTTP, such as defining new methods, status codes, or fields (see Section 16 of [[HTTP](#ref-HTTP)]). Extensions are permitted to use new frame types ([Section 4.1](#section-4.1)), new settings ([Section 6.5](#section-6.5)), or new error codes ([Section 7](#section-7)). Registries for managing these extension points are defined in [Section 11 of [RFC7540]](https://datatracker.ietf.org/doc/html/rfc7540#section-11). Implementations MUST ignore unknown or unsupported values in all extensible protocol elements. Implementations MUST discard frames that have unknown or unsupported types. This means that any of these extension points can be safely used by extensions without prior arrangement or negotiation. However, extension frames that appear in the middle of a field block ([Section 4.3](#section-4.3)) are not permitted; these MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. Extensions SHOULD avoid changing protocol elements defined in this document or elements for which no extension mechanism is defined. This includes changes to the layout of frames, additions or changes to the way that frames are composed into HTTP messages ([Section 8.1](#section-8.1)), the definition of pseudo-header fields, or changes to any protocol element that a compliant endpoint might treat as a connection error ([Section 5.4.1](#section-5.4.1)). An extension that changes existing protocol elements or state MUST be negotiated before being used. For example, an extension that changes the layout of the HEADERS frame cannot be used until the peer has given a positive signal that this is acceptable. In this case, it could also be necessary to coordinate when the revised layout comes into effect. For example, treating frames other than DATA frames as flow controlled requires a change in semantics that both endpoints need to understand, so this can only be done through negotiation. This document doesn't mandate a specific method for negotiating the use of an extension but notes that a setting ([Section 6.5.2](#section-6.5.2)) could be used for that purpose. If both peers set a value that indicates willingness to use the extension, then the extension can be used. If a setting is used for extension negotiation, the initial value MUST be defined in such a fashion that the extension is initially disabled. 6. Frame Definitions -------------------- This specification defines a number of frame types, each identified by a unique 8-bit type code. Each frame type serves a distinct purpose in the establishment and management of either the connection as a whole or individual streams. The transmission of specific frame types can alter the state of a connection. If endpoints fail to maintain a synchronized view of the connection state, successful communication within the connection will no longer be possible. Therefore, it is important that endpoints have a shared comprehension of how the state is affected by the use of any given frame. ### 6.1. DATA DATA frames (type=0x00) convey arbitrary, variable-length sequences of octets associated with a stream. One or more DATA frames are used, for instance, to carry HTTP request or response message contents. DATA frames MAY also contain padding. Padding can be added to DATA frames to obscure the size of messages. Padding is a security feature; see [Section 10.7](#section-10.7). DATA Frame { Length (24), Type (8) = 0x00, Unused Flags (4), PADDED Flag (1), Unused Flags (2), END\_STREAM Flag (1), Reserved (1), Stream Identifier (31), [Pad Length (8)], Data (..), Padding (..2040), } Figure 3: DATA Frame Format The Length, Type, Unused Flag(s), Reserved, and Stream Identifier fields are described in [Section 4](#section-4). The DATA frame contains the following additional fields: Pad Length: An 8-bit field containing the length of the frame padding in units of octets. This field is conditional and is only present if the PADDED flag is set. Data: Application data. The amount of data is the remainder of the frame payload after subtracting the length of the other fields that are present. Padding: Padding octets that contain no application semantic value. Padding octets MUST be set to zero when sending. A receiver is not obligated to verify padding but MAY treat non-zero padding as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. The DATA frame defines the following flags: PADDED (0x08): When set, the PADDED flag indicates that the Pad Length field and any padding that it describes are present. END\_STREAM (0x01): When set, the END\_STREAM flag indicates that this frame is the last that the endpoint will send for the identified stream. Setting this flag causes the stream to enter one of the "half-closed" states or the "closed" state ([Section 5.1](#section-5.1)). | Note: An endpoint that learns of stream closure after sending | all data can close a stream by sending a STREAM frame with a | zero-length Data field and the END\_STREAM flag set. This is | only possible if the endpoint does not send trailers, as the | END\_STREAM flag appears on a HEADERS frame in that case; see | [Section 8.1](#section-8.1). DATA frames MUST be associated with a stream. If a DATA frame is received whose Stream Identifier field is 0x00, the recipient MUST respond with a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. DATA frames are subject to flow control and can only be sent when a stream is in the "open" or "half-closed (remote)" state. The entire DATA frame payload is included in flow control, including the Pad Length and Padding fields if present. If a DATA frame is received whose stream is not in the "open" or "half-closed (local)" state, the recipient MUST respond with a stream error ([Section 5.4.2](#section-5.4.2)) of type STREAM\_CLOSED. The total number of padding octets is determined by the value of the Pad Length field. If the length of the padding is the length of the frame payload or greater, the recipient MUST treat this as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. | Note: A frame can be increased in size by one octet by | including a Pad Length field with a value of zero. ### 6.2. HEADERS The HEADERS frame (type=0x01) is used to open a stream ([Section 5.1](#section-5.1)), and additionally carries a field block fragment. Despite the name, a HEADERS frame can carry a header section or a trailer section. HEADERS frames can be sent on a stream in the "idle", "reserved (local)", "open", or "half-closed (remote)" state. HEADERS Frame { Length (24), Type (8) = 0x01, Unused Flags (2), PRIORITY Flag (1), Unused Flag (1), PADDED Flag (1), END\_HEADERS Flag (1), Unused Flag (1), END\_STREAM Flag (1), Reserved (1), Stream Identifier (31), [Pad Length (8)], [Exclusive (1)], [Stream Dependency (31)], [Weight (8)], Field Block Fragment (..), Padding (..2040), } Figure 4: HEADERS Frame Format The Length, Type, Unused Flag(s), Reserved, and Stream Identifier fields are described in [Section 4](#section-4). The HEADERS frame payload has the following additional fields: Pad Length: An 8-bit field containing the length of the frame padding in units of octets. This field is only present if the PADDED flag is set. Exclusive: A single-bit flag. This field is only present if the PRIORITY flag is set. Priority signals in HEADERS frames are deprecated; see [Section 5.3.2](#section-5.3.2). Stream Dependency: A 31-bit stream identifier. This field is only present if the PRIORITY flag is set. Weight: An unsigned 8-bit integer. This field is only present if the PRIORITY flag is set. Field Block Fragment: A field block fragment ([Section 4.3](#section-4.3)). Padding: Padding octets that contain no application semantic value. Padding octets MUST be set to zero when sending. A receiver is not obligated to verify padding but MAY treat non-zero padding as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. The HEADERS frame defines the following flags: PRIORITY (0x20): When set, the PRIORITY flag indicates that the Exclusive, Stream Dependency, and Weight fields are present. PADDED (0x08): When set, the PADDED flag indicates that the Pad Length field and any padding that it describes are present. END\_HEADERS (0x04): When set, the END\_HEADERS flag indicates that this frame contains an entire field block ([Section 4.3](#section-4.3)) and is not followed by any CONTINUATION frames. A HEADERS frame without the END\_HEADERS flag set MUST be followed by a CONTINUATION frame for the same stream. A receiver MUST treat the receipt of any other type of frame or a frame on a different stream as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. END\_STREAM (0x01): When set, the END\_STREAM flag indicates that the field block ([Section 4.3](#section-4.3)) is the last that the endpoint will send for the identified stream. A HEADERS frame with the END\_STREAM flag set signals the end of a stream. However, a HEADERS frame with the END\_STREAM flag set can be followed by CONTINUATION frames on the same stream. Logically, the CONTINUATION frames are part of the HEADERS frame. The frame payload of a HEADERS frame contains a field block fragment ([Section 4.3](#section-4.3)). A field block that does not fit within a HEADERS frame is continued in a CONTINUATION frame ([Section 6.10](#section-6.10)). HEADERS frames MUST be associated with a stream. If a HEADERS frame is received whose Stream Identifier field is 0x00, the recipient MUST respond with a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. The HEADERS frame changes the connection state as described in [Section 4.3](#section-4.3). The total number of padding octets is determined by the value of the Pad Length field. If the length of the padding is the length of the frame payload or greater, the recipient MUST treat this as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. | Note: A frame can be increased in size by one octet by | including a Pad Length field with a value of zero. ### 6.3. PRIORITY The PRIORITY frame (type=0x02) is deprecated; see [Section 5.3.2](#section-5.3.2). A PRIORITY frame can be sent in any stream state, including idle or closed streams. PRIORITY Frame { Length (24) = 0x05, Type (8) = 0x02, Unused Flags (8), Reserved (1), Stream Identifier (31), Exclusive (1), Stream Dependency (31), Weight (8), } Figure 5: PRIORITY Frame Format The Length, Type, Unused Flag(s), Reserved, and Stream Identifier fields are described in [Section 4](#section-4). The frame payload of a PRIORITY frame contains the following additional fields: Exclusive: A single-bit flag. Stream Dependency: A 31-bit stream identifier. Weight: An unsigned 8-bit integer. The PRIORITY frame does not define any flags. The PRIORITY frame always identifies a stream. If a PRIORITY frame is received with a stream identifier of 0x00, the recipient MUST respond with a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. Sending or receiving a PRIORITY frame does not affect the state of any stream ([Section 5.1](#section-5.1)). The PRIORITY frame can be sent on a stream in any state, including "idle" or "closed". A PRIORITY frame cannot be sent between consecutive frames that comprise a single field block ([Section 4.3](#section-4.3)). A PRIORITY frame with a length other than 5 octets MUST be treated as a stream error ([Section 5.4.2](#section-5.4.2)) of type FRAME\_SIZE\_ERROR. ### 6.4. RST\_STREAM The RST\_STREAM frame (type=0x03) allows for immediate termination of a stream. RST\_STREAM is sent to request cancellation of a stream or to indicate that an error condition has occurred. RST\_STREAM Frame { Length (24) = 0x04, Type (8) = 0x03, Unused Flags (8), Reserved (1), Stream Identifier (31), Error Code (32), } Figure 6: RST\_STREAM Frame Format The Length, Type, Unused Flag(s), Reserved, and Stream Identifier fields are described in [Section 4](#section-4). Additionally, the RST\_STREAM frame contains a single unsigned, 32-bit integer identifying the error code ([Section 7](#section-7)). The error code indicates why the stream is being terminated. The RST\_STREAM frame does not define any flags. The RST\_STREAM frame fully terminates the referenced stream and causes it to enter the "closed" state. After receiving a RST\_STREAM on a stream, the receiver MUST NOT send additional frames for that stream, except for PRIORITY. However, after sending the RST\_STREAM, the sending endpoint MUST be prepared to receive and process additional frames sent on the stream that might have been sent by the peer prior to the arrival of the RST\_STREAM. RST\_STREAM frames MUST be associated with a stream. If a RST\_STREAM frame is received with a stream identifier of 0x00, the recipient MUST treat this as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. RST\_STREAM frames MUST NOT be sent for a stream in the "idle" state. If a RST\_STREAM frame identifying an idle stream is received, the recipient MUST treat this as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. A RST\_STREAM frame with a length other than 4 octets MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type FRAME\_SIZE\_ERROR. ### 6.5. SETTINGS The SETTINGS frame (type=0x04) conveys configuration parameters that affect how endpoints communicate, such as preferences and constraints on peer behavior. The SETTINGS frame is also used to acknowledge the receipt of those settings. Individually, a configuration parameter from a SETTINGS frame is referred to as a "setting". Settings are not negotiated; they describe characteristics of the sending peer, which are used by the receiving peer. Different values for the same setting can be advertised by each peer. For example, a client might set a high initial flow-control window, whereas a server might set a lower value to conserve resources. A SETTINGS frame MUST be sent by both endpoints at the start of a connection and MAY be sent at any other time by either endpoint over the lifetime of the connection. Implementations MUST support all of the settings defined by this specification. Each parameter in a SETTINGS frame replaces any existing value for that parameter. Settings are processed in the order in which they appear, and a receiver of a SETTINGS frame does not need to maintain any state other than the current value of each setting. Therefore, the value of a SETTINGS parameter is the last value that is seen by a receiver. SETTINGS frames are acknowledged by the receiving peer. To enable this, the SETTINGS frame defines the ACK flag: ACK (0x01): When set, the ACK flag indicates that this frame acknowledges receipt and application of the peer's SETTINGS frame. When this bit is set, the frame payload of the SETTINGS frame MUST be empty. Receipt of a SETTINGS frame with the ACK flag set and a length field value other than 0 MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type FRAME\_SIZE\_ERROR. For more information, see [Section 6.5.3](#section-6.5.3) ("Settings Synchronization"). SETTINGS frames always apply to a connection, never a single stream. The stream identifier for a SETTINGS frame MUST be zero (0x00). If an endpoint receives a SETTINGS frame whose Stream Identifier field is anything other than 0x00, the endpoint MUST respond with a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. The SETTINGS frame affects connection state. A badly formed or incomplete SETTINGS frame MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. A SETTINGS frame with a length other than a multiple of 6 octets MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type FRAME\_SIZE\_ERROR. #### 6.5.1. SETTINGS Format The frame payload of a SETTINGS frame consists of zero or more settings, each consisting of an unsigned 16-bit setting identifier and an unsigned 32-bit value. SETTINGS Frame { Length (24), Type (8) = 0x04, Unused Flags (7), ACK Flag (1), Reserved (1), Stream Identifier (31) = 0, Setting (48) ..., } Setting { Identifier (16), Value (32), } Figure 7: SETTINGS Frame Format The Length, Type, Unused Flag(s), Reserved, and Stream Identifier fields are described in [Section 4](#section-4). The frame payload of a SETTINGS frame contains any number of Setting fields, each of which consists of: Identifier: A 16-bit setting identifier; see [Section 6.5.2](#section-6.5.2). Value: A 32-bit value for the setting. #### 6.5.2. Defined Settings The following settings are defined: SETTINGS\_HEADER\_TABLE\_SIZE (0x01): This setting allows the sender to inform the remote endpoint of the maximum size of the compression table used to decode field blocks, in units of octets. The encoder can select any size equal to or less than this value by using signaling specific to the compression format inside a field block (see [[COMPRESSION](#ref-COMPRESSION)]). The initial value is 4,096 octets. SETTINGS\_ENABLE\_PUSH (0x02): This setting can be used to enable or disable server push. A server MUST NOT send a PUSH\_PROMISE frame if it receives this parameter set to a value of 0; see [Section 8.4](#section-8.4). A client that has both set this parameter to 0 and had it acknowledged MUST treat the receipt of a PUSH\_PROMISE frame as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. The initial value of SETTINGS\_ENABLE\_PUSH is 1. For a client, this value indicates that it is willing to receive PUSH\_PROMISE frames. For a server, this initial value has no effect, and is equivalent to the value 0. Any value other than 0 or 1 MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. A server MUST NOT explicitly set this value to 1. A server MAY choose to omit this setting when it sends a SETTINGS frame, but if a server does include a value, it MUST be 0. A client MUST treat receipt of a SETTINGS frame with SETTINGS\_ENABLE\_PUSH set to 1 as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. SETTINGS\_MAX\_CONCURRENT\_STREAMS (0x03): This setting indicates the maximum number of concurrent streams that the sender will allow. This limit is directional: it applies to the number of streams that the sender permits the receiver to create. Initially, there is no limit to this value. It is recommended that this value be no smaller than 100, so as to not unnecessarily limit parallelism. A value of 0 for SETTINGS\_MAX\_CONCURRENT\_STREAMS SHOULD NOT be treated as special by endpoints. A zero value does prevent the creation of new streams; however, this can also happen for any limit that is exhausted with active streams. Servers SHOULD only set a zero value for short durations; if a server does not wish to accept requests, closing the connection is more appropriate. SETTINGS\_INITIAL\_WINDOW\_SIZE (0x04): This setting indicates the sender's initial window size (in units of octets) for stream-level flow control. The initial value is 2^16-1 (65,535) octets. This setting affects the window size of all streams (see [Section 6.9.2](#section-6.9.2)). Values above the maximum flow-control window size of 2^31-1 MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type FLOW\_CONTROL\_ERROR. SETTINGS\_MAX\_FRAME\_SIZE (0x05): This setting indicates the size of the largest frame payload that the sender is willing to receive, in units of octets. The initial value is 2^14 (16,384) octets. The value advertised by an endpoint MUST be between this initial value and the maximum allowed frame size (2^24-1 or 16,777,215 octets), inclusive. Values outside this range MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. SETTINGS\_MAX\_HEADER\_LIST\_SIZE (0x06): This advisory setting informs a peer of the maximum field section size that the sender is prepared to accept, in units of octets. The value is based on the uncompressed size of field lines, including the length of the name and value in units of octets plus an overhead of 32 octets for each field line. For any given request, a lower limit than what is advertised MAY be enforced. The initial value of this setting is unlimited. An endpoint that receives a SETTINGS frame with any unknown or unsupported identifier MUST ignore that setting. #### 6.5.3. Settings Synchronization Most values in SETTINGS benefit from or require an understanding of when the peer has received and applied the changed parameter values. In order to provide such synchronization timepoints, the recipient of a SETTINGS frame in which the ACK flag is not set MUST apply the updated settings as soon as possible upon receipt. SETTINGS frames are acknowledged in the order in which they are received. The values in the SETTINGS frame MUST be processed in the order they appear, with no other frame processing between values. Unsupported settings MUST be ignored. Once all values have been processed, the recipient MUST immediately emit a SETTINGS frame with the ACK flag set. Upon receiving a SETTINGS frame with the ACK flag set, the sender of the altered settings can rely on the values from the oldest unacknowledged SETTINGS frame having been applied. If the sender of a SETTINGS frame does not receive an acknowledgment within a reasonable amount of time, it MAY issue a connection error ([Section 5.4.1](#section-5.4.1)) of type SETTINGS\_TIMEOUT. In setting a timeout, some allowance needs to be made for processing delays at the peer; a timeout that is solely based on the round-trip time between endpoints might result in spurious errors. ### 6.6. PUSH\_PROMISE The PUSH\_PROMISE frame (type=0x05) is used to notify the peer endpoint in advance of streams the sender intends to initiate. The PUSH\_PROMISE frame includes the unsigned 31-bit identifier of the stream the endpoint plans to create along with a field section that provides additional context for the stream. [Section 8.4](#section-8.4) contains a thorough description of the use of PUSH\_PROMISE frames. PUSH\_PROMISE Frame { Length (24), Type (8) = 0x05, Unused Flags (4), PADDED Flag (1), END\_HEADERS Flag (1), Unused Flags (2), Reserved (1), Stream Identifier (31), [Pad Length (8)], Reserved (1), Promised Stream ID (31), Field Block Fragment (..), Padding (..2040), } Figure 8: PUSH\_PROMISE Frame Format The Length, Type, Unused Flag(s), Reserved, and Stream Identifier fields are described in [Section 4](#section-4). The PUSH\_PROMISE frame payload has the following additional fields: Pad Length: An 8-bit field containing the length of the frame padding in units of octets. This field is only present if the PADDED flag is set. Promised Stream ID: An unsigned 31-bit integer that identifies the stream that is reserved by the PUSH\_PROMISE. The promised stream identifier MUST be a valid choice for the next stream sent by the sender (see "new stream identifier" in [Section 5.1.1](#section-5.1.1)). Field Block Fragment: A field block fragment ([Section 4.3](#section-4.3)) containing the request control data and a header section. Padding: Padding octets that contain no application semantic value. Padding octets MUST be set to zero when sending. A receiver is not obligated to verify padding but MAY treat non-zero padding as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. The PUSH\_PROMISE frame defines the following flags: PADDED (0x08): When set, the PADDED flag indicates that the Pad Length field and any padding that it describes are present. END\_HEADERS (0x04): When set, the END\_HEADERS flag indicates that this frame contains an entire field block ([Section 4.3](#section-4.3)) and is not followed by any CONTINUATION frames. A PUSH\_PROMISE frame without the END\_HEADERS flag set MUST be followed by a CONTINUATION frame for the same stream. A receiver MUST treat the receipt of any other type of frame or a frame on a different stream as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. PUSH\_PROMISE frames MUST only be sent on a peer-initiated stream that is in either the "open" or "half-closed (remote)" state. The stream identifier of a PUSH\_PROMISE frame indicates the stream it is associated with. If the Stream Identifier field specifies the value 0x00, a recipient MUST respond with a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. Promised streams are not required to be used in the order they are promised. The PUSH\_PROMISE only reserves stream identifiers for later use. PUSH\_PROMISE MUST NOT be sent if the SETTINGS\_ENABLE\_PUSH setting of the peer endpoint is set to 0. An endpoint that has set this setting and has received acknowledgment MUST treat the receipt of a PUSH\_PROMISE frame as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. Recipients of PUSH\_PROMISE frames can choose to reject promised streams by returning a RST\_STREAM referencing the promised stream identifier back to the sender of the PUSH\_PROMISE. A PUSH\_PROMISE frame modifies the connection state in two ways. First, the inclusion of a field block ([Section 4.3](#section-4.3)) potentially modifies the state maintained for field section compression. Second, PUSH\_PROMISE also reserves a stream for later use, causing the promised stream to enter the "reserved (local)" or "reserved (remote)" state. A sender MUST NOT send a PUSH\_PROMISE on a stream unless that stream is either "open" or "half-closed (remote)"; the sender MUST ensure that the promised stream is a valid choice for a new stream identifier ([Section 5.1.1](#section-5.1.1)) (that is, the promised stream MUST be in the "idle" state). Since PUSH\_PROMISE reserves a stream, ignoring a PUSH\_PROMISE frame causes the stream state to become indeterminate. A receiver MUST treat the receipt of a PUSH\_PROMISE on a stream that is neither "open" nor "half-closed (local)" as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. However, an endpoint that has sent RST\_STREAM on the associated stream MUST handle PUSH\_PROMISE frames that might have been created before the RST\_STREAM frame is received and processed. A receiver MUST treat the receipt of a PUSH\_PROMISE that promises an illegal stream identifier ([Section 5.1.1](#section-5.1.1)) as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. Note that an illegal stream identifier is an identifier for a stream that is not currently in the "idle" state. The total number of padding octets is determined by the value of the Pad Length field. If the length of the padding is the length of the frame payload or greater, the recipient MUST treat this as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. | Note: A frame can be increased in size by one octet by | including a Pad Length field with a value of zero. ### 6.7. PING The PING frame (type=0x06) is a mechanism for measuring a minimal round-trip time from the sender, as well as determining whether an idle connection is still functional. PING frames can be sent from any endpoint. PING Frame { Length (24) = 0x08, Type (8) = 0x06, Unused Flags (7), ACK Flag (1), Reserved (1), Stream Identifier (31) = 0, Opaque Data (64), } Figure 9: PING Frame Format The Length, Type, Unused Flag(s), Reserved, and Stream Identifier fields are described in [Section 4](#section-4). In addition to the frame header, PING frames MUST contain 8 octets of opaque data in the frame payload. A sender can include any value it chooses and use those octets in any fashion. Receivers of a PING frame that does not include an ACK flag MUST send a PING frame with the ACK flag set in response, with an identical frame payload. PING responses SHOULD be given higher priority than any other frame. The PING frame defines the following flags: ACK (0x01): When set, the ACK flag indicates that this PING frame is a PING response. An endpoint MUST set this flag in PING responses. An endpoint MUST NOT respond to PING frames containing this flag. PING frames are not associated with any individual stream. If a PING frame is received with a Stream Identifier field value other than 0x00, the recipient MUST respond with a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. Receipt of a PING frame with a length field value other than 8 MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type FRAME\_SIZE\_ERROR. ### 6.8. GOAWAY The GOAWAY frame (type=0x07) is used to initiate shutdown of a connection or to signal serious error conditions. GOAWAY allows an endpoint to gracefully stop accepting new streams while still finishing processing of previously established streams. This enables administrative actions, like server maintenance. There is an inherent race condition between an endpoint starting new streams and the remote peer sending a GOAWAY frame. To deal with this case, the GOAWAY contains the stream identifier of the last peer-initiated stream that was or might be processed on the sending endpoint in this connection. For instance, if the server sends a GOAWAY frame, the identified stream is the highest-numbered stream initiated by the client. Once the GOAWAY is sent, the sender will ignore frames sent on streams initiated by the receiver if the stream has an identifier higher than the included last stream identifier. Receivers of a GOAWAY frame MUST NOT open additional streams on the connection, although a new connection can be established for new streams. If the receiver of the GOAWAY has sent data on streams with a higher stream identifier than what is indicated in the GOAWAY frame, those streams are not or will not be processed. The receiver of the GOAWAY frame can treat the streams as though they had never been created at all, thereby allowing those streams to be retried later on a new connection. Endpoints SHOULD always send a GOAWAY frame before closing a connection so that the remote peer can know whether a stream has been partially processed or not. For example, if an HTTP client sends a POST at the same time that a server closes a connection, the client cannot know if the server started to process that POST request if the server does not send a GOAWAY frame to indicate what streams it might have acted on. An endpoint might choose to close a connection without sending a GOAWAY for misbehaving peers. A GOAWAY frame might not immediately precede closing of the connection; a receiver of a GOAWAY that has no more use for the connection SHOULD still send a GOAWAY frame before terminating the connection. GOAWAY Frame { Length (24), Type (8) = 0x07, Unused Flags (8), Reserved (1), Stream Identifier (31) = 0, Reserved (1), Last-Stream-ID (31), Error Code (32), Additional Debug Data (..), } Figure 10: GOAWAY Frame Format The Length, Type, Unused Flag(s), Reserved, and Stream Identifier fields are described in [Section 4](#section-4). The GOAWAY frame does not define any flags. The GOAWAY frame applies to the connection, not a specific stream. An endpoint MUST treat a GOAWAY frame with a stream identifier other than 0x00 as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. The last stream identifier in the GOAWAY frame contains the highest- numbered stream identifier for which the sender of the GOAWAY frame might have taken some action on or might yet take action on. All streams up to and including the identified stream might have been processed in some way. The last stream identifier can be set to 0 if no streams were processed. | Note: In this context, "processed" means that some data from | the stream was passed to some higher layer of software that | might have taken some action as a result. If a connection terminates without a GOAWAY frame, the last stream identifier is effectively the highest possible stream identifier. On streams with lower- or equal-numbered identifiers that were not closed completely prior to the connection being closed, reattempting requests, transactions, or any protocol activity is not possible, except for idempotent actions like HTTP GET, PUT, or DELETE. Any protocol activity that uses higher-numbered streams can be safely retried using a new connection. Activity on streams numbered lower than or equal to the last stream identifier might still complete successfully. The sender of a GOAWAY frame might gracefully shut down a connection by sending a GOAWAY frame, maintaining the connection in an "open" state until all in- progress streams complete. An endpoint MAY send multiple GOAWAY frames if circumstances change. For instance, an endpoint that sends GOAWAY with NO\_ERROR during graceful shutdown could subsequently encounter a condition that requires immediate termination of the connection. The last stream identifier from the last GOAWAY frame received indicates which streams could have been acted upon. Endpoints MUST NOT increase the value they send in the last stream identifier, since the peers might already have retried unprocessed requests on another connection. A client that is unable to retry requests loses all requests that are in flight when the server closes the connection. This is especially true for intermediaries that might not be serving clients using HTTP/2. A server that is attempting to gracefully shut down a connection SHOULD send an initial GOAWAY frame with the last stream identifier set to 2^31-1 and a NO\_ERROR code. This signals to the client that a shutdown is imminent and that initiating further requests is prohibited. After allowing time for any in-flight stream creation (at least one round-trip time), the server MAY send another GOAWAY frame with an updated last stream identifier. This ensures that a connection can be cleanly shut down without losing requests. After sending a GOAWAY frame, the sender can discard frames for streams initiated by the receiver with identifiers higher than the identified last stream. However, any frames that alter connection state cannot be completely ignored. For instance, HEADERS, PUSH\_PROMISE, and CONTINUATION frames MUST be minimally processed to ensure that the state maintained for field section compression is consistent (see [Section 4.3](#section-4.3)); similarly, DATA frames MUST be counted toward the connection flow-control window. Failure to process these frames can cause flow control or field section compression state to become unsynchronized. The GOAWAY frame also contains a 32-bit error code ([Section 7](#section-7)) that contains the reason for closing the connection. Endpoints MAY append opaque data to the frame payload of any GOAWAY frame. Additional debug data is intended for diagnostic purposes only and carries no semantic value. Debug information could contain security- or privacy-sensitive data. Logged or otherwise persistently stored debug data MUST have adequate safeguards to prevent unauthorized access. ### 6.9. WINDOW\_UPDATE The WINDOW\_UPDATE frame (type=0x08) is used to implement flow control; see [Section 5.2](#section-5.2) for an overview. Flow control operates at two levels: on each individual stream and on the entire connection. Both types of flow control are hop by hop, that is, only between the two endpoints. Intermediaries do not forward WINDOW\_UPDATE frames between dependent connections. However, throttling of data transfer by any receiver can indirectly cause the propagation of flow-control information toward the original sender. Flow control only applies to frames that are identified as being subject to flow control. Of the frame types defined in this document, this includes only DATA frames. Frames that are exempt from flow control MUST be accepted and processed, unless the receiver is unable to assign resources to handling the frame. A receiver MAY respond with a stream error ([Section 5.4.2](#section-5.4.2)) or connection error ([Section 5.4.1](#section-5.4.1)) of type FLOW\_CONTROL\_ERROR if it is unable to accept a frame. WINDOW\_UPDATE Frame { Length (24) = 0x04, Type (8) = 0x08, Unused Flags (8), Reserved (1), Stream Identifier (31), Reserved (1), Window Size Increment (31), } Figure 11: WINDOW\_UPDATE Frame Format The Length, Type, Unused Flag(s), Reserved, and Stream Identifier fields are described in [Section 4](#section-4). The frame payload of a WINDOW\_UPDATE frame is one reserved bit plus an unsigned 31-bit integer indicating the number of octets that the sender can transmit in addition to the existing flow-control window. The legal range for the increment to the flow-control window is 1 to 2^31-1 (2,147,483,647) octets. The WINDOW\_UPDATE frame does not define any flags. The WINDOW\_UPDATE frame can be specific to a stream or to the entire connection. In the former case, the frame's stream identifier indicates the affected stream; in the latter, the value "0" indicates that the entire connection is the subject of the frame. A receiver MUST treat the receipt of a WINDOW\_UPDATE frame with a flow-control window increment of 0 as a stream error ([Section 5.4.2](#section-5.4.2)) of type PROTOCOL\_ERROR; errors on the connection flow-control window MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)). WINDOW\_UPDATE can be sent by a peer that has sent a frame with the END\_STREAM flag set. This means that a receiver could receive a WINDOW\_UPDATE frame on a stream in a "half-closed (remote)" or "closed" state. A receiver MUST NOT treat this as an error (see [Section 5.1](#section-5.1)). A receiver that receives a flow-controlled frame MUST always account for its contribution against the connection flow-control window, unless the receiver treats this as a connection error ([Section 5.4.1](#section-5.4.1)). This is necessary even if the frame is in error. The sender counts the frame toward the flow-control window, but if the receiver does not, the flow-control window at the sender and receiver can become different. A WINDOW\_UPDATE frame with a length other than 4 octets MUST be treated as a connection error ([Section 5.4.1](#section-5.4.1)) of type FRAME\_SIZE\_ERROR. #### 6.9.1. The Flow-Control Window Flow control in HTTP/2 is implemented using a window kept by each sender on every stream. The flow-control window is a simple integer value that indicates how many octets of data the sender is permitted to transmit; as such, its size is a measure of the buffering capacity of the receiver. Two flow-control windows are applicable: the stream flow-control window and the connection flow-control window. The sender MUST NOT send a flow-controlled frame with a length that exceeds the space available in either of the flow-control windows advertised by the receiver. Frames with zero length with the END\_STREAM flag set (that is, an empty DATA frame) MAY be sent if there is no available space in either flow-control window. For flow-control calculations, the 9-octet frame header is not counted. After sending a flow-controlled frame, the sender reduces the space available in both windows by the length of the transmitted frame. The receiver of a frame sends a WINDOW\_UPDATE frame as it consumes data and frees up space in flow-control windows. Separate WINDOW\_UPDATE frames are sent for the stream- and connection-level flow-control windows. Receivers are advised to have mechanisms in place to avoid sending WINDOW\_UPDATE frames with very small increments; see [Section 4.2.3.3 of [RFC1122]](https://datatracker.ietf.org/doc/html/rfc1122#section-4.2.3.3). A sender that receives a WINDOW\_UPDATE frame updates the corresponding window by the amount specified in the frame. A sender MUST NOT allow a flow-control window to exceed 2^31-1 octets. If a sender receives a WINDOW\_UPDATE that causes a flow- control window to exceed this maximum, it MUST terminate either the stream or the connection, as appropriate. For streams, the sender sends a RST\_STREAM with an error code of FLOW\_CONTROL\_ERROR; for the connection, a GOAWAY frame with an error code of FLOW\_CONTROL\_ERROR is sent. Flow-controlled frames from the sender and WINDOW\_UPDATE frames from the receiver are completely asynchronous with respect to each other. This property allows a receiver to aggressively update the window size kept by the sender to prevent streams from stalling. #### 6.9.2. Initial Flow-Control Window Size When an HTTP/2 connection is first established, new streams are created with an initial flow-control window size of 65,535 octets. The connection flow-control window is also 65,535 octets. Both endpoints can adjust the initial window size for new streams by including a value for SETTINGS\_INITIAL\_WINDOW\_SIZE in the SETTINGS frame. The connection flow-control window can only be changed using WINDOW\_UPDATE frames. Prior to receiving a SETTINGS frame that sets a value for SETTINGS\_INITIAL\_WINDOW\_SIZE, an endpoint can only use the default initial window size when sending flow-controlled frames. Similarly, the connection flow-control window is set based on the default initial window size until a WINDOW\_UPDATE frame is received. In addition to changing the flow-control window for streams that are not yet active, a SETTINGS frame can alter the initial flow-control window size for streams with active flow-control windows (that is, streams in the "open" or "half-closed (remote)" state). When the value of SETTINGS\_INITIAL\_WINDOW\_SIZE changes, a receiver MUST adjust the size of all stream flow-control windows that it maintains by the difference between the new value and the old value. A change to SETTINGS\_INITIAL\_WINDOW\_SIZE can cause the available space in a flow-control window to become negative. A sender MUST track the negative flow-control window and MUST NOT send new flow- controlled frames until it receives WINDOW\_UPDATE frames that cause the flow-control window to become positive. For example, if the client sends 60 KB immediately on connection establishment and the server sets the initial window size to be 16 KB, the client will recalculate the available flow-control window to be -44 KB on receipt of the SETTINGS frame. The client retains a negative flow-control window until WINDOW\_UPDATE frames restore the window to being positive, after which the client can resume sending. A SETTINGS frame cannot alter the connection flow-control window. An endpoint MUST treat a change to SETTINGS\_INITIAL\_WINDOW\_SIZE that causes any flow-control window to exceed the maximum size as a connection error ([Section 5.4.1](#section-5.4.1)) of type FLOW\_CONTROL\_ERROR. #### 6.9.3. Reducing the Stream Window Size A receiver that wishes to use a smaller flow-control window than the current size can send a new SETTINGS frame. However, the receiver MUST be prepared to receive data that exceeds this window size, since the sender might send data that exceeds the lower limit prior to processing the SETTINGS frame. After sending a SETTINGS frame that reduces the initial flow-control window size, a receiver MAY continue to process streams that exceed flow-control limits. Allowing streams to continue does not allow the receiver to immediately reduce the space it reserves for flow-control windows. Progress on these streams can also stall, since WINDOW\_UPDATE frames are needed to allow the sender to resume sending. The receiver MAY instead send a RST\_STREAM with an error code of FLOW\_CONTROL\_ERROR for the affected streams. ### 6.10. CONTINUATION The CONTINUATION frame (type=0x09) is used to continue a sequence of field block fragments ([Section 4.3](#section-4.3)). Any number of CONTINUATION frames can be sent, as long as the preceding frame is on the same stream and is a HEADERS, PUSH\_PROMISE, or CONTINUATION frame without the END\_HEADERS flag set. CONTINUATION Frame { Length (24), Type (8) = 0x09, Unused Flags (5), END\_HEADERS Flag (1), Unused Flags (2), Reserved (1), Stream Identifier (31), Field Block Fragment (..), } Figure 12: CONTINUATION Frame Format The Length, Type, Unused Flag(s), Reserved, and Stream Identifier fields are described in [Section 4](#section-4). The CONTINUATION frame payload contains a field block fragment ([Section 4.3](#section-4.3)). The CONTINUATION frame defines the following flag: END\_HEADERS (0x04): When set, the END\_HEADERS flag indicates that this frame ends a field block ([Section 4.3](#section-4.3)). If the END\_HEADERS flag is not set, this frame MUST be followed by another CONTINUATION frame. A receiver MUST treat the receipt of any other type of frame or a frame on a different stream as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. The CONTINUATION frame changes the connection state as defined in [Section 4.3](#section-4.3). CONTINUATION frames MUST be associated with a stream. If a CONTINUATION frame is received with a Stream Identifier field of 0x00, the recipient MUST respond with a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. A CONTINUATION frame MUST be preceded by a HEADERS, PUSH\_PROMISE or CONTINUATION frame without the END\_HEADERS flag set. A recipient that observes violation of this rule MUST respond with a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. 7. Error Codes -------------- Error codes are 32-bit fields that are used in RST\_STREAM and GOAWAY frames to convey the reasons for the stream or connection error. Error codes share a common code space. Some error codes apply only to either streams or the entire connection and have no defined semantics in the other context. The following error codes are defined: NO\_ERROR (0x00): The associated condition is not a result of an error. For example, a GOAWAY might include this code to indicate graceful shutdown of a connection. PROTOCOL\_ERROR (0x01): The endpoint detected an unspecific protocol error. This error is for use when a more specific error code is not available. INTERNAL\_ERROR (0x02): The endpoint encountered an unexpected internal error. FLOW\_CONTROL\_ERROR (0x03): The endpoint detected that its peer violated the flow-control protocol. SETTINGS\_TIMEOUT (0x04): The endpoint sent a SETTINGS frame but did not receive a response in a timely manner. See [Section 6.5.3](#section-6.5.3) ("Settings Synchronization"). STREAM\_CLOSED (0x05): The endpoint received a frame after a stream was half-closed. FRAME\_SIZE\_ERROR (0x06): The endpoint received a frame with an invalid size. REFUSED\_STREAM (0x07): The endpoint refused the stream prior to performing any application processing (see [Section 8.7](#section-8.7) for details). CANCEL (0x08): The endpoint uses this error code to indicate that the stream is no longer needed. COMPRESSION\_ERROR (0x09): The endpoint is unable to maintain the field section compression context for the connection. CONNECT\_ERROR (0x0a): The connection established in response to a CONNECT request ([Section 8.5](#section-8.5)) was reset or abnormally closed. ENHANCE\_YOUR\_CALM (0x0b): The endpoint detected that its peer is exhibiting a behavior that might be generating excessive load. INADEQUATE\_SECURITY (0x0c): The underlying transport has properties that do not meet minimum security requirements (see [Section 9.2](#section-9.2)). HTTP\_1\_1\_REQUIRED (0x0d): The endpoint requires that HTTP/1.1 be used instead of HTTP/2. Unknown or unsupported error codes MUST NOT trigger any special behavior. These MAY be treated by an implementation as being equivalent to INTERNAL\_ERROR. 8. Expressing HTTP Semantics in HTTP/2 -------------------------------------- HTTP/2 is an instantiation of the HTTP message abstraction (Section 6 of [[HTTP](#ref-HTTP)]). ### 8.1. HTTP Message Framing A client sends an HTTP request on a new stream, using a previously unused stream identifier ([Section 5.1.1](#section-5.1.1)). A server sends an HTTP response on the same stream as the request. An HTTP message (request or response) consists of: 1. one HEADERS frame (followed by zero or more CONTINUATION frames) containing the header section (see Section 6.3 of [[HTTP](#ref-HTTP)]), 2. zero or more DATA frames containing the message content (see Section 6.4 of [[HTTP](#ref-HTTP)]), and 3. optionally, one HEADERS frame (followed by zero or more CONTINUATION frames) containing the trailer section, if present (see Section 6.5 of [[HTTP](#ref-HTTP)]). For a response only, a server MAY send any number of interim responses before the HEADERS frame containing a final response. An interim response consists of a HEADERS frame (which might be followed by zero or more CONTINUATION frames) containing the control data and header section of an interim (1xx) HTTP response (see Section 15 of [[HTTP](#ref-HTTP)]). A HEADERS frame with the END\_STREAM flag set that carries an informational status code is malformed ([Section 8.1.1](#section-8.1.1)). The last frame in the sequence bears an END\_STREAM flag, noting that a HEADERS frame with the END\_STREAM flag set can be followed by CONTINUATION frames that carry any remaining fragments of the field block. Other frames (from any stream) MUST NOT occur between the HEADERS frame and any CONTINUATION frames that might follow. HTTP/2 uses DATA frames to carry message content. The chunked transfer encoding defined in [Section 7.1](#section-7.1) of [HTTP/1.1] cannot be used in HTTP/2; see [Section 8.2.2](#section-8.2.2). Trailer fields are carried in a field block that also terminates the stream. That is, trailer fields comprise a sequence starting with a HEADERS frame, followed by zero or more CONTINUATION frames, where the HEADERS frame bears an END\_STREAM flag. Trailers MUST NOT include pseudo-header fields ([Section 8.3](#section-8.3)). An endpoint that receives pseudo-header fields in trailers MUST treat the request or response as malformed ([Section 8.1.1](#section-8.1.1)). An endpoint that receives a HEADERS frame without the END\_STREAM flag set after receiving the HEADERS frame that opens a request or after receiving a final (non-informational) status code MUST treat the corresponding request or response as malformed ([Section 8.1.1](#section-8.1.1)). An HTTP request/response exchange fully consumes a single stream. A request starts with the HEADERS frame that puts the stream into the "open" state. The request ends with a frame with the END\_STREAM flag set, which causes the stream to become "half-closed (local)" for the client and "half-closed (remote)" for the server. A response stream starts with zero or more interim responses in HEADERS frames, followed by a HEADERS frame containing a final status code. An HTTP response is complete after the server sends -- or the client receives -- a frame with the END\_STREAM flag set (including any CONTINUATION frames needed to complete a field block). A server can send a complete response prior to the client sending an entire request if the response does not depend on any portion of the request that has not been sent and received. When this is true, a server MAY request that the client abort transmission of a request without error by sending a RST\_STREAM with an error code of NO\_ERROR after sending a complete response (i.e., a frame with the END\_STREAM flag set). Clients MUST NOT discard responses as a result of receiving such a RST\_STREAM, though clients can always discard responses at their discretion for other reasons. #### 8.1.1. Malformed Messages A malformed request or response is one that is an otherwise valid sequence of HTTP/2 frames but is invalid due to the presence of extraneous frames, prohibited fields or pseudo-header fields, the absence of mandatory pseudo-header fields, the inclusion of uppercase field names, or invalid field names and/or values (in certain circumstances; see [Section 8.2](#section-8.2)). A request or response that includes message content can include a content-length header field. A request or response is also malformed if the value of a content-length header field does not equal the sum of the DATA frame payload lengths that form the content, unless the message is defined as having no content. For example, 204 or 304 responses contain no content, as does the response to a HEAD request. A response that is defined to have no content, as described in Section 6.4.1 of [[HTTP](#ref-HTTP)], MAY have a non-zero content-length header field, even though no content is included in DATA frames. Intermediaries that process HTTP requests or responses (i.e., any intermediary not acting as a tunnel) MUST NOT forward a malformed request or response. Malformed requests or responses that are detected MUST be treated as a stream error ([Section 5.4.2](#section-5.4.2)) of type PROTOCOL\_ERROR. For malformed requests, a server MAY send an HTTP response prior to closing or resetting the stream. Clients MUST NOT accept a malformed response. Endpoints that progressively process messages might have performed some processing before identifying a request or response as malformed. For instance, it might be possible to generate an informational or 404 status code without having received a complete request. Similarly, intermediaries might forward incomplete messages before detecting errors. A server MAY generate a final response before receiving an entire request when the response does not depend on the remainder of the request being correct. These requirements are intended to protect against several types of common attacks against HTTP; they are deliberately strict because being permissive can expose implementations to these vulnerabilities. ### 8.2. HTTP Fields HTTP fields (Section 5 of [[HTTP](#ref-HTTP)]) are conveyed by HTTP/2 in the HEADERS, CONTINUATION, and PUSH\_PROMISE frames, compressed with HPACK [[COMPRESSION](#ref-COMPRESSION)]. Field names MUST be converted to lowercase when constructing an HTTP/2 message. #### 8.2.1. Field Validity The definitions of field names and values in HTTP prohibit some characters that HPACK might be able to convey. HTTP/2 implementations SHOULD validate field names and values according to their definitions in Sections [5.1](#section-5.1) and [5.5](#section-5.5) of [[HTTP](#ref-HTTP)], respectively, and treat messages that contain prohibited characters as malformed ([Section 8.1.1](#section-8.1.1)). Failure to validate fields can be exploited for request smuggling attacks. In particular, unvalidated fields might enable attacks when messages are forwarded using HTTP/1.1 [HTTP/1.1], where characters such as carriage return (CR), line feed (LF), and COLON are used as delimiters. Implementations MUST perform the following minimal validation of field names and values: \* A field name MUST NOT contain characters in the ranges 0x00-0x20, 0x41-0x5a, or 0x7f-0xff (all ranges inclusive). This specifically excludes all non-visible ASCII characters, ASCII SP (0x20), and uppercase characters ('A' to 'Z', ASCII 0x41 to 0x5a). \* With the exception of pseudo-header fields ([Section 8.3](#section-8.3)), which have a name that starts with a single colon, field names MUST NOT include a colon (ASCII COLON, 0x3a). \* A field value MUST NOT contain the zero value (ASCII NUL, 0x00), line feed (ASCII LF, 0x0a), or carriage return (ASCII CR, 0x0d) at any position. \* A field value MUST NOT start or end with an ASCII whitespace character (ASCII SP or HTAB, 0x20 or 0x09). | Note: An implementation that validates fields according to the | definitions in Sections [5.1](#section-5.1) and [5.5](#section-5.5) of [[HTTP](#ref-HTTP)] only needs an | additional check that field names do not include uppercase | characters. A request or response that contains a field that violates any of these conditions MUST be treated as malformed ([Section 8.1.1](#section-8.1.1)). In particular, an intermediary that does not process fields when forwarding messages MUST NOT forward fields that contain any of the values that are listed as prohibited above. When a request message violates one of these requirements, an implementation SHOULD generate a 400 (Bad Request) status code (see Section 15.5.1 of [[HTTP](#ref-HTTP)]), unless a more suitable status code is defined or the status code cannot be sent (e.g., because the error occurs in a trailer field). | Note: Field values that are not valid according to the | definition of the corresponding field do not cause a request to | be malformed; the requirements above only apply to the generic | syntax for fields as defined in Section 5 of [[HTTP](#ref-HTTP)]. #### 8.2.2. Connection-Specific Header Fields HTTP/2 does not use the Connection header field (Section 7.6.1 of [[HTTP](#ref-HTTP)]) to indicate connection-specific header fields; in this protocol, connection-specific metadata is conveyed by other means. An endpoint MUST NOT generate an HTTP/2 message containing connection-specific header fields. This includes the Connection header field and those listed as having connection-specific semantics in Section 7.6.1 of [[HTTP](#ref-HTTP)] (that is, Proxy-Connection, Keep-Alive, Transfer-Encoding, and Upgrade). Any message containing connection- specific header fields MUST be treated as malformed ([Section 8.1.1](#section-8.1.1)). The only exception to this is the TE header field, which MAY be present in an HTTP/2 request; when it is, it MUST NOT contain any value other than "trailers". An intermediary transforming an HTTP/1.x message to HTTP/2 MUST remove connection-specific header fields as discussed in Section 7.6.1 of [[HTTP](#ref-HTTP)], or their messages will be treated by other HTTP/2 endpoints as malformed ([Section 8.1.1](#section-8.1.1)). | Note: HTTP/2 purposefully does not support upgrade to another | protocol. The handshake methods described in [Section 3](#section-3) are | believed sufficient to negotiate the use of alternative | protocols. #### 8.2.3. Compressing the Cookie Header Field The Cookie header field [[COOKIE](#ref-COOKIE)] uses a semicolon (";") to delimit cookie-pairs (or "crumbs"). This header field contains multiple values, but does not use a COMMA (",") as a separator, thereby preventing cookie-pairs from being sent on multiple field lines (see Section 5.2 of [[HTTP](#ref-HTTP)]). This can significantly reduce compression efficiency, as updates to individual cookie-pairs would invalidate any field lines that are stored in the HPACK table. To allow for better compression efficiency, the Cookie header field MAY be split into separate header fields, each with one or more cookie-pairs. If there are multiple Cookie header fields after decompression, these MUST be concatenated into a single octet string using the two-octet delimiter of 0x3b, 0x20 (the ASCII string "; ") before being passed into a non-HTTP/2 context, such as an HTTP/1.1 connection, or a generic HTTP server application. Therefore, the following two lists of Cookie header fields are semantically equivalent. cookie: a=b; c=d; e=f cookie: a=b cookie: c=d cookie: e=f ### 8.3. HTTP Control Data HTTP/2 uses special pseudo-header fields beginning with a ':' character (ASCII 0x3a) to convey message control data (see Section 6.2 of [[HTTP](#ref-HTTP)]). Pseudo-header fields are not HTTP header fields. Endpoints MUST NOT generate pseudo-header fields other than those defined in this document. Note that an extension could negotiate the use of additional pseudo-header fields; see [Section 5.5](#section-5.5). Pseudo-header fields are only valid in the context in which they are defined. Pseudo-header fields defined for requests MUST NOT appear in responses; pseudo-header fields defined for responses MUST NOT appear in requests. Pseudo-header fields MUST NOT appear in a trailer section. Endpoints MUST treat a request or response that contains undefined or invalid pseudo-header fields as malformed ([Section 8.1.1](#section-8.1.1)). All pseudo-header fields MUST appear in a field block before all regular field lines. Any request or response that contains a pseudo- header field that appears in a field block after a regular field line MUST be treated as malformed ([Section 8.1.1](#section-8.1.1)). The same pseudo-header field name MUST NOT appear more than once in a field block. A field block for an HTTP request or response that contains a repeated pseudo-header field name MUST be treated as malformed ([Section 8.1.1](#section-8.1.1)). #### 8.3.1. Request Pseudo-Header Fields The following pseudo-header fields are defined for HTTP/2 requests: \* The ":method" pseudo-header field includes the HTTP method (Section 9 of [[HTTP](#ref-HTTP)]). \* The ":scheme" pseudo-header field includes the scheme portion of the request target. The scheme is taken from the target URI ([Section 3.1 of [RFC3986]](https://datatracker.ietf.org/doc/html/rfc3986#section-3.1)) when generating a request directly, or from the scheme of a translated request (for example, see [Section 3.3](#section-3.3) of [HTTP/1.1]). Scheme is omitted for CONNECT requests ([Section 8.5](#section-8.5)). ":scheme" is not restricted to "http" and "https" schemed URIs. A proxy or gateway can translate requests for non-HTTP schemes, enabling the use of HTTP to interact with non-HTTP services. \* The ":authority" pseudo-header field conveys the authority portion ([Section 3.2 of [RFC3986]](https://datatracker.ietf.org/doc/html/rfc3986#section-3.2)) of the target URI (Section 7.1 of [[HTTP](#ref-HTTP)]). The recipient of an HTTP/2 request MUST NOT use the Host header field to determine the target URI if ":authority" is present. Clients that generate HTTP/2 requests directly MUST use the ":authority" pseudo-header field to convey authority information, unless there is no authority information to convey (in which case it MUST NOT generate ":authority"). Clients MUST NOT generate a request with a Host header field that differs from the ":authority" pseudo-header field. A server SHOULD treat a request as malformed if it contains a Host header field that identifies an entity that differs from the entity in the ":authority" pseudo-header field. The values of fields need to be normalized to compare them (see [Section 6.2 of [RFC3986]](https://datatracker.ietf.org/doc/html/rfc3986#section-6.2)). An origin server can apply any normalization method, whereas other servers MUST perform scheme-based normalization (see [Section 6.2.3 of [RFC3986]](https://datatracker.ietf.org/doc/html/rfc3986#section-6.2.3)) of the two fields. An intermediary that forwards a request over HTTP/2 MUST construct an ":authority" pseudo-header field using the authority information from the control data of the original request, unless the original request's target URI does not contain authority information (in which case it MUST NOT generate ":authority"). Note that the Host header field is not the sole source of this information; see Section 7.2 of [[HTTP](#ref-HTTP)]. An intermediary that needs to generate a Host header field (which might be necessary to construct an HTTP/1.1 request) MUST use the value from the ":authority" pseudo-header field as the value of the Host field, unless the intermediary also changes the request target. This replaces any existing Host field to avoid potential vulnerabilities in HTTP routing. An intermediary that forwards a request over HTTP/2 MAY retain any Host header field. Note that request targets for CONNECT or asterisk-form OPTIONS requests never include authority information; see Sections [7.1](#section-7.1) and 7.2 of [[HTTP](#ref-HTTP)]. ":authority" MUST NOT include the deprecated userinfo subcomponent for "http" or "https" schemed URIs. \* The ":path" pseudo-header field includes the path and query parts of the target URI (the absolute-path production and, optionally, a '?' character followed by the query production; see Section 4.1 of [[HTTP](#ref-HTTP)]). A request in asterisk form (for OPTIONS) includes the value '\*' for the ":path" pseudo-header field. This pseudo-header field MUST NOT be empty for "http" or "https" URIs; "http" or "https" URIs that do not contain a path component MUST include a value of '/'. The exceptions to this rule are: - an OPTIONS request for an "http" or "https" URI that does not include a path component; these MUST include a ":path" pseudo- header field with a value of '\*' (see Section 7.1 of [[HTTP](#ref-HTTP)]). - CONNECT requests ([Section 8.5](#section-8.5)), where the ":path" pseudo-header field is omitted. All HTTP/2 requests MUST include exactly one valid value for the ":method", ":scheme", and ":path" pseudo-header fields, unless they are CONNECT requests ([Section 8.5](#section-8.5)). An HTTP request that omits mandatory pseudo-header fields is malformed ([Section 8.1.1](#section-8.1.1)). Individual HTTP/2 requests do not carry an explicit indicator of protocol version. All HTTP/2 requests implicitly have a protocol version of "2.0" (see Section 6.2 of [[HTTP](#ref-HTTP)]). #### 8.3.2. Response Pseudo-Header Fields For HTTP/2 responses, a single ":status" pseudo-header field is defined that carries the HTTP status code field (see Section 15 of [[HTTP](#ref-HTTP)]). This pseudo-header field MUST be included in all responses, including interim responses; otherwise, the response is malformed ([Section 8.1.1](#section-8.1.1)). HTTP/2 responses implicitly have a protocol version of "2.0". ### 8.4. Server Push HTTP/2 allows a server to preemptively send (or "push") responses (along with corresponding "promised" requests) to a client in association with a previous client-initiated request. Server push was designed to allow a server to improve client- perceived performance by predicting what requests will follow those that it receives, thereby removing a round trip for them. For example, a request for HTML is often followed by requests for stylesheets and scripts referenced by that page. When these requests are pushed, the client does not need to wait to receive the references to them in the HTML and issue separate requests. In practice, server push is difficult to use effectively, because it requires the server to correctly anticipate the additional requests the client will make, taking into account factors such as caching, content negotiation, and user behavior. Errors in prediction can lead to performance degradation, due to the opportunity cost that the additional data on the wire represents. In particular, pushing any significant amount of data can cause contention issues with responses that are more important. A client can request that server push be disabled, though this is negotiated for each hop independently. The SETTINGS\_ENABLE\_PUSH setting can be set to 0 to indicate that server push is disabled. Promised requests MUST be safe (see Section 9.2.1 of [[HTTP](#ref-HTTP)]) and cacheable (see Section 9.2.3 of [[HTTP](#ref-HTTP)]). Promised requests cannot include any content or a trailer section. Clients that receive a promised request that is not cacheable, that is not known to be safe, or that indicates the presence of request content MUST reset the promised stream with a stream error ([Section 5.4.2](#section-5.4.2)) of type PROTOCOL\_ERROR. Note that this could result in the promised stream being reset if the client does not recognize a newly defined method as being safe. Pushed responses that are cacheable (see Section 3 of [[CACHING](#ref-CACHING)]) can be stored by the client, if it implements an HTTP cache. Pushed responses are considered successfully validated on the origin server (e.g., if the "no-cache" cache response directive is present; see Section 5.2.2.4 of [[CACHING](#ref-CACHING)]) while the stream identified by the promised stream identifier is still open. Pushed responses that are not cacheable MUST NOT be stored by any HTTP cache. They MAY be made available to the application separately. The server MUST include a value in the ":authority" pseudo-header field for which the server is authoritative (see [Section 10.1](#section-10.1)). A client MUST treat a PUSH\_PROMISE for which the server is not authoritative as a stream error ([Section 5.4.2](#section-5.4.2)) of type PROTOCOL\_ERROR. An intermediary can receive pushes from the server and choose not to forward them on to the client. In other words, how to make use of the pushed information is up to that intermediary. Equally, the intermediary might choose to make additional pushes to the client, without any action taken by the server. A client cannot push. Thus, servers MUST treat the receipt of a PUSH\_PROMISE frame as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. A server cannot set the SETTINGS\_ENABLE\_PUSH setting to a value other than 0 (see [Section 6.5.2](#section-6.5.2)). #### 8.4.1. Push Requests Server push is semantically equivalent to a server responding to a request; however, in this case, that request is also sent by the server, as a PUSH\_PROMISE frame. The PUSH\_PROMISE frame includes a field block that contains control data and a complete set of request header fields that the server attributes to the request. It is not possible to push a response to a request that includes message content. Promised requests are always associated with an explicit request from the client. The PUSH\_PROMISE frames sent by the server are sent on that explicit request's stream. The PUSH\_PROMISE frame also includes a promised stream identifier, chosen from the stream identifiers available to the server (see [Section 5.1.1](#section-5.1.1)). The header fields in PUSH\_PROMISE and any subsequent CONTINUATION frames MUST be a valid and complete set of request header fields ([Section 8.3.1](#section-8.3.1)). The server MUST include a method in the ":method" pseudo-header field that is safe and cacheable. If a client receives a PUSH\_PROMISE that does not include a complete and valid set of header fields or the ":method" pseudo-header field identifies a method that is not safe, it MUST respond on the promised stream with a stream error ([Section 5.4.2](#section-5.4.2)) of type PROTOCOL\_ERROR. The server SHOULD send PUSH\_PROMISE ([Section 6.6](#section-6.6)) frames prior to sending any frames that reference the promised responses. This avoids a race where clients issue requests prior to receiving any PUSH\_PROMISE frames. For example, if the server receives a request for a document containing embedded links to multiple image files and the server chooses to push those additional images to the client, sending PUSH\_PROMISE frames before the DATA frames that contain the image links ensures that the client is able to see that a resource will be pushed before discovering embedded links. Similarly, if the server pushes resources referenced by the field block (for instance, in Link header fields), sending a PUSH\_PROMISE before sending the header ensures that clients do not request those resources. PUSH\_PROMISE frames MUST NOT be sent by the client. PUSH\_PROMISE frames can be sent by the server on any client-initiated stream, but the stream MUST be in either the "open" or "half-closed (remote)" state with respect to the server. PUSH\_PROMISE frames are interspersed with the frames that comprise a response, though they cannot be interspersed with HEADERS and CONTINUATION frames that comprise a single field block. Sending a PUSH\_PROMISE frame creates a new stream and puts the stream into the "reserved (local)" state for the server and the "reserved (remote)" state for the client. #### 8.4.2. Push Responses After sending the PUSH\_PROMISE frame, the server can begin delivering the pushed response as a response ([Section 8.3.2](#section-8.3.2)) on a server- initiated stream that uses the promised stream identifier. The server uses this stream to transmit an HTTP response, using the same sequence of frames as that defined in [Section 8.1](#section-8.1). This stream becomes "half-closed" to the client ([Section 5.1](#section-5.1)) after the initial HEADERS frame is sent. Once a client receives a PUSH\_PROMISE frame and chooses to accept the pushed response, the client SHOULD NOT issue any requests for the promised response until after the promised stream has closed. If the client determines, for any reason, that it does not wish to receive the pushed response from the server or if the server takes too long to begin sending the promised response, the client can send a RST\_STREAM frame, using either the CANCEL or REFUSED\_STREAM code and referencing the pushed stream's identifier. A client can use the SETTINGS\_MAX\_CONCURRENT\_STREAMS setting to limit the number of responses that can be concurrently pushed by a server. Advertising a SETTINGS\_MAX\_CONCURRENT\_STREAMS value of zero prevents the server from opening the streams necessary to push responses. However, this does not prevent the server from reserving streams using PUSH\_PROMISE frames, because reserved streams do not count toward the concurrent stream limit. Clients that do not wish to receive pushed resources need to reset any unwanted reserved streams or set SETTINGS\_ENABLE\_PUSH to 0. Clients receiving a pushed response MUST validate that either the server is authoritative (see [Section 10.1](#section-10.1)) or the proxy that provided the pushed response is configured for the corresponding request. For example, a server that offers a certificate for only the example.com DNS-ID (see [[RFC6125](https://datatracker.ietf.org/doc/html/rfc6125)]) is not permitted to push a response for <https://www.example.org/doc>. The response for a PUSH\_PROMISE stream begins with a HEADERS frame, which immediately puts the stream into the "half-closed (remote)" state for the server and "half-closed (local)" state for the client, and ends with a frame with the END\_STREAM flag set, which places the stream in the "closed" state. | Note: The client never sends a frame with the END\_STREAM flag | set for a server push. ### 8.5. The CONNECT Method The CONNECT method (Section 9.3.6 of [[HTTP](#ref-HTTP)]) is used to convert an HTTP connection into a tunnel to a remote host. CONNECT is primarily used with HTTP proxies to establish a TLS session with an origin server for the purposes of interacting with "https" resources. In HTTP/2, the CONNECT method establishes a tunnel over a single HTTP/2 stream to a remote host, rather than converting the entire connection to a tunnel. A CONNECT header section is constructed as defined in [Section 8.3.1](#section-8.3.1) ("Request Pseudo-Header Fields"), with a few differences. Specifically: \* The ":method" pseudo-header field is set to CONNECT. \* The ":scheme" and ":path" pseudo-header fields MUST be omitted. \* The ":authority" pseudo-header field contains the host and port to connect to (equivalent to the authority-form of the request-target of CONNECT requests; see [Section 3.2.3](#section-3.2.3) of [HTTP/1.1]). A CONNECT request that does not conform to these restrictions is malformed ([Section 8.1.1](#section-8.1.1)). A proxy that supports CONNECT establishes a TCP connection [[TCP](#ref-TCP)] to the host and port identified in the ":authority" pseudo-header field. Once this connection is successfully established, the proxy sends a HEADERS frame containing a 2xx-series status code to the client, as defined in Section 9.3.6 of [[HTTP](#ref-HTTP)]. After the initial HEADERS frame sent by each peer, all subsequent DATA frames correspond to data sent on the TCP connection. The frame payload of any DATA frames sent by the client is transmitted by the proxy to the TCP server; data received from the TCP server is assembled into DATA frames by the proxy. Frame types other than DATA or stream management frames (RST\_STREAM, WINDOW\_UPDATE, and PRIORITY) MUST NOT be sent on a connected stream and MUST be treated as a stream error ([Section 5.4.2](#section-5.4.2)) if received. The TCP connection can be closed by either peer. The END\_STREAM flag on a DATA frame is treated as being equivalent to the TCP FIN bit. A client is expected to send a DATA frame with the END\_STREAM flag set after receiving a frame with the END\_STREAM flag set. A proxy that receives a DATA frame with the END\_STREAM flag set sends the attached data with the FIN bit set on the last TCP segment. A proxy that receives a TCP segment with the FIN bit set sends a DATA frame with the END\_STREAM flag set. Note that the final TCP segment or DATA frame could be empty. A TCP connection error is signaled with RST\_STREAM. A proxy treats any error in the TCP connection, which includes receiving a TCP segment with the RST bit set, as a stream error ([Section 5.4.2](#section-5.4.2)) of type CONNECT\_ERROR. Correspondingly, a proxy MUST send a TCP segment with the RST bit set if it detects an error with the stream or the HTTP/2 connection. ### 8.6. The Upgrade Header Field HTTP/2 does not support the 101 (Switching Protocols) informational status code (Section 15.2.2 of [[HTTP](#ref-HTTP)]). The semantics of 101 (Switching Protocols) aren't applicable to a multiplexed protocol. Similar functionality might be enabled through the use of extended CONNECT [[RFC8441](https://datatracker.ietf.org/doc/html/rfc8441)], and other protocols are able to use the same mechanisms that HTTP/2 uses to negotiate their use (see [Section 3](#section-3)). ### 8.7. Request Reliability In general, an HTTP client is unable to retry a non-idempotent request when an error occurs because there is no means to determine the nature of the error (see Section 9.2.2 of [[HTTP](#ref-HTTP)]). It is possible that some server processing occurred prior to the error, which could result in undesirable effects if the request were reattempted. HTTP/2 provides two mechanisms for providing a guarantee to a client that a request has not been processed: \* The GOAWAY frame indicates the highest stream number that might have been processed. Requests on streams with higher numbers are therefore guaranteed to be safe to retry. \* The REFUSED\_STREAM error code can be included in a RST\_STREAM frame to indicate that the stream is being closed prior to any processing having occurred. Any request that was sent on the reset stream can be safely retried. Requests that have not been processed have not failed; clients MAY automatically retry them, even those with non-idempotent methods. A server MUST NOT indicate that a stream has not been processed unless it can guarantee that fact. If frames that are on a stream are passed to the application layer for any stream, then REFUSED\_STREAM MUST NOT be used for that stream, and a GOAWAY frame MUST include a stream identifier that is greater than or equal to the given stream identifier. In addition to these mechanisms, the PING frame provides a way for a client to easily test a connection. Connections that remain idle can become broken, because some middleboxes (for instance, network address translators or load balancers) silently discard connection bindings. The PING frame allows a client to safely test whether a connection is still active without sending a request. ### 8.8. Examples This section shows HTTP/1.1 requests and responses, with illustrations of equivalent HTTP/2 requests and responses. #### 8.8.1. Simple Request An HTTP GET request includes control data and a request header with no message content and is therefore transmitted as a single HEADERS frame, followed by zero or more CONTINUATION frames containing the serialized block of request header fields. The HEADERS frame in the following has both the END\_HEADERS and END\_STREAM flags set; no CONTINUATION frames are sent. GET /resource HTTP/1.1 HEADERS Host: example.org ==> + END\_STREAM Accept: image/jpeg + END\_HEADERS :method = GET :scheme = https :authority = example.org :path = /resource host = example.org accept = image/jpeg #### 8.8.2. Simple Response Similarly, a response that includes only control data and a response header is transmitted as a HEADERS frame (again, followed by zero or more CONTINUATION frames) containing the serialized block of response header fields. HTTP/1.1 304 Not Modified HEADERS ETag: "xyzzy" ==> + END\_STREAM Expires: Thu, 23 Jan ... + END\_HEADERS :status = 304 etag = "xyzzy" expires = Thu, 23 Jan #### 8.8.3. Complex Request An HTTP POST request that includes control data and a request header with message content is transmitted as one HEADERS frame, followed by zero or more CONTINUATION frames containing the request header, followed by one or more DATA frames, with the last CONTINUATION (or HEADERS) frame having the END\_HEADERS flag set and the final DATA frame having the END\_STREAM flag set: POST /resource HTTP/1.1 HEADERS Host: example.org ==> - END\_STREAM Content-Type: image/jpeg - END\_HEADERS Content-Length: 123 :method = POST :authority = example.org :path = /resource {binary data} :scheme = https CONTINUATION + END\_HEADERS content-type = image/jpeg host = example.org content-length = 123 DATA + END\_STREAM {binary data} Note that data contributing to any given field line could be spread between field block fragments. The allocation of field lines to frames in this example is illustrative only. #### 8.8.4. Response with Body A response that includes control data and a response header with message content is transmitted as a HEADERS frame, followed by zero or more CONTINUATION frames, followed by one or more DATA frames, with the last DATA frame in the sequence having the END\_STREAM flag set: HTTP/1.1 200 OK HEADERS Content-Type: image/jpeg ==> - END\_STREAM Content-Length: 123 + END\_HEADERS :status = 200 {binary data} content-type = image/jpeg content-length = 123 DATA + END\_STREAM {binary data} #### 8.8.5. Informational Responses An informational response using a 1xx status code other than 101 is transmitted as a HEADERS frame, followed by zero or more CONTINUATION frames. A trailer section is sent as a field block after both the request or response field block and all the DATA frames have been sent. The HEADERS frame starting the field block that comprises the trailer section has the END\_STREAM flag set. The following example includes both a 100 (Continue) status code, which is sent in response to a request containing a "100-continue" token in the Expect header field, and a trailer section: HTTP/1.1 100 Continue HEADERS Extension-Field: bar ==> - END\_STREAM + END\_HEADERS :status = 100 extension-field = bar HTTP/1.1 200 OK HEADERS Content-Type: image/jpeg ==> - END\_STREAM Transfer-Encoding: chunked + END\_HEADERS Trailer: Foo :status = 200 content-type = image/jpeg 123 trailer = Foo {binary data} 0 DATA Foo: bar - END\_STREAM {binary data} HEADERS + END\_STREAM + END\_HEADERS foo = bar 9. HTTP/2 Connections --------------------- This section outlines attributes of HTTP that improve interoperability, reduce exposure to known security vulnerabilities, or reduce the potential for implementation variation. ### 9.1. Connection Management HTTP/2 connections are persistent. For best performance, it is expected that clients will not close connections until it is determined that no further communication with a server is necessary (for example, when a user navigates away from a particular web page) or until the server closes the connection. Clients SHOULD NOT open more than one HTTP/2 connection to a given host and port pair, where the host is derived from a URI, a selected alternative service [[ALT-SVC](#ref-ALT-SVC)], or a configured proxy. A client can create additional connections as replacements, either to replace connections that are near to exhausting the available stream identifier space ([Section 5.1.1](#section-5.1.1)), to refresh the keying material for a TLS connection, or to replace connections that have encountered errors ([Section 5.4.1](#section-5.4.1)). A client MAY open multiple connections to the same IP address and TCP port using different Server Name Indication [[TLS-EXT](#ref-TLS-EXT)] values or to provide different TLS client certificates but SHOULD avoid creating multiple connections with the same configuration. Servers are encouraged to maintain open connections for as long as possible but are permitted to terminate idle connections if necessary. When either endpoint chooses to close the transport-layer TCP connection, the terminating endpoint SHOULD first send a GOAWAY ([Section 6.8](#section-6.8)) frame so that both endpoints can reliably determine whether previously sent frames have been processed and gracefully complete or terminate any necessary remaining tasks. #### 9.1.1. Connection Reuse Connections that are made to an origin server, either directly or through a tunnel created using the CONNECT method ([Section 8.5](#section-8.5)), MAY be reused for requests with multiple different URI authority components. A connection can be reused as long as the origin server is authoritative ([Section 10.1](#section-10.1)). For TCP connections without TLS, this depends on the host having resolved to the same IP address. For "https" resources, connection reuse additionally depends on having a certificate that is valid for the host in the URI. The certificate presented by the server MUST satisfy any checks that the client would perform when forming a new TLS connection for the host in the URI. A single certificate can be used to establish authority for multiple origins. Section 4.3 of [[HTTP](#ref-HTTP)] describes how a client determines whether a server is authoritative for a URI. In some deployments, reusing a connection for multiple origins can result in requests being directed to the wrong origin server. For example, TLS termination might be performed by a middlebox that uses the TLS Server Name Indication [[TLS-EXT](#ref-TLS-EXT)] extension to select an origin server. This means that it is possible for clients to send requests to servers that might not be the intended target for the request, even though the server is otherwise authoritative. A server that does not wish clients to reuse connections can indicate that it is not authoritative for a request by sending a 421 (Misdirected Request) status code in response to the request (see Section 15.5.20 of [[HTTP](#ref-HTTP)]). A client that is configured to use a proxy over HTTP/2 directs requests to that proxy through a single connection. That is, all requests sent via a proxy reuse the connection to the proxy. ### 9.2. Use of TLS Features Implementations of HTTP/2 MUST use TLS version 1.2 [[TLS12](#ref-TLS12)] or higher for HTTP/2 over TLS. The general TLS usage guidance in [[TLSBCP](#ref-TLSBCP)] SHOULD be followed, with some additional restrictions that are specific to HTTP/2. The TLS implementation MUST support the Server Name Indication (SNI) [[TLS-EXT](#ref-TLS-EXT)] extension to TLS. If the server is identified by a domain name [[DNS-TERMS](#ref-DNS-TERMS)], clients MUST send the server\_name TLS extension unless an alternative mechanism to indicate the target host is used. Requirements for deployments of HTTP/2 that negotiate TLS 1.3 [[TLS13](#ref-TLS13)] are included in [Section 9.2.3](#section-9.2.3). Deployments of TLS 1.2 are subject to the requirements in Sections [9.2.1](#section-9.2.1) and [9.2.2](#section-9.2.2). Implementations are encouraged to provide defaults that comply, but it is recognized that deployments are ultimately responsible for compliance. #### 9.2.1. TLS 1.2 Features This section describes restrictions on the TLS 1.2 feature set that can be used with HTTP/2. Due to deployment limitations, it might not be possible to fail TLS negotiation when these restrictions are not met. An endpoint MAY immediately terminate an HTTP/2 connection that does not meet these TLS requirements with a connection error ([Section 5.4.1](#section-5.4.1)) of type INADEQUATE\_SECURITY. A deployment of HTTP/2 over TLS 1.2 MUST disable compression. TLS compression can lead to the exposure of information that would not otherwise be revealed [[RFC3749](https://datatracker.ietf.org/doc/html/rfc3749)]. Generic compression is unnecessary, since HTTP/2 provides compression features that are more aware of context and therefore likely to be more appropriate for use for performance, security, or other reasons. A deployment of HTTP/2 over TLS 1.2 MUST disable renegotiation. An endpoint MUST treat a TLS renegotiation as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. Note that disabling renegotiation can result in long-lived connections becoming unusable due to limits on the number of messages the underlying cipher suite can encipher. An endpoint MAY use renegotiation to provide confidentiality protection for client credentials offered in the handshake, but any renegotiation MUST occur prior to sending the connection preface. A server SHOULD request a client certificate if it sees a renegotiation request immediately after establishing a connection. This effectively prevents the use of renegotiation in response to a request for a specific protected resource. A future specification might provide a way to support this use case. Alternatively, a server might use an error ([Section 5.4](#section-5.4)) of type HTTP\_1\_1\_REQUIRED to request that the client use a protocol that supports renegotiation. Implementations MUST support ephemeral key exchange sizes of at least 2048 bits for cipher suites that use ephemeral finite field Diffie- Hellman (DHE) (Section 8.1.2 of [[TLS12](#ref-TLS12)]) and 224 bits for cipher suites that use ephemeral elliptic curve Diffie-Hellman (ECDHE) [[RFC8422](https://datatracker.ietf.org/doc/html/rfc8422)]. Clients MUST accept DHE sizes of up to 4096 bits. Endpoints MAY treat negotiation of key sizes smaller than the lower limits as a connection error ([Section 5.4.1](#section-5.4.1)) of type INADEQUATE\_SECURITY. #### 9.2.2. TLS 1.2 Cipher Suites A deployment of HTTP/2 over TLS 1.2 SHOULD NOT use any of the prohibited cipher suites listed in [Appendix A](#appendix-A). Endpoints MAY choose to generate a connection error ([Section 5.4.1](#section-5.4.1)) of type INADEQUATE\_SECURITY if one of the prohibited cipher suites is negotiated. A deployment that chooses to use a prohibited cipher suite risks triggering a connection error unless the set of potential peers is known to accept that cipher suite. Implementations MUST NOT generate this error in reaction to the negotiation of a cipher suite that is not prohibited. Consequently, when clients offer a cipher suite that is not prohibited, they have to be prepared to use that cipher suite with HTTP/2. The list of prohibited cipher suites includes the cipher suite that TLS 1.2 makes mandatory, which means that TLS 1.2 deployments could have non-intersecting sets of permitted cipher suites. To avoid this problem, which causes TLS handshake failures, deployments of HTTP/2 that use TLS 1.2 MUST support TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256 [[TLS-ECDHE](#ref-TLS-ECDHE)] with the P-256 elliptic curve [[RFC8422](https://datatracker.ietf.org/doc/html/rfc8422)]. Note that clients might advertise support of cipher suites that are prohibited in order to allow for connection to servers that do not support HTTP/2. This allows servers to select HTTP/1.1 with a cipher suite that is prohibited in HTTP/2. However, this can result in HTTP/2 being negotiated with a prohibited cipher suite if the application protocol and cipher suite are independently selected. #### 9.2.3. TLS 1.3 Features TLS 1.3 includes a number of features not available in earlier versions. This section discusses the use of these features. HTTP/2 servers MUST NOT send post-handshake TLS 1.3 CertificateRequest messages. HTTP/2 clients MUST treat a TLS post- handshake CertificateRequest message as a connection error ([Section 5.4.1](#section-5.4.1)) of type PROTOCOL\_ERROR. The prohibition on post-handshake authentication applies even if the client offered the "post\_handshake\_auth" TLS extension. Post- handshake authentication support might be advertised independently of ALPN [[TLS-ALPN](#ref-TLS-ALPN)]. Clients might offer the capability for use in other protocols, but inclusion of the extension cannot imply support within HTTP/2. [TLS13] defines other post-handshake messages, NewSessionTicket and KeyUpdate, which can be used as they have no direct interaction with HTTP/2. Unless the use of a new type of TLS message depends on an interaction with the application-layer protocol, that TLS message can be sent after the handshake completes. TLS early data MAY be used to send requests, provided that the guidance in [[RFC8470](https://datatracker.ietf.org/doc/html/rfc8470)] is observed. Clients send requests in early data assuming initial values for all server settings. 10. Security Considerations --------------------------- The use of TLS is necessary to provide many of the security properties of this protocol. Many of the claims in this section do not hold unless TLS is used as described in [Section 9.2](#section-9.2). ### 10.1. Server Authority HTTP/2 relies on the HTTP definition of authority for determining whether a server is authoritative in providing a given response (see Section 4.3 of [[HTTP](#ref-HTTP)]). This relies on local name resolution for the "http" URI scheme and the authenticated server identity for the "https" scheme. ### 10.2. Cross-Protocol Attacks In a cross-protocol attack, an attacker causes a client to initiate a transaction in one protocol toward a server that understands a different protocol. An attacker might be able to cause the transaction to appear as a valid transaction in the second protocol. In combination with the capabilities of the web context, this can be used to interact with poorly protected servers in private networks. Completing a TLS handshake with an ALPN identifier for HTTP/2 can be considered sufficient protection against cross-protocol attacks. ALPN provides a positive indication that a server is willing to proceed with HTTP/2, which prevents attacks on other TLS-based protocols. The encryption in TLS makes it difficult for attackers to control the data that could be used in a cross-protocol attack on a cleartext protocol. The cleartext version of HTTP/2 has minimal protection against cross- protocol attacks. The connection preface ([Section 3.4](#section-3.4)) contains a string that is designed to confuse HTTP/1.1 servers, but no special protection is offered for other protocols. ### 10.3. Intermediary Encapsulation Attacks HPACK permits encoding of field names and values that might be treated as delimiters in other HTTP versions. An intermediary that translates an HTTP/2 request or response MUST validate fields according to the rules in [Section 8.2](#section-8.2) before translating a message to another HTTP version. Translating a field that includes invalid delimiters could be used to cause recipients to incorrectly interpret a message, which could be exploited by an attacker. [Section 8.2](#section-8.2) does not include specific rules for validation of pseudo- header fields. If the values of these fields are used, additional validation is necessary. This is particularly important where ":scheme", ":authority", and ":path" are combined to form a single URI string [[RFC3986](https://datatracker.ietf.org/doc/html/rfc3986)]. Similar problems might occur when that URI or just ":path" is combined with ":method" to construct a request line (as in [Section 3](#section-3) of [HTTP/1.1]). Simple concatenation is not secure unless the input values are fully validated. An intermediary can reject fields that contain invalid field names or values for other reasons -- in particular, those fields that do not conform to the HTTP ABNF grammar from Section 5 of [[HTTP](#ref-HTTP)]. Intermediaries that do not perform any validation of fields other than the minimum required by [Section 8.2](#section-8.2) could forward messages that contain invalid field names or values. An intermediary that receives any fields that require removal before forwarding (see Section 7.6.1 of [[HTTP](#ref-HTTP)]) MUST remove or replace those header fields when forwarding messages. Additionally, intermediaries should take care when forwarding messages containing Content-Length fields to ensure that the message is well-formed ([Section 8.1.1](#section-8.1.1)). This ensures that if the message is translated into HTTP/1.1 at any point, the framing will be correct. ### 10.4. Cacheability of Pushed Responses Pushed responses do not have an explicit request from the client; the request is provided by the server in the PUSH\_PROMISE frame. Caching responses that are pushed is possible based on the guidance provided by the origin server in the Cache-Control header field. However, this can cause issues if a single server hosts more than one tenant. For example, a server might offer multiple users each a small portion of its URI space. Where multiple tenants share space on the same server, that server MUST ensure that tenants are not able to push representations of resources that they do not have authority over. Failure to enforce this would allow a tenant to provide a representation that would be served out of cache, overriding the actual representation that the authoritative tenant provides. Pushed responses for which an origin server is not authoritative (see [Section 10.1](#section-10.1)) MUST NOT be used or cached. ### 10.5. Denial-of-Service Considerations An HTTP/2 connection can demand a greater commitment of resources to operate than an HTTP/1.1 connection. Both field section compression and flow control depend on a commitment of a greater amount of state. Settings for these features ensure that memory commitments for these features are strictly bounded. The number of PUSH\_PROMISE frames is not constrained in the same fashion. A client that accepts server push SHOULD limit the number of streams it allows to be in the "reserved (remote)" state. An excessive number of server push streams can be treated as a stream error ([Section 5.4.2](#section-5.4.2)) of type ENHANCE\_YOUR\_CALM. A number of HTTP/2 implementations were found to be vulnerable to denial of service [[NFLX-2019-002](#ref-NFLX-2019-002)]. Below is a list of known ways that implementations might be subject to denial-of-service attacks: \* Inefficient tracking of outstanding outbound frames can lead to overload if an adversary can cause large numbers of frames to be enqueued for sending. A peer could use one of several techniques to cause large numbers of frames to be generated: - Providing tiny increments to flow control in WINDOW\_UPDATE frames can cause a sender to generate a large number of DATA frames. - An endpoint is required to respond to a PING frame. - Each SETTINGS frame requires acknowledgment. - An invalid request (or server push) can cause a peer to send RST\_STREAM frames in response. \* An attacker can provide large amounts of flow-control credit at the HTTP/2 layer but withhold credit at the TCP layer, preventing frames from being sent. An endpoint that constructs and remembers frames for sending without considering TCP limits might be subject to resource exhaustion. \* Large numbers of small or empty frames can be abused to cause a peer to expend time processing frame headers. Caution is required here as some uses of small frames are entirely legitimate, such as the sending of an empty DATA or CONTINUATION frame at the end of a stream. \* The SETTINGS frame might also be abused to cause a peer to expend additional processing time. This might be done by pointlessly changing settings, sending multiple undefined settings, or changing the same setting multiple times in the same frame. \* Handling reprioritization with PRIORITY frames can require significant processing time and can lead to overload if many PRIORITY frames are sent. \* Field section compression also provides opportunities for an attacker to waste processing resources; see Section 7 of [[COMPRESSION](#ref-COMPRESSION)] for more details on potential abuses. \* Limits in SETTINGS cannot be reduced instantaneously, which leaves an endpoint exposed to behavior from a peer that could exceed the new limits. In particular, immediately after establishing a connection, limits set by a server are not known to clients and could be exceeded without being an obvious protocol violation. Most of the features that might be exploited for denial of service -- such as SETTINGS changes, small frames, field section compression -- have legitimate uses. These features become a burden only when they are used unnecessarily or to excess. An endpoint that doesn't monitor use of these features exposes itself to a risk of denial of service. Implementations SHOULD track the use of these features and set limits on their use. An endpoint MAY treat activity that is suspicious as a connection error ([Section 5.4.1](#section-5.4.1)) of type ENHANCE\_YOUR\_CALM. #### 10.5.1. Limits on Field Block Size A large field block ([Section 4.3](#section-4.3)) can cause an implementation to commit a large amount of state. Field lines that are critical for routing can appear toward the end of a field block, which prevents streaming of fields to their ultimate destination. This ordering and other reasons, such as ensuring cache correctness, mean that an endpoint might need to buffer the entire field block. Since there is no hard limit to the size of a field block, some endpoints could be forced to commit a large amount of available memory for field blocks. An endpoint can use the SETTINGS\_MAX\_HEADER\_LIST\_SIZE to advise peers of limits that might apply on the size of uncompressed field blocks. This setting is only advisory, so endpoints MAY choose to send field blocks that exceed this limit and risk the request or response being treated as malformed. This setting is specific to a connection, so any request or response could encounter a hop with a lower, unknown limit. An intermediary can attempt to avoid this problem by passing on values presented by different peers, but they are not obliged to do so. A server that receives a larger field block than it is willing to handle can send an HTTP 431 (Request Header Fields Too Large) status code [[RFC6585](https://datatracker.ietf.org/doc/html/rfc6585)]. A client can discard responses that it cannot process. The field block MUST be processed to ensure a consistent connection state, unless the connection is closed. #### 10.5.2. CONNECT Issues The CONNECT method can be used to create disproportionate load on a proxy, since stream creation is relatively inexpensive when compared to the creation and maintenance of a TCP connection. A proxy might also maintain some resources for a TCP connection beyond the closing of the stream that carries the CONNECT request, since the outgoing TCP connection remains in the TIME\_WAIT state. Therefore, a proxy cannot rely on SETTINGS\_MAX\_CONCURRENT\_STREAMS alone to limit the resources consumed by CONNECT requests. ### 10.6. Use of Compression Compression can allow an attacker to recover secret data when it is compressed in the same context as data under attacker control. HTTP/2 enables compression of field lines ([Section 4.3](#section-4.3)); the following concerns also apply to the use of HTTP compressed content- codings (Section 8.4.1 of [[HTTP](#ref-HTTP)]). There are demonstrable attacks on compression that exploit the characteristics of the Web (e.g., [[BREACH](#ref-BREACH)]). The attacker induces multiple requests containing varying plaintext, observing the length of the resulting ciphertext in each, which reveals a shorter length when a guess about the secret is correct. Implementations communicating on a secure channel MUST NOT compress content that includes both confidential and attacker-controlled data unless separate compression dictionaries are used for each source of data. Compression MUST NOT be used if the source of data cannot be reliably determined. Generic stream compression, such as that provided by TLS, MUST NOT be used with HTTP/2 (see [Section 9.2](#section-9.2)). Further considerations regarding the compression of header fields are described in [[COMPRESSION](#ref-COMPRESSION)]. ### 10.7. Use of Padding Padding within HTTP/2 is not intended as a replacement for general purpose padding, such as that provided by TLS [[TLS13](#ref-TLS13)]. Redundant padding could even be counterproductive. Correct application can depend on having specific knowledge of the data that is being padded. To mitigate attacks that rely on compression, disabling or limiting compression might be preferable to padding as a countermeasure. Padding can be used to obscure the exact size of frame content and is provided to mitigate specific attacks within HTTP -- for example, attacks where compressed content includes both attacker-controlled plaintext and secret data (e.g., [[BREACH](#ref-BREACH)]). Use of padding can result in less protection than might seem immediately obvious. At best, padding only makes it more difficult for an attacker to infer length information by increasing the number of frames an attacker has to observe. Incorrectly implemented padding schemes can be easily defeated. In particular, randomized padding with a predictable distribution provides very little protection; similarly, padding frame payloads to a fixed size exposes information as frame payload sizes cross the fixed-sized boundary, which could be possible if an attacker can control plaintext. Intermediaries SHOULD retain padding for DATA frames but MAY drop padding for HEADERS and PUSH\_PROMISE frames. A valid reason for an intermediary to change the amount of padding of frames is to improve the protections that padding provides. ### 10.8. Privacy Considerations Several characteristics of HTTP/2 provide an observer an opportunity to correlate actions of a single client or server over time. These include the values of settings, the manner in which flow-control windows are managed, the way priorities are allocated to streams, the timing of reactions to stimulus, and the handling of any features that are controlled by settings. As far as these create observable differences in behavior, they could be used as a basis for fingerprinting a specific client, as defined in Section 3.2 of [[PRIVACY](#ref-PRIVACY)]. HTTP/2's preference for using a single TCP connection allows correlation of a user's activity on a site. Reusing connections for different origins allows tracking across those origins. Because the PING and SETTINGS frames solicit immediate responses, they can be used by an endpoint to measure latency to their peer. This might have privacy implications in certain scenarios. ### 10.9. Remote Timing Attacks Remote timing attacks extract secrets from servers by observing variations in the time that servers take when processing requests that use secrets. HTTP/2 enables concurrent request creation and processing, which can give attackers better control over when request processing commences. Multiple HTTP/2 requests can be included in the same IP packet or TLS record. HTTP/2 can therefore make remote timing attacks more efficient by eliminating variability in request delivery, leaving only request order and the delivery of responses as sources of timing variability. Ensuring that processing time is not dependent on the value of a secret is the best defense against any form of timing attack. 11. IANA Considerations ----------------------- This revision of HTTP/2 marks the HTTP2-Settings header field and the h2c upgrade token, both defined in [[RFC7540](https://datatracker.ietf.org/doc/html/rfc7540)], as obsolete. [Section 11 of [RFC7540]](https://datatracker.ietf.org/doc/html/rfc7540#section-11) registered the h2 and h2c ALPN identifiers along with the PRI HTTP method. [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) also established a registry for frame types, settings, and error codes. These registrations and registries apply to HTTP/2, but are not redefined in this document. IANA has updated references to [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) in the following registries to refer to this document: "TLS Application-Layer Protocol Negotiation (ALPN) Protocol IDs", "HTTP/2 Frame Type", "HTTP/2 Settings", "HTTP/2 Error Code", and "HTTP Method Registry". The registration of the PRI method has been updated to refer to [Section 3.4](#section-3.4); all other section numbers have not changed. IANA has changed the policy on those portions of the "HTTP/2 Frame Type" and "HTTP/2 Settings" registries that were reserved for Experimental Use in [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540). These portions of the registries shall operate on the same policy as the remainder of each registry. ### 11.1. HTTP2-Settings Header Field Registration This section marks the HTTP2-Settings header field registered by [Section 11.5 of [RFC7540]](https://datatracker.ietf.org/doc/html/rfc7540#section-11.5) in the "Hypertext Transfer Protocol (HTTP) Field Name Registry" as obsolete. This capability has been removed: see [Section 3.1](#section-3.1). The registration is updated to include the details as required by Section 18.4 of [[HTTP](#ref-HTTP)]: Field Name: HTTP2-Settings Status: obsoleted Reference: [Section 3.2.1 of [RFC7540]](https://datatracker.ietf.org/doc/html/rfc7540#section-3.2.1) Comments: Obsolete; see [Section 11.1](#section-11.1) of this document. ### 11.2. The h2c Upgrade Token This section records the h2c upgrade token registered by [Section 11.8 of [RFC7540]](https://datatracker.ietf.org/doc/html/rfc7540#section-11.8) in the "Hypertext Transfer Protocol (HTTP) Upgrade Token Registry" as obsolete. This capability has been removed: see [Section 3.1](#section-3.1). The registration is updated as follows: Value: h2c Description: (OBSOLETE) Hypertext Transfer Protocol version 2 (HTTP/2) Expected Version Tokens: None Reference: [Section 3.1](#section-3.1) of this document 12. References -------------- ### 12.1. Normative References [CACHING] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP Caching", STD 98, [RFC 9111](https://datatracker.ietf.org/doc/html/rfc9111), DOI 10.17487/RFC9111, June 2022, <<https://www.rfc-editor.org/info/rfc9111>>. [COMPRESSION] Peon, R. and H. Ruellan, "HPACK: Header Compression for HTTP/2", [RFC 7541](https://datatracker.ietf.org/doc/html/rfc7541), DOI 10.17487/RFC7541, May 2015, <<https://www.rfc-editor.org/info/rfc7541>>. [COOKIE] Barth, A., "HTTP State Management Mechanism", [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265), DOI 10.17487/RFC6265, April 2011, <<https://www.rfc-editor.org/info/rfc6265>>. [HTTP] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP Semantics", STD 97, [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110), DOI 10.17487/RFC9110, June 2022, <<https://www.rfc-editor.org/info/rfc9110>>. [QUIC] Iyengar, J., Ed. and M. Thomson, Ed., "QUIC: A UDP-Based Multiplexed and Secure Transport", [RFC 9000](https://datatracker.ietf.org/doc/html/rfc9000), DOI 10.17487/RFC9000, May 2021, <<https://www.rfc-editor.org/info/rfc9000>>. [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", [BCP 14](https://datatracker.ietf.org/doc/html/bcp14), [RFC 2119](https://datatracker.ietf.org/doc/html/rfc2119), DOI 10.17487/RFC2119, March 1997, <<https://www.rfc-editor.org/info/rfc2119>>. [RFC3986] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform Resource Identifier (URI): Generic Syntax", STD 66, [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986), DOI 10.17487/RFC3986, January 2005, <<https://www.rfc-editor.org/info/rfc3986>>. [RFC8174] Leiba, B., "Ambiguity of Uppercase vs Lowercase in [RFC](https://datatracker.ietf.org/doc/html/rfc2119) [2119](https://datatracker.ietf.org/doc/html/rfc2119) Key Words", [BCP 14](https://datatracker.ietf.org/doc/html/bcp14), [RFC 8174](https://datatracker.ietf.org/doc/html/rfc8174), DOI 10.17487/RFC8174, May 2017, <<https://www.rfc-editor.org/info/rfc8174>>. [RFC8422] Nir, Y., Josefsson, S., and M. Pegourie-Gonnard, "Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS) Versions 1.2 and Earlier", [RFC 8422](https://datatracker.ietf.org/doc/html/rfc8422), DOI 10.17487/RFC8422, August 2018, <<https://www.rfc-editor.org/info/rfc8422>>. [RFC8470] Thomson, M., Nottingham, M., and W. Tarreau, "Using Early Data in HTTP", [RFC 8470](https://datatracker.ietf.org/doc/html/rfc8470), DOI 10.17487/RFC8470, September 2018, <<https://www.rfc-editor.org/info/rfc8470>>. [TCP] Postel, J., "Transmission Control Protocol", STD 7, [RFC 793](https://datatracker.ietf.org/doc/html/rfc793), DOI 10.17487/RFC0793, September 1981, <<https://www.rfc-editor.org/info/rfc793>>. [TLS-ALPN] Friedl, S., Popov, A., Langley, A., and E. Stephan, "Transport Layer Security (TLS) Application-Layer Protocol Negotiation Extension", [RFC 7301](https://datatracker.ietf.org/doc/html/rfc7301), DOI 10.17487/RFC7301, July 2014, <<https://www.rfc-editor.org/info/rfc7301>>. [TLS-ECDHE] Rescorla, E., "TLS Elliptic Curve Cipher Suites with SHA- 256/384 and AES Galois Counter Mode (GCM)", [RFC 5289](https://datatracker.ietf.org/doc/html/rfc5289), DOI 10.17487/RFC5289, August 2008, <<https://www.rfc-editor.org/info/rfc5289>>. [TLS-EXT] Eastlake 3rd, D., "Transport Layer Security (TLS) Extensions: Extension Definitions", [RFC 6066](https://datatracker.ietf.org/doc/html/rfc6066), DOI 10.17487/RFC6066, January 2011, <<https://www.rfc-editor.org/info/rfc6066>>. [TLS12] Dierks, T. and E. Rescorla, "The Transport Layer Security (TLS) Protocol Version 1.2", [RFC 5246](https://datatracker.ietf.org/doc/html/rfc5246), DOI 10.17487/RFC5246, August 2008, <<https://www.rfc-editor.org/info/rfc5246>>. [TLS13] Rescorla, E., "The Transport Layer Security (TLS) Protocol Version 1.3", [RFC 8446](https://datatracker.ietf.org/doc/html/rfc8446), DOI 10.17487/RFC8446, August 2018, <<https://www.rfc-editor.org/info/rfc8446>>. [TLSBCP] Sheffer, Y., Holz, R., and P. Saint-Andre, "Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS)", [BCP 195](https://datatracker.ietf.org/doc/html/bcp195), [RFC 7525](https://datatracker.ietf.org/doc/html/rfc7525), DOI 10.17487/RFC7525, May 2015, <<https://www.rfc-editor.org/info/rfc7525>>. ### 12.2. Informative References [ALT-SVC] Nottingham, M., McManus, P., and J. Reschke, "HTTP Alternative Services", [RFC 7838](https://datatracker.ietf.org/doc/html/rfc7838), DOI 10.17487/RFC7838, April 2016, <<https://www.rfc-editor.org/info/rfc7838>>. [BREACH] Gluck, Y., Harris, N., and A. Prado, "BREACH: Reviving the CRIME Attack", 12 July 2013, <<https://breachattack.com/resources/> BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf>. [DNS-TERMS] Hoffman, P., Sullivan, A., and K. Fujiwara, "DNS Terminology", [BCP 219](https://datatracker.ietf.org/doc/html/bcp219), [RFC 8499](https://datatracker.ietf.org/doc/html/rfc8499), DOI 10.17487/RFC8499, January 2019, <<https://www.rfc-editor.org/info/rfc8499>>. [HTTP-PRIORITY] Oku, K. and L. Pardue, "Extensible Prioritization Scheme for HTTP", [RFC 9218](https://datatracker.ietf.org/doc/html/rfc9218), DOI 10.17487/RFC9218, June 2022, <<https://www.rfc-editor.org/info/rfc9218>>. [HTTP/1.1] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP/1.1", STD 99, [RFC 9112](https://datatracker.ietf.org/doc/html/rfc9112), DOI 10.17487/RFC9112, June 2022, <<https://www.rfc-editor.org/info/rfc9112>>. [NFLX-2019-002] Netflix, "HTTP/2 Denial of Service Advisory", 13 August 2019, <[https://github.com/Netflix/security-](https://github.com/Netflix/security-bulletins/blob/master/advisories/third-party/2019-002.md) [bulletins/blob/master/advisories/third-party/2019-002.md](https://github.com/Netflix/security-bulletins/blob/master/advisories/third-party/2019-002.md)>. [PRIVACY] Cooper, A., Tschofenig, H., Aboba, B., Peterson, J., Morris, J., Hansen, M., and R. Smith, "Privacy Considerations for Internet Protocols", [RFC 6973](https://datatracker.ietf.org/doc/html/rfc6973), DOI 10.17487/RFC6973, July 2013, <<https://www.rfc-editor.org/info/rfc6973>>. [RFC1122] Braden, R., Ed., "Requirements for Internet Hosts - Communication Layers", STD 3, [RFC 1122](https://datatracker.ietf.org/doc/html/rfc1122), DOI 10.17487/RFC1122, October 1989, <<https://www.rfc-editor.org/info/rfc1122>>. [RFC3749] Hollenbeck, S., "Transport Layer Security Protocol Compression Methods", [RFC 3749](https://datatracker.ietf.org/doc/html/rfc3749), DOI 10.17487/RFC3749, May 2004, <<https://www.rfc-editor.org/info/rfc3749>>. [RFC6125] Saint-Andre, P. and J. Hodges, "Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS)", [RFC 6125](https://datatracker.ietf.org/doc/html/rfc6125), DOI 10.17487/RFC6125, March 2011, <<https://www.rfc-editor.org/info/rfc6125>>. [RFC6585] Nottingham, M. and R. Fielding, "Additional HTTP Status Codes", [RFC 6585](https://datatracker.ietf.org/doc/html/rfc6585), DOI 10.17487/RFC6585, April 2012, <<https://www.rfc-editor.org/info/rfc6585>>. [RFC7323] Borman, D., Braden, B., Jacobson, V., and R. Scheffenegger, Ed., "TCP Extensions for High Performance", [RFC 7323](https://datatracker.ietf.org/doc/html/rfc7323), DOI 10.17487/RFC7323, September 2014, <<https://www.rfc-editor.org/info/rfc7323>>. [RFC7540] Belshe, M., Peon, R., and M. Thomson, Ed., "Hypertext Transfer Protocol Version 2 (HTTP/2)", [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540), DOI 10.17487/RFC7540, May 2015, <<https://www.rfc-editor.org/info/rfc7540>>. [RFC8441] McManus, P., "Bootstrapping WebSockets with HTTP/2", [RFC 8441](https://datatracker.ietf.org/doc/html/rfc8441), DOI 10.17487/RFC8441, September 2018, <<https://www.rfc-editor.org/info/rfc8441>>. [RFC8740] Benjamin, D., "Using TLS 1.3 with HTTP/2", [RFC 8740](https://datatracker.ietf.org/doc/html/rfc8740), DOI 10.17487/RFC8740, February 2020, <<https://www.rfc-editor.org/info/rfc8740>>. [TALKING] Huang, L., Chen, E., Barth, A., Rescorla, E., and C. Jackson, "Talking to Yourself for Fun and Profit", 2011, <[https://www.adambarth.com/papers/2011/huang-chen-barth-](https://www.adambarth.com/papers/2011/huang-chen-barth-rescorla-jackson.pdf) [rescorla-jackson.pdf](https://www.adambarth.com/papers/2011/huang-chen-barth-rescorla-jackson.pdf)>. Appendix A. Prohibited TLS 1.2 Cipher Suites -------------------------------------------- An HTTP/2 implementation MAY treat the negotiation of any of the following cipher suites with TLS 1.2 as a connection error ([Section 5.4.1](#section-5.4.1)) of type INADEQUATE\_SECURITY: \* TLS\_NULL\_WITH\_NULL\_NULL \* TLS\_RSA\_WITH\_NULL\_MD5 \* TLS\_RSA\_WITH\_NULL\_SHA \* TLS\_RSA\_EXPORT\_WITH\_RC4\_40\_MD5 \* TLS\_RSA\_WITH\_RC4\_128\_MD5 \* TLS\_RSA\_WITH\_RC4\_128\_SHA \* TLS\_RSA\_EXPORT\_WITH\_RC2\_CBC\_40\_MD5 \* TLS\_RSA\_WITH\_IDEA\_CBC\_SHA \* TLS\_RSA\_EXPORT\_WITH\_DES40\_CBC\_SHA \* TLS\_RSA\_WITH\_DES\_CBC\_SHA \* TLS\_RSA\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_DH\_DSS\_EXPORT\_WITH\_DES40\_CBC\_SHA \* TLS\_DH\_DSS\_WITH\_DES\_CBC\_SHA \* TLS\_DH\_DSS\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_DH\_RSA\_EXPORT\_WITH\_DES40\_CBC\_SHA \* TLS\_DH\_RSA\_WITH\_DES\_CBC\_SHA \* TLS\_DH\_RSA\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_DHE\_DSS\_EXPORT\_WITH\_DES40\_CBC\_SHA \* TLS\_DHE\_DSS\_WITH\_DES\_CBC\_SHA \* TLS\_DHE\_DSS\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_DHE\_RSA\_EXPORT\_WITH\_DES40\_CBC\_SHA \* TLS\_DHE\_RSA\_WITH\_DES\_CBC\_SHA \* TLS\_DHE\_RSA\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_DH\_anon\_EXPORT\_WITH\_RC4\_40\_MD5 \* TLS\_DH\_anon\_WITH\_RC4\_128\_MD5 \* TLS\_DH\_anon\_EXPORT\_WITH\_DES40\_CBC\_SHA \* TLS\_DH\_anon\_WITH\_DES\_CBC\_SHA \* TLS\_DH\_anon\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_KRB5\_WITH\_DES\_CBC\_SHA \* TLS\_KRB5\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_KRB5\_WITH\_RC4\_128\_SHA \* TLS\_KRB5\_WITH\_IDEA\_CBC\_SHA \* TLS\_KRB5\_WITH\_DES\_CBC\_MD5 \* TLS\_KRB5\_WITH\_3DES\_EDE\_CBC\_MD5 \* TLS\_KRB5\_WITH\_RC4\_128\_MD5 \* TLS\_KRB5\_WITH\_IDEA\_CBC\_MD5 \* TLS\_KRB5\_EXPORT\_WITH\_DES\_CBC\_40\_SHA \* TLS\_KRB5\_EXPORT\_WITH\_RC2\_CBC\_40\_SHA \* TLS\_KRB5\_EXPORT\_WITH\_RC4\_40\_SHA \* TLS\_KRB5\_EXPORT\_WITH\_DES\_CBC\_40\_MD5 \* TLS\_KRB5\_EXPORT\_WITH\_RC2\_CBC\_40\_MD5 \* TLS\_KRB5\_EXPORT\_WITH\_RC4\_40\_MD5 \* TLS\_PSK\_WITH\_NULL\_SHA \* TLS\_DHE\_PSK\_WITH\_NULL\_SHA \* TLS\_RSA\_PSK\_WITH\_NULL\_SHA \* TLS\_RSA\_WITH\_AES\_128\_CBC\_SHA \* TLS\_DH\_DSS\_WITH\_AES\_128\_CBC\_SHA \* TLS\_DH\_RSA\_WITH\_AES\_128\_CBC\_SHA \* TLS\_DHE\_DSS\_WITH\_AES\_128\_CBC\_SHA \* TLS\_DHE\_RSA\_WITH\_AES\_128\_CBC\_SHA \* TLS\_DH\_anon\_WITH\_AES\_128\_CBC\_SHA \* TLS\_RSA\_WITH\_AES\_256\_CBC\_SHA \* TLS\_DH\_DSS\_WITH\_AES\_256\_CBC\_SHA \* TLS\_DH\_RSA\_WITH\_AES\_256\_CBC\_SHA \* TLS\_DHE\_DSS\_WITH\_AES\_256\_CBC\_SHA \* TLS\_DHE\_RSA\_WITH\_AES\_256\_CBC\_SHA \* TLS\_DH\_anon\_WITH\_AES\_256\_CBC\_SHA \* TLS\_RSA\_WITH\_NULL\_SHA256 \* TLS\_RSA\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_RSA\_WITH\_AES\_256\_CBC\_SHA256 \* TLS\_DH\_DSS\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_DH\_RSA\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_DHE\_DSS\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_RSA\_WITH\_CAMELLIA\_128\_CBC\_SHA \* TLS\_DH\_DSS\_WITH\_CAMELLIA\_128\_CBC\_SHA \* TLS\_DH\_RSA\_WITH\_CAMELLIA\_128\_CBC\_SHA \* TLS\_DHE\_DSS\_WITH\_CAMELLIA\_128\_CBC\_SHA \* TLS\_DHE\_RSA\_WITH\_CAMELLIA\_128\_CBC\_SHA \* TLS\_DH\_anon\_WITH\_CAMELLIA\_128\_CBC\_SHA \* TLS\_DHE\_RSA\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_DH\_DSS\_WITH\_AES\_256\_CBC\_SHA256 \* TLS\_DH\_RSA\_WITH\_AES\_256\_CBC\_SHA256 \* TLS\_DHE\_DSS\_WITH\_AES\_256\_CBC\_SHA256 \* TLS\_DHE\_RSA\_WITH\_AES\_256\_CBC\_SHA256 \* TLS\_DH\_anon\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_DH\_anon\_WITH\_AES\_256\_CBC\_SHA256 \* TLS\_RSA\_WITH\_CAMELLIA\_256\_CBC\_SHA \* TLS\_DH\_DSS\_WITH\_CAMELLIA\_256\_CBC\_SHA \* TLS\_DH\_RSA\_WITH\_CAMELLIA\_256\_CBC\_SHA \* TLS\_DHE\_DSS\_WITH\_CAMELLIA\_256\_CBC\_SHA \* TLS\_DHE\_RSA\_WITH\_CAMELLIA\_256\_CBC\_SHA \* TLS\_DH\_anon\_WITH\_CAMELLIA\_256\_CBC\_SHA \* TLS\_PSK\_WITH\_RC4\_128\_SHA \* TLS\_PSK\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_PSK\_WITH\_AES\_128\_CBC\_SHA \* TLS\_PSK\_WITH\_AES\_256\_CBC\_SHA \* TLS\_DHE\_PSK\_WITH\_RC4\_128\_SHA \* TLS\_DHE\_PSK\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_DHE\_PSK\_WITH\_AES\_128\_CBC\_SHA \* TLS\_DHE\_PSK\_WITH\_AES\_256\_CBC\_SHA \* TLS\_RSA\_PSK\_WITH\_RC4\_128\_SHA \* TLS\_RSA\_PSK\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_RSA\_PSK\_WITH\_AES\_128\_CBC\_SHA \* TLS\_RSA\_PSK\_WITH\_AES\_256\_CBC\_SHA \* TLS\_RSA\_WITH\_SEED\_CBC\_SHA \* TLS\_DH\_DSS\_WITH\_SEED\_CBC\_SHA \* TLS\_DH\_RSA\_WITH\_SEED\_CBC\_SHA \* TLS\_DHE\_DSS\_WITH\_SEED\_CBC\_SHA \* TLS\_DHE\_RSA\_WITH\_SEED\_CBC\_SHA \* TLS\_DH\_anon\_WITH\_SEED\_CBC\_SHA \* TLS\_RSA\_WITH\_AES\_128\_GCM\_SHA256 \* TLS\_RSA\_WITH\_AES\_256\_GCM\_SHA384 \* TLS\_DH\_RSA\_WITH\_AES\_128\_GCM\_SHA256 \* TLS\_DH\_RSA\_WITH\_AES\_256\_GCM\_SHA384 \* TLS\_DH\_DSS\_WITH\_AES\_128\_GCM\_SHA256 \* TLS\_DH\_DSS\_WITH\_AES\_256\_GCM\_SHA384 \* TLS\_DH\_anon\_WITH\_AES\_128\_GCM\_SHA256 \* TLS\_DH\_anon\_WITH\_AES\_256\_GCM\_SHA384 \* TLS\_PSK\_WITH\_AES\_128\_GCM\_SHA256 \* TLS\_PSK\_WITH\_AES\_256\_GCM\_SHA384 \* TLS\_RSA\_PSK\_WITH\_AES\_128\_GCM\_SHA256 \* TLS\_RSA\_PSK\_WITH\_AES\_256\_GCM\_SHA384 \* TLS\_PSK\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_PSK\_WITH\_AES\_256\_CBC\_SHA384 \* TLS\_PSK\_WITH\_NULL\_SHA256 \* TLS\_PSK\_WITH\_NULL\_SHA384 \* TLS\_DHE\_PSK\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_DHE\_PSK\_WITH\_AES\_256\_CBC\_SHA384 \* TLS\_DHE\_PSK\_WITH\_NULL\_SHA256 \* TLS\_DHE\_PSK\_WITH\_NULL\_SHA384 \* TLS\_RSA\_PSK\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_RSA\_PSK\_WITH\_AES\_256\_CBC\_SHA384 \* TLS\_RSA\_PSK\_WITH\_NULL\_SHA256 \* TLS\_RSA\_PSK\_WITH\_NULL\_SHA384 \* TLS\_RSA\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_DH\_DSS\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_DH\_RSA\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_DHE\_DSS\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_DHE\_RSA\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_DH\_anon\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_RSA\_WITH\_CAMELLIA\_256\_CBC\_SHA256 \* TLS\_DH\_DSS\_WITH\_CAMELLIA\_256\_CBC\_SHA256 \* TLS\_DH\_RSA\_WITH\_CAMELLIA\_256\_CBC\_SHA256 \* TLS\_DHE\_DSS\_WITH\_CAMELLIA\_256\_CBC\_SHA256 \* TLS\_DHE\_RSA\_WITH\_CAMELLIA\_256\_CBC\_SHA256 \* TLS\_DH\_anon\_WITH\_CAMELLIA\_256\_CBC\_SHA256 \* TLS\_EMPTY\_RENEGOTIATION\_INFO\_SCSV \* TLS\_ECDH\_ECDSA\_WITH\_NULL\_SHA \* TLS\_ECDH\_ECDSA\_WITH\_RC4\_128\_SHA \* TLS\_ECDH\_ECDSA\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_ECDH\_ECDSA\_WITH\_AES\_128\_CBC\_SHA \* TLS\_ECDH\_ECDSA\_WITH\_AES\_256\_CBC\_SHA \* TLS\_ECDHE\_ECDSA\_WITH\_NULL\_SHA \* TLS\_ECDHE\_ECDSA\_WITH\_RC4\_128\_SHA \* TLS\_ECDHE\_ECDSA\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA \* TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA \* TLS\_ECDH\_RSA\_WITH\_NULL\_SHA \* TLS\_ECDH\_RSA\_WITH\_RC4\_128\_SHA \* TLS\_ECDH\_RSA\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_ECDH\_RSA\_WITH\_AES\_128\_CBC\_SHA \* TLS\_ECDH\_RSA\_WITH\_AES\_256\_CBC\_SHA \* TLS\_ECDHE\_RSA\_WITH\_NULL\_SHA \* TLS\_ECDHE\_RSA\_WITH\_RC4\_128\_SHA \* TLS\_ECDHE\_RSA\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA \* TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA \* TLS\_ECDH\_anon\_WITH\_NULL\_SHA \* TLS\_ECDH\_anon\_WITH\_RC4\_128\_SHA \* TLS\_ECDH\_anon\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_ECDH\_anon\_WITH\_AES\_128\_CBC\_SHA \* TLS\_ECDH\_anon\_WITH\_AES\_256\_CBC\_SHA \* TLS\_SRP\_SHA\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_SRP\_SHA\_RSA\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_SRP\_SHA\_DSS\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_SRP\_SHA\_WITH\_AES\_128\_CBC\_SHA \* TLS\_SRP\_SHA\_RSA\_WITH\_AES\_128\_CBC\_SHA \* TLS\_SRP\_SHA\_DSS\_WITH\_AES\_128\_CBC\_SHA \* TLS\_SRP\_SHA\_WITH\_AES\_256\_CBC\_SHA \* TLS\_SRP\_SHA\_RSA\_WITH\_AES\_256\_CBC\_SHA \* TLS\_SRP\_SHA\_DSS\_WITH\_AES\_256\_CBC\_SHA \* TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 \* TLS\_ECDH\_ECDSA\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_ECDH\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 \* TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384 \* TLS\_ECDH\_RSA\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_ECDH\_RSA\_WITH\_AES\_256\_CBC\_SHA384 \* TLS\_ECDH\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256 \* TLS\_ECDH\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384 \* TLS\_ECDH\_RSA\_WITH\_AES\_128\_GCM\_SHA256 \* TLS\_ECDH\_RSA\_WITH\_AES\_256\_GCM\_SHA384 \* TLS\_ECDHE\_PSK\_WITH\_RC4\_128\_SHA \* TLS\_ECDHE\_PSK\_WITH\_3DES\_EDE\_CBC\_SHA \* TLS\_ECDHE\_PSK\_WITH\_AES\_128\_CBC\_SHA \* TLS\_ECDHE\_PSK\_WITH\_AES\_256\_CBC\_SHA \* TLS\_ECDHE\_PSK\_WITH\_AES\_128\_CBC\_SHA256 \* TLS\_ECDHE\_PSK\_WITH\_AES\_256\_CBC\_SHA384 \* TLS\_ECDHE\_PSK\_WITH\_NULL\_SHA \* TLS\_ECDHE\_PSK\_WITH\_NULL\_SHA256 \* TLS\_ECDHE\_PSK\_WITH\_NULL\_SHA384 \* TLS\_RSA\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_RSA\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_DH\_DSS\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_DH\_DSS\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_DH\_RSA\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_DH\_RSA\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_DHE\_DSS\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_DHE\_DSS\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_DHE\_RSA\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_DHE\_RSA\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_DH\_anon\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_DH\_anon\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_ECDHE\_ECDSA\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_ECDHE\_ECDSA\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_ECDH\_ECDSA\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_ECDH\_ECDSA\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_ECDHE\_RSA\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_ECDHE\_RSA\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_ECDH\_RSA\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_ECDH\_RSA\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_RSA\_WITH\_ARIA\_128\_GCM\_SHA256 \* TLS\_RSA\_WITH\_ARIA\_256\_GCM\_SHA384 \* TLS\_DH\_RSA\_WITH\_ARIA\_128\_GCM\_SHA256 \* TLS\_DH\_RSA\_WITH\_ARIA\_256\_GCM\_SHA384 \* TLS\_DH\_DSS\_WITH\_ARIA\_128\_GCM\_SHA256 \* TLS\_DH\_DSS\_WITH\_ARIA\_256\_GCM\_SHA384 \* TLS\_DH\_anon\_WITH\_ARIA\_128\_GCM\_SHA256 \* TLS\_DH\_anon\_WITH\_ARIA\_256\_GCM\_SHA384 \* TLS\_ECDH\_ECDSA\_WITH\_ARIA\_128\_GCM\_SHA256 \* TLS\_ECDH\_ECDSA\_WITH\_ARIA\_256\_GCM\_SHA384 \* TLS\_ECDH\_RSA\_WITH\_ARIA\_128\_GCM\_SHA256 \* TLS\_ECDH\_RSA\_WITH\_ARIA\_256\_GCM\_SHA384 \* TLS\_PSK\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_PSK\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_DHE\_PSK\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_DHE\_PSK\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_RSA\_PSK\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_RSA\_PSK\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_PSK\_WITH\_ARIA\_128\_GCM\_SHA256 \* TLS\_PSK\_WITH\_ARIA\_256\_GCM\_SHA384 \* TLS\_RSA\_PSK\_WITH\_ARIA\_128\_GCM\_SHA256 \* TLS\_RSA\_PSK\_WITH\_ARIA\_256\_GCM\_SHA384 \* TLS\_ECDHE\_PSK\_WITH\_ARIA\_128\_CBC\_SHA256 \* TLS\_ECDHE\_PSK\_WITH\_ARIA\_256\_CBC\_SHA384 \* TLS\_ECDHE\_ECDSA\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_ECDHE\_ECDSA\_WITH\_CAMELLIA\_256\_CBC\_SHA384 \* TLS\_ECDH\_ECDSA\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_ECDH\_ECDSA\_WITH\_CAMELLIA\_256\_CBC\_SHA384 \* TLS\_ECDHE\_RSA\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_ECDHE\_RSA\_WITH\_CAMELLIA\_256\_CBC\_SHA384 \* TLS\_ECDH\_RSA\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_ECDH\_RSA\_WITH\_CAMELLIA\_256\_CBC\_SHA384 \* TLS\_RSA\_WITH\_CAMELLIA\_128\_GCM\_SHA256 \* TLS\_RSA\_WITH\_CAMELLIA\_256\_GCM\_SHA384 \* TLS\_DH\_RSA\_WITH\_CAMELLIA\_128\_GCM\_SHA256 \* TLS\_DH\_RSA\_WITH\_CAMELLIA\_256\_GCM\_SHA384 \* TLS\_DH\_DSS\_WITH\_CAMELLIA\_128\_GCM\_SHA256 \* TLS\_DH\_DSS\_WITH\_CAMELLIA\_256\_GCM\_SHA384 \* TLS\_DH\_anon\_WITH\_CAMELLIA\_128\_GCM\_SHA256 \* TLS\_DH\_anon\_WITH\_CAMELLIA\_256\_GCM\_SHA384 \* TLS\_ECDH\_ECDSA\_WITH\_CAMELLIA\_128\_GCM\_SHA256 \* TLS\_ECDH\_ECDSA\_WITH\_CAMELLIA\_256\_GCM\_SHA384 \* TLS\_ECDH\_RSA\_WITH\_CAMELLIA\_128\_GCM\_SHA256 \* TLS\_ECDH\_RSA\_WITH\_CAMELLIA\_256\_GCM\_SHA384 \* TLS\_PSK\_WITH\_CAMELLIA\_128\_GCM\_SHA256 \* TLS\_PSK\_WITH\_CAMELLIA\_256\_GCM\_SHA384 \* TLS\_RSA\_PSK\_WITH\_CAMELLIA\_128\_GCM\_SHA256 \* TLS\_RSA\_PSK\_WITH\_CAMELLIA\_256\_GCM\_SHA384 \* TLS\_PSK\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_PSK\_WITH\_CAMELLIA\_256\_CBC\_SHA384 \* TLS\_DHE\_PSK\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_DHE\_PSK\_WITH\_CAMELLIA\_256\_CBC\_SHA384 \* TLS\_RSA\_PSK\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_RSA\_PSK\_WITH\_CAMELLIA\_256\_CBC\_SHA384 \* TLS\_ECDHE\_PSK\_WITH\_CAMELLIA\_128\_CBC\_SHA256 \* TLS\_ECDHE\_PSK\_WITH\_CAMELLIA\_256\_CBC\_SHA384 \* TLS\_RSA\_WITH\_AES\_128\_CCM \* TLS\_RSA\_WITH\_AES\_256\_CCM \* TLS\_RSA\_WITH\_AES\_128\_CCM\_8 \* TLS\_RSA\_WITH\_AES\_256\_CCM\_8 \* TLS\_PSK\_WITH\_AES\_128\_CCM \* TLS\_PSK\_WITH\_AES\_256\_CCM \* TLS\_PSK\_WITH\_AES\_128\_CCM\_8 \* TLS\_PSK\_WITH\_AES\_256\_CCM\_8 | Note: This list was assembled from the set of registered TLS | cipher suites when [[RFC7540](https://datatracker.ietf.org/doc/html/rfc7540)] was developed. This list includes | those cipher suites that do not offer an ephemeral key exchange | and those that are based on the TLS null, stream, or block | cipher type (as defined in Section 6.2.3 of [[TLS12](#ref-TLS12)]). | Additional cipher suites with these properties could be | defined; these would not be explicitly prohibited. For more details, see [Section 9.2.2](#section-9.2.2). Appendix B. Changes from [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) ---------------------------------------------------------------------------------- This revision includes the following substantive changes: \* Use of TLS 1.3 was defined based on [[RFC8740](https://datatracker.ietf.org/doc/html/rfc8740)], which this document obsoletes. \* The priority scheme defined in [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) is deprecated. Definitions for the format of the PRIORITY frame and the priority fields in the HEADERS frame have been retained, plus the rules governing when PRIORITY frames can be sent and received, but the semantics of these fields are only described in [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540). The priority signaling scheme from [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540) was not successful. Using the simpler signaling in [[HTTP-PRIORITY](#ref-HTTP-PRIORITY)] is recommended. \* The HTTP/1.1 Upgrade mechanism is deprecated and no longer specified in this document. It was never widely deployed, with plaintext HTTP/2 users choosing to use the prior-knowledge implementation instead. \* Validation for field names and values has been narrowed. The validation that is mandatory for intermediaries is precisely defined, and error reporting for requests has been amended to encourage sending 400-series status codes. \* The ranges of codepoints for settings and frame types that were reserved for Experimental Use are now available for general use. \* Connection-specific header fields -- which are prohibited -- are more precisely and comprehensively identified. \* Host and ":authority" are no longer permitted to disagree. \* Rules for sending Dynamic Table Size Update instructions after changes in settings have been clarified in [Section 4.3.1](#section-4.3.1). Editorial changes are also included. In particular, changes to terminology and document structure are in response to updates to core HTTP semantics [[HTTP](#ref-HTTP)]. Those documents now include some concepts that were first defined in [RFC 7540](https://datatracker.ietf.org/doc/html/rfc7540), such as the 421 status code or connection coalescing. Acknowledgments Credit for non-trivial input to this document is owed to a large number of people who have contributed to the HTTP Working Group over the years. [[RFC7540](https://datatracker.ietf.org/doc/html/rfc7540)] contains a more extensive list of people that deserve acknowledgment for their contributions. Contributors Mike Belshe and Roberto Peon authored the text that this document is based on. Authors' Addresses Martin Thomson (editor) Mozilla Australia Email: [email protected] Cory Benfield (editor) Apple Inc. Email: [email protected]
programming_docs
http HTTP/3 Internet Engineering Task Force (IETF) M. Bishop, Ed. Request for Comments: 9114 Akamai Category: Standards Track June 2022 ISSN: 2070-1721 HTTP/3 ====== Abstract The QUIC transport protocol has several features that are desirable in a transport for HTTP, such as stream multiplexing, per-stream flow control, and low-latency connection establishment. This document describes a mapping of HTTP semantics over QUIC. This document also identifies HTTP/2 features that are subsumed by QUIC and describes how HTTP/2 extensions can be ported to HTTP/3. Status of This Memo This is an Internet Standards Track document. This document is a product of the Internet Engineering Task Force (IETF). It represents the consensus of the IETF community. It has received public review and has been approved for publication by the Internet Engineering Steering Group (IESG). Further information on Internet Standards is available in [Section 2 of RFC 7841](https://datatracker.ietf.org/doc/html/rfc7841#section-2). Information about the current status of this document, any errata, and how to provide feedback on it may be obtained at <https://www.rfc-editor.org/info/rfc9114>. Copyright Notice Copyright (c) 2022 IETF Trust and the persons identified as the document authors. All rights reserved. This document is subject to [BCP 78](https://datatracker.ietf.org/doc/html/bcp78) and the IETF Trust's Legal Provisions Relating to IETF Documents (<https://trustee.ietf.org/license-info>) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Revised BSD License text as described in [Section 4](#section-4).e of the Trust Legal Provisions and are provided without warranty as described in the Revised BSD License. Table of Contents 1. Introduction 1.1. Prior Versions of HTTP 1.2. Delegation to QUIC 2. HTTP/3 Protocol Overview 2.1. Document Organization 2.2. Conventions and Terminology 3. Connection Setup and Management 3.1. Discovering an HTTP/3 Endpoint 3.1.1. HTTP Alternative Services 3.1.2. Other Schemes 3.2. Connection Establishment 3.3. Connection Reuse 4. Expressing HTTP Semantics in HTTP/3 4.1. HTTP Message Framing 4.1.1. Request Cancellation and Rejection 4.1.2. Malformed Requests and Responses 4.2. HTTP Fields 4.2.1. Field Compression 4.2.2. Header Size Constraints 4.3. HTTP Control Data 4.3.1. Request Pseudo-Header Fields 4.3.2. Response Pseudo-Header Fields 4.4. The CONNECT Method 4.5. HTTP Upgrade 4.6. Server Push 5. Connection Closure 5.1. Idle Connections 5.2. Connection Shutdown 5.3. Immediate Application Closure 5.4. Transport Closure 6. Stream Mapping and Usage 6.1. Bidirectional Streams 6.2. Unidirectional Streams 6.2.1. Control Streams 6.2.2. Push Streams 6.2.3. Reserved Stream Types 7. HTTP Framing Layer 7.1. Frame Layout 7.2. Frame Definitions 7.2.1. DATA 7.2.2. HEADERS 7.2.3. CANCEL\_PUSH 7.2.4. SETTINGS 7.2.5. PUSH\_PROMISE 7.2.6. GOAWAY 7.2.7. MAX\_PUSH\_ID 7.2.8. Reserved Frame Types 8. Error Handling 8.1. HTTP/3 Error Codes 9. Extensions to HTTP/3 10. Security Considerations 10.1. Server Authority 10.2. Cross-Protocol Attacks 10.3. Intermediary-Encapsulation Attacks 10.4. Cacheability of Pushed Responses 10.5. Denial-of-Service Considerations 10.5.1. Limits on Field Section Size 10.5.2. CONNECT Issues 10.6. Use of Compression 10.7. Padding and Traffic Analysis 10.8. Frame Parsing 10.9. Early Data 10.10. Migration 10.11. Privacy Considerations 11. IANA Considerations 11.1. Registration of HTTP/3 Identification String 11.2. New Registries 11.2.1. Frame Types 11.2.2. Settings Parameters 11.2.3. Error Codes 11.2.4. Stream Types 12. References 12.1. Normative References 12.2. Informative References [Appendix A](#appendix-A). Considerations for Transitioning from HTTP/2 A.1. Streams A.2. HTTP Frame Types A.2.1. Prioritization Differences A.2.2. Field Compression Differences A.2.3. Flow-Control Differences A.2.4. Guidance for New Frame Type Definitions A.2.5. Comparison of HTTP/2 and HTTP/3 Frame Types A.3. HTTP/2 SETTINGS Parameters A.4. HTTP/2 Error Codes A.4.1. Mapping between HTTP/2 and HTTP/3 Errors Acknowledgments Index Author's Address 1. Introduction --------------- HTTP semantics ([[HTTP](#ref-HTTP)]) are used for a broad range of services on the Internet. These semantics have most commonly been used with HTTP/1.1 and HTTP/2. HTTP/1.1 has been used over a variety of transport and session layers, while HTTP/2 has been used primarily with TLS over TCP. HTTP/3 supports the same semantics over a new transport protocol: QUIC. ### 1.1. Prior Versions of HTTP HTTP/1.1 ([HTTP/1.1]) uses whitespace-delimited text fields to convey HTTP messages. While these exchanges are human readable, using whitespace for message formatting leads to parsing complexity and excessive tolerance of variant behavior. Because HTTP/1.1 does not include a multiplexing layer, multiple TCP connections are often used to service requests in parallel. However, that has a negative impact on congestion control and network efficiency, since TCP does not share congestion control across multiple connections. HTTP/2 ([HTTP/2]) introduced a binary framing and multiplexing layer to improve latency without modifying the transport layer. However, because the parallel nature of HTTP/2's multiplexing is not visible to TCP's loss recovery mechanisms, a lost or reordered packet causes all active transactions to experience a stall regardless of whether that transaction was directly impacted by the lost packet. ### 1.2. Delegation to QUIC The QUIC transport protocol incorporates stream multiplexing and per- stream flow control, similar to that provided by the HTTP/2 framing layer. By providing reliability at the stream level and congestion control across the entire connection, QUIC has the capability to improve the performance of HTTP compared to a TCP mapping. QUIC also incorporates TLS 1.3 ([[TLS](#ref-TLS)]) at the transport layer, offering comparable confidentiality and integrity to running TLS over TCP, with the improved connection setup latency of TCP Fast Open ([[TFO](#ref-TFO)]). This document defines HTTP/3: a mapping of HTTP semantics over the QUIC transport protocol, drawing heavily on the design of HTTP/2. HTTP/3 relies on QUIC to provide confidentiality and integrity protection of data; peer authentication; and reliable, in-order, per- stream delivery. While delegating stream lifetime and flow-control issues to QUIC, a binary framing similar to the HTTP/2 framing is used on each stream. Some HTTP/2 features are subsumed by QUIC, while other features are implemented atop QUIC. QUIC is described in [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. For a full description of HTTP/2, see [HTTP/2]. 2. HTTP/3 Protocol Overview --------------------------- HTTP/3 provides a transport for HTTP semantics using the QUIC transport protocol and an internal framing layer similar to HTTP/2. Once a client knows that an HTTP/3 server exists at a certain endpoint, it opens a QUIC connection. QUIC provides protocol negotiation, stream-based multiplexing, and flow control. Discovery of an HTTP/3 endpoint is described in [Section 3.1](#section-3.1). Within each stream, the basic unit of HTTP/3 communication is a frame ([Section 7.2](#section-7.2)). Each frame type serves a different purpose. For example, HEADERS and DATA frames form the basis of HTTP requests and responses ([Section 4.1](#section-4.1)). Frames that apply to the entire connection are conveyed on a dedicated control stream. Multiplexing of requests is performed using the QUIC stream abstraction, which is described in Section 2 of [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. Each request-response pair consumes a single QUIC stream. Streams are independent of each other, so one stream that is blocked or suffers packet loss does not prevent progress on other streams. Server push is an interaction mode introduced in HTTP/2 ([HTTP/2]) that permits a server to push a request-response exchange to a client in anticipation of the client making the indicated request. This trades off network usage against a potential latency gain. Several HTTP/3 frames are used to manage server push, such as PUSH\_PROMISE, MAX\_PUSH\_ID, and CANCEL\_PUSH. As in HTTP/2, request and response fields are compressed for transmission. Because HPACK ([[HPACK](#ref-HPACK)]) relies on in-order transmission of compressed field sections (a guarantee not provided by QUIC), HTTP/3 replaces HPACK with QPACK ([[QPACK](#ref-QPACK)]). QPACK uses separate unidirectional streams to modify and track field table state, while encoded field sections refer to the state of the table without modifying it. ### 2.1. Document Organization The following sections provide a detailed overview of the lifecycle of an HTTP/3 connection: \* "Connection Setup and Management" ([Section 3](#section-3)) covers how an HTTP/3 endpoint is discovered and an HTTP/3 connection is established. \* "Expressing HTTP Semantics in HTTP/3" ([Section 4](#section-4)) describes how HTTP semantics are expressed using frames. \* "Connection Closure" ([Section 5](#section-5)) describes how HTTP/3 connections are terminated, either gracefully or abruptly. The details of the wire protocol and interactions with the transport are described in subsequent sections: \* "Stream Mapping and Usage" ([Section 6](#section-6)) describes the way QUIC streams are used. \* "HTTP Framing Layer" ([Section 7](#section-7)) describes the frames used on most streams. \* "Error Handling" ([Section 8](#section-8)) describes how error conditions are handled and expressed, either on a particular stream or for the connection as a whole. Additional resources are provided in the final sections: \* "Extensions to HTTP/3" ([Section 9](#section-9)) describes how new capabilities can be added in future documents. \* A more detailed comparison between HTTP/2 and HTTP/3 can be found in [Appendix A](#appendix-A). ### 2.2. Conventions and Terminology The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://datatracker.ietf.org/doc/html/bcp14) [[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)] [[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when, and only when, they appear in all capitals, as shown here. This document uses the variable-length integer encoding from [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. The following terms are used: abort: An abrupt termination of a connection or stream, possibly due to an error condition. client: The endpoint that initiates an HTTP/3 connection. Clients send HTTP requests and receive HTTP responses. connection: A transport-layer connection between two endpoints using QUIC as the transport protocol. connection error: An error that affects the entire HTTP/3 connection. endpoint: Either the client or server of the connection. frame: The smallest unit of communication on a stream in HTTP/3, consisting of a header and a variable-length sequence of bytes structured according to the frame type. Protocol elements called "frames" exist in both this document and [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. Where frames from [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)] are referenced, the frame name will be prefaced with "QUIC". For example, "QUIC CONNECTION\_CLOSE frames". References without this preface refer to frames defined in [Section 7.2](#section-7.2). HTTP/3 connection: A QUIC connection where the negotiated application protocol is HTTP/3. peer: An endpoint. When discussing a particular endpoint, "peer" refers to the endpoint that is remote to the primary subject of discussion. receiver: An endpoint that is receiving frames. sender: An endpoint that is transmitting frames. server: The endpoint that accepts an HTTP/3 connection. Servers receive HTTP requests and send HTTP responses. stream: A bidirectional or unidirectional bytestream provided by the QUIC transport. All streams within an HTTP/3 connection can be considered "HTTP/3 streams", but multiple stream types are defined within HTTP/3. stream error: An application-level error on the individual stream. The term "content" is defined in Section 6.4 of [[HTTP](#ref-HTTP)]. Finally, the terms "resource", "message", "user agent", "origin server", "gateway", "intermediary", "proxy", and "tunnel" are defined in Section 3 of [[HTTP](#ref-HTTP)]. Packet diagrams in this document use the format defined in Section 1.3 of [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)] to illustrate the order and size of fields. 3. Connection Setup and Management ---------------------------------- ### 3.1. Discovering an HTTP/3 Endpoint HTTP relies on the notion of an authoritative response: a response that has been determined to be the most appropriate response for that request given the state of the target resource at the time of response message origination by (or at the direction of) the origin server identified within the target URI. Locating an authoritative server for an HTTP URI is discussed in Section 4.3 of [[HTTP](#ref-HTTP)]. The "https" scheme associates authority with possession of a certificate that the client considers to be trustworthy for the host identified by the authority component of the URI. Upon receiving a server certificate in the TLS handshake, the client MUST verify that the certificate is an acceptable match for the URI's origin server using the process described in Section 4.3.4 of [[HTTP](#ref-HTTP)]. If the certificate cannot be verified with respect to the URI's origin server, the client MUST NOT consider the server authoritative for that origin. A client MAY attempt access to a resource with an "https" URI by resolving the host identifier to an IP address, establishing a QUIC connection to that address on the indicated port (including validation of the server certificate as described above), and sending an HTTP/3 request message targeting the URI to the server over that secured connection. Unless some other mechanism is used to select HTTP/3, the token "h3" is used in the Application-Layer Protocol Negotiation (ALPN; see [[RFC7301](https://datatracker.ietf.org/doc/html/rfc7301)]) extension during the TLS handshake. Connectivity problems (e.g., blocking UDP) can result in a failure to establish a QUIC connection; clients SHOULD attempt to use TCP-based versions of HTTP in this case. Servers MAY serve HTTP/3 on any UDP port; an alternative service advertisement always includes an explicit port, and URIs contain either an explicit port or a default port associated with the scheme. #### 3.1.1. HTTP Alternative Services An HTTP origin can advertise the availability of an equivalent HTTP/3 endpoint via the Alt-Svc HTTP response header field or the HTTP/2 ALTSVC frame ([[ALTSVC](#ref-ALTSVC)]) using the "h3" ALPN token. For example, an origin could indicate in an HTTP response that HTTP/3 was available on UDP port 50781 at the same hostname by including the following header field: Alt-Svc: h3=":50781" On receipt of an Alt-Svc record indicating HTTP/3 support, a client MAY attempt to establish a QUIC connection to the indicated host and port; if this connection is successful, the client can send HTTP requests using the mapping described in this document. #### 3.1.2. Other Schemes Although HTTP is independent of the transport protocol, the "http" scheme associates authority with the ability to receive TCP connections on the indicated port of whatever host is identified within the authority component. Because HTTP/3 does not use TCP, HTTP/3 cannot be used for direct access to the authoritative server for a resource identified by an "http" URI. However, protocol extensions such as [[ALTSVC](#ref-ALTSVC)] permit the authoritative server to identify other services that are also authoritative and that might be reachable over HTTP/3. Prior to making requests for an origin whose scheme is not "https", the client MUST ensure the server is willing to serve that scheme. For origins whose scheme is "http", an experimental method to accomplish this is described in [[RFC8164](https://datatracker.ietf.org/doc/html/rfc8164)]. Other mechanisms might be defined for various schemes in the future. ### 3.2. Connection Establishment HTTP/3 relies on QUIC version 1 as the underlying transport. The use of other QUIC transport versions with HTTP/3 MAY be defined by future specifications. QUIC version 1 uses TLS version 1.3 or greater as its handshake protocol. HTTP/3 clients MUST support a mechanism to indicate the target host to the server during the TLS handshake. If the server is identified by a domain name ([[DNS-TERMS](#ref-DNS-TERMS)]), clients MUST send the Server Name Indication (SNI; [[RFC6066](https://datatracker.ietf.org/doc/html/rfc6066)]) TLS extension unless an alternative mechanism to indicate the target host is used. QUIC connections are established as described in [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. During connection establishment, HTTP/3 support is indicated by selecting the ALPN token "h3" in the TLS handshake. Support for other application-layer protocols MAY be offered in the same handshake. While connection-level options pertaining to the core QUIC protocol are set in the initial crypto handshake, settings specific to HTTP/3 are conveyed in the SETTINGS frame. After the QUIC connection is established, a SETTINGS frame MUST be sent by each endpoint as the initial frame of their respective HTTP control stream. ### 3.3. Connection Reuse HTTP/3 connections are persistent across multiple requests. For best performance, it is expected that clients will not close connections until it is determined that no further communication with a server is necessary (for example, when a user navigates away from a particular web page) or until the server closes the connection. Once a connection to a server endpoint exists, this connection MAY be reused for requests with multiple different URI authority components. To use an existing connection for a new origin, clients MUST validate the certificate presented by the server for the new origin server using the process described in Section 4.3.4 of [[HTTP](#ref-HTTP)]. This implies that clients will need to retain the server certificate and any additional information needed to verify that certificate; clients that do not do so will be unable to reuse the connection for additional origins. If the certificate is not acceptable with regard to the new origin for any reason, the connection MUST NOT be reused and a new connection SHOULD be established for the new origin. If the reason the certificate cannot be verified might apply to other origins already associated with the connection, the client SHOULD revalidate the server certificate for those origins. For instance, if validation of a certificate fails because the certificate has expired or been revoked, this might be used to invalidate all other origins for which that certificate was used to establish authority. Clients SHOULD NOT open more than one HTTP/3 connection to a given IP address and UDP port, where the IP address and port might be derived from a URI, a selected alternative service ([[ALTSVC](#ref-ALTSVC)]), a configured proxy, or name resolution of any of these. A client MAY open multiple HTTP/3 connections to the same IP address and UDP port using different transport or TLS configurations but SHOULD avoid creating multiple connections with the same configuration. Servers are encouraged to maintain open HTTP/3 connections for as long as possible but are permitted to terminate idle connections if necessary. When either endpoint chooses to close the HTTP/3 connection, the terminating endpoint SHOULD first send a GOAWAY frame ([Section 5.2](#section-5.2)) so that both endpoints can reliably determine whether previously sent frames have been processed and gracefully complete or terminate any necessary remaining tasks. A server that does not wish clients to reuse HTTP/3 connections for a particular origin can indicate that it is not authoritative for a request by sending a 421 (Misdirected Request) status code in response to the request; see Section 7.4 of [[HTTP](#ref-HTTP)]. 4. Expressing HTTP Semantics in HTTP/3 -------------------------------------- ### 4.1. HTTP Message Framing A client sends an HTTP request on a request stream, which is a client-initiated bidirectional QUIC stream; see [Section 6.1](#section-6.1). A client MUST send only a single request on a given stream. A server sends zero or more interim HTTP responses on the same stream as the request, followed by a single final HTTP response, as detailed below. See Section 15 of [[HTTP](#ref-HTTP)] for a description of interim and final HTTP responses. Pushed responses are sent on a server-initiated unidirectional QUIC stream; see [Section 6.2.2](#section-6.2.2). A server sends zero or more interim HTTP responses, followed by a single final HTTP response, in the same manner as a standard response. Push is described in more detail in [Section 4.6](#section-4.6). On a given stream, receipt of multiple requests or receipt of an additional HTTP response following a final HTTP response MUST be treated as malformed. An HTTP message (request or response) consists of: 1. the header section, including message control data, sent as a single HEADERS frame, 2. optionally, the content, if present, sent as a series of DATA frames, and 3. optionally, the trailer section, if present, sent as a single HEADERS frame. Header and trailer sections are described in Sections [6.3](#section-6.3) and [6.5](#section-6.5) of [[HTTP](#ref-HTTP)]; the content is described in Section 6.4 of [[HTTP](#ref-HTTP)]. Receipt of an invalid sequence of frames MUST be treated as a connection error of type H3\_FRAME\_UNEXPECTED. In particular, a DATA frame before any HEADERS frame, or a HEADERS or DATA frame after the trailing HEADERS frame, is considered invalid. Other frame types, especially unknown frame types, might be permitted subject to their own rules; see [Section 9](#section-9). A server MAY send one or more PUSH\_PROMISE frames before, after, or interleaved with the frames of a response message. These PUSH\_PROMISE frames are not part of the response; see [Section 4.6](#section-4.6) for more details. PUSH\_PROMISE frames are not permitted on push streams; a pushed response that includes PUSH\_PROMISE frames MUST be treated as a connection error of type H3\_FRAME\_UNEXPECTED. Frames of unknown types ([Section 9](#section-9)), including reserved frames ([Section 7.2.8](#section-7.2.8)) MAY be sent on a request or push stream before, after, or interleaved with other frames described in this section. The HEADERS and PUSH\_PROMISE frames might reference updates to the QPACK dynamic table. While these updates are not directly part of the message exchange, they must be received and processed before the message can be consumed. See [Section 4.2](#section-4.2) for more details. Transfer codings (see [Section 7](#section-7) of [HTTP/1.1]) are not defined for HTTP/3; the Transfer-Encoding header field MUST NOT be used. A response MAY consist of multiple messages when and only when one or more interim responses (1xx; see Section 15.2 of [[HTTP](#ref-HTTP)]) precede a final response to the same request. Interim responses do not contain content or trailer sections. An HTTP request/response exchange fully consumes a client-initiated bidirectional QUIC stream. After sending a request, a client MUST close the stream for sending. Unless using the CONNECT method (see [Section 4.4](#section-4.4)), clients MUST NOT make stream closure dependent on receiving a response to their request. After sending a final response, the server MUST close the stream for sending. At this point, the QUIC stream is fully closed. When a stream is closed, this indicates the end of the final HTTP message. Because some messages are large or unbounded, endpoints SHOULD begin processing partial HTTP messages once enough of the message has been received to make progress. If a client-initiated stream terminates without enough of the HTTP message to provide a complete response, the server SHOULD abort its response stream with the error code H3\_REQUEST\_INCOMPLETE. A server can send a complete response prior to the client sending an entire request if the response does not depend on any portion of the request that has not been sent and received. When the server does not need to receive the remainder of the request, it MAY abort reading the request stream, send a complete response, and cleanly close the sending part of the stream. The error code H3\_NO\_ERROR SHOULD be used when requesting that the client stop sending on the request stream. Clients MUST NOT discard complete responses as a result of having their request terminated abruptly, though clients can always discard responses at their discretion for other reasons. If the server sends a partial or complete response but does not abort reading the request, clients SHOULD continue sending the content of the request and close the stream normally. #### 4.1.1. Request Cancellation and Rejection Once a request stream has been opened, the request MAY be cancelled by either endpoint. Clients cancel requests if the response is no longer of interest; servers cancel requests if they are unable to or choose not to respond. When possible, it is RECOMMENDED that servers send an HTTP response with an appropriate status code rather than cancelling a request it has already begun processing. Implementations SHOULD cancel requests by abruptly terminating any directions of a stream that are still open. To do so, an implementation resets the sending parts of streams and aborts reading on the receiving parts of streams; see Section 2.4 of [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. When the server cancels a request without performing any application processing, the request is considered "rejected". The server SHOULD abort its response stream with the error code H3\_REQUEST\_REJECTED. In this context, "processed" means that some data from the stream was passed to some higher layer of software that might have taken some action as a result. The client can treat requests rejected by the server as though they had never been sent at all, thereby allowing them to be retried later. Servers MUST NOT use the H3\_REQUEST\_REJECTED error code for requests that were partially or fully processed. When a server abandons a response after partial processing, it SHOULD abort its response stream with the error code H3\_REQUEST\_CANCELLED. Client SHOULD use the error code H3\_REQUEST\_CANCELLED to cancel requests. Upon receipt of this error code, a server MAY abruptly terminate the response using the error code H3\_REQUEST\_REJECTED if no processing was performed. Clients MUST NOT use the H3\_REQUEST\_REJECTED error code, except when a server has requested closure of the request stream with this error code. If a stream is cancelled after receiving a complete response, the client MAY ignore the cancellation and use the response. However, if a stream is cancelled after receiving a partial response, the response SHOULD NOT be used. Only idempotent actions such as GET, PUT, or DELETE can be safely retried; a client SHOULD NOT automatically retry a request with a non-idempotent method unless it has some means to know that the request semantics are idempotent independent of the method or some means to detect that the original request was never applied. See Section 9.2.2 of [[HTTP](#ref-HTTP)] for more details. #### 4.1.2. Malformed Requests and Responses A malformed request or response is one that is an otherwise valid sequence of frames but is invalid due to: \* the presence of prohibited fields or pseudo-header fields, \* the absence of mandatory pseudo-header fields, \* invalid values for pseudo-header fields, \* pseudo-header fields after fields, \* an invalid sequence of HTTP messages, \* the inclusion of uppercase field names, or \* the inclusion of invalid characters in field names or values. A request or response that is defined as having content when it contains a Content-Length header field (Section 8.6 of [[HTTP](#ref-HTTP)]) is malformed if the value of the Content-Length header field does not equal the sum of the DATA frame lengths received. A response that is defined as never having content, even when a Content-Length is present, can have a non-zero Content-Length header field even though no content is included in DATA frames. Intermediaries that process HTTP requests or responses (i.e., any intermediary not acting as a tunnel) MUST NOT forward a malformed request or response. Malformed requests or responses that are detected MUST be treated as a stream error of type H3\_MESSAGE\_ERROR. For malformed requests, a server MAY send an HTTP response indicating the error prior to closing or resetting the stream. Clients MUST NOT accept a malformed response. Note that these requirements are intended to protect against several types of common attacks against HTTP; they are deliberately strict because being permissive can expose implementations to these vulnerabilities. ### 4.2. HTTP Fields HTTP messages carry metadata as a series of key-value pairs called "HTTP fields"; see Sections [6.3](#section-6.3) and [6.5](#section-6.5) of [[HTTP](#ref-HTTP)]. For a listing of registered HTTP fields, see the "Hypertext Transfer Protocol (HTTP) Field Name Registry" maintained at <[https://www.iana.org/assignments/](https://www.iana.org/assignments/http-fields/) [http-fields/](https://www.iana.org/assignments/http-fields/)>. Like HTTP/2, HTTP/3 has additional considerations related to the use of characters in field names, the Connection header field, and pseudo-header fields. Field names are strings containing a subset of ASCII characters. Properties of HTTP field names and values are discussed in more detail in Section 5.1 of [[HTTP](#ref-HTTP)]. Characters in field names MUST be converted to lowercase prior to their encoding. A request or response containing uppercase characters in field names MUST be treated as malformed. HTTP/3 does not use the Connection header field to indicate connection-specific fields; in this protocol, connection-specific metadata is conveyed by other means. An endpoint MUST NOT generate an HTTP/3 field section containing connection-specific fields; any message containing connection-specific fields MUST be treated as malformed. The only exception to this is the TE header field, which MAY be present in an HTTP/3 request header; when it is, it MUST NOT contain any value other than "trailers". An intermediary transforming an HTTP/1.x message to HTTP/3 MUST remove connection-specific header fields as discussed in Section 7.6.1 of [[HTTP](#ref-HTTP)], or their messages will be treated by other HTTP/3 endpoints as malformed. #### 4.2.1. Field Compression [QPACK] describes a variation of HPACK that gives an encoder some control over how much head-of-line blocking can be caused by compression. This allows an encoder to balance compression efficiency with latency. HTTP/3 uses QPACK to compress header and trailer sections, including the control data present in the header section. To allow for better compression efficiency, the Cookie header field ([[COOKIES](#ref-COOKIES)]) MAY be split into separate field lines, each with one or more cookie-pairs, before compression. If a decompressed field section contains multiple cookie field lines, these MUST be concatenated into a single byte string using the two-byte delimiter of "; " (ASCII 0x3b, 0x20) before being passed into a context other than HTTP/2 or HTTP/3, such as an HTTP/1.1 connection, or a generic HTTP server application. #### 4.2.2. Header Size Constraints An HTTP/3 implementation MAY impose a limit on the maximum size of the message header it will accept on an individual HTTP message. A server that receives a larger header section than it is willing to handle can send an HTTP 431 (Request Header Fields Too Large) status code ([[RFC6585](https://datatracker.ietf.org/doc/html/rfc6585)]). A client can discard responses that it cannot process. The size of a field list is calculated based on the uncompressed size of fields, including the length of the name and value in bytes plus an overhead of 32 bytes for each field. If an implementation wishes to advise its peer of this limit, it can be conveyed as a number of bytes in the SETTINGS\_MAX\_FIELD\_SECTION\_SIZE parameter. An implementation that has received this parameter SHOULD NOT send an HTTP message header that exceeds the indicated size, as the peer will likely refuse to process it. However, an HTTP message can traverse one or more intermediaries before reaching the origin server; see Section 3.7 of [[HTTP](#ref-HTTP)]. Because this limit is applied separately by each implementation that processes the message, messages below this limit are not guaranteed to be accepted. ### 4.3. HTTP Control Data Like HTTP/2, HTTP/3 employs a series of pseudo-header fields, where the field name begins with the : character (ASCII 0x3a). These pseudo-header fields convey message control data; see Section 6.2 of [[HTTP](#ref-HTTP)]. Pseudo-header fields are not HTTP fields. Endpoints MUST NOT generate pseudo-header fields other than those defined in this document. However, an extension could negotiate a modification of this restriction; see [Section 9](#section-9). Pseudo-header fields are only valid in the context in which they are defined. Pseudo-header fields defined for requests MUST NOT appear in responses; pseudo-header fields defined for responses MUST NOT appear in requests. Pseudo-header fields MUST NOT appear in trailer sections. Endpoints MUST treat a request or response that contains undefined or invalid pseudo-header fields as malformed. All pseudo-header fields MUST appear in the header section before regular header fields. Any request or response that contains a pseudo-header field that appears in a header section after a regular header field MUST be treated as malformed. #### 4.3.1. Request Pseudo-Header Fields The following pseudo-header fields are defined for requests: ":method": Contains the HTTP method (Section 9 of [[HTTP](#ref-HTTP)]) ":scheme": Contains the scheme portion of the target URI (Section 3.1 of [[URI](#ref-URI)]). The :scheme pseudo-header is not restricted to URIs with scheme "http" and "https". A proxy or gateway can translate requests for non-HTTP schemes, enabling the use of HTTP to interact with non- HTTP services. See [Section 3.1.2](#section-3.1.2) for guidance on using a scheme other than "https". ":authority": Contains the authority portion of the target URI (Section 3.2 of [[URI](#ref-URI)]). The authority MUST NOT include the deprecated userinfo subcomponent for URIs of scheme "http" or "https". To ensure that the HTTP/1.1 request line can be reproduced accurately, this pseudo-header field MUST be omitted when translating from an HTTP/1.1 request that has a request target in a method-specific form; see Section 7.1 of [[HTTP](#ref-HTTP)]. Clients that generate HTTP/3 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field. An intermediary that converts an HTTP/3 request to HTTP/1.1 MUST create a Host field if one is not present in a request by copying the value of the :authority pseudo-header field. ":path": Contains the path and query parts of the target URI (the "path-absolute" production and optionally a ? character (ASCII 0x3f) followed by the "query" production; see Sections [3.3](#section-3.3) and [3.4](#section-3.4) of [[URI](#ref-URI)]. This pseudo-header field MUST NOT be empty for "http" or "https" URIs; "http" or "https" URIs that do not contain a path component MUST include a value of / (ASCII 0x2f). An OPTIONS request that does not include a path component includes the value \* (ASCII 0x2a) for the :path pseudo-header field; see Section 7.1 of [[HTTP](#ref-HTTP)]. All HTTP/3 requests MUST include exactly one value for the :method, :scheme, and :path pseudo-header fields, unless the request is a CONNECT request; see [Section 4.4](#section-4.4). If the :scheme pseudo-header field identifies a scheme that has a mandatory authority component (including "http" and "https"), the request MUST contain either an :authority pseudo-header field or a Host header field. If these fields are present, they MUST NOT be empty. If both fields are present, they MUST contain the same value. If the scheme does not have a mandatory authority component and none is provided in the request target, the request MUST NOT contain the :authority pseudo-header or Host header fields. An HTTP request that omits mandatory pseudo-header fields or contains invalid values for those pseudo-header fields is malformed. HTTP/3 does not define a way to carry the version identifier that is included in the HTTP/1.1 request line. HTTP/3 requests implicitly have a protocol version of "3.0". #### 4.3.2. Response Pseudo-Header Fields For responses, a single ":status" pseudo-header field is defined that carries the HTTP status code; see Section 15 of [[HTTP](#ref-HTTP)]. This pseudo- header field MUST be included in all responses; otherwise, the response is malformed (see [Section 4.1.2](#section-4.1.2)). HTTP/3 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line. HTTP/3 responses implicitly have a protocol version of "3.0". ### 4.4. The CONNECT Method The CONNECT method requests that the recipient establish a tunnel to the destination origin server identified by the request-target; see Section 9.3.6 of [[HTTP](#ref-HTTP)]. It is primarily used with HTTP proxies to establish a TLS session with an origin server for the purposes of interacting with "https" resources. In HTTP/1.x, CONNECT is used to convert an entire HTTP connection into a tunnel to a remote host. In HTTP/2 and HTTP/3, the CONNECT method is used to establish a tunnel over a single stream. A CONNECT request MUST be constructed as follows: \* The :method pseudo-header field is set to "CONNECT" \* The :scheme and :path pseudo-header fields are omitted \* The :authority pseudo-header field contains the host and port to connect to (equivalent to the authority-form of the request-target of CONNECT requests; see Section 7.1 of [[HTTP](#ref-HTTP)]). The request stream remains open at the end of the request to carry the data to be transferred. A CONNECT request that does not conform to these restrictions is malformed. A proxy that supports CONNECT establishes a TCP connection ([[RFC0793](https://datatracker.ietf.org/doc/html/rfc0793)]) to the server identified in the :authority pseudo-header field. Once this connection is successfully established, the proxy sends a HEADERS frame containing a 2xx series status code to the client, as defined in Section 15.3 of [[HTTP](#ref-HTTP)]. All DATA frames on the stream correspond to data sent or received on the TCP connection. The payload of any DATA frame sent by the client is transmitted by the proxy to the TCP server; data received from the TCP server is packaged into DATA frames by the proxy. Note that the size and number of TCP segments is not guaranteed to map predictably to the size and number of HTTP DATA or QUIC STREAM frames. Once the CONNECT method has completed, only DATA frames are permitted to be sent on the stream. Extension frames MAY be used if specifically permitted by the definition of the extension. Receipt of any other known frame type MUST be treated as a connection error of type H3\_FRAME\_UNEXPECTED. The TCP connection can be closed by either peer. When the client ends the request stream (that is, the receive stream at the proxy enters the "Data Recvd" state), the proxy will set the FIN bit on its connection to the TCP server. When the proxy receives a packet with the FIN bit set, it will close the send stream that it sends to the client. TCP connections that remain half closed in a single direction are not invalid, but are often handled poorly by servers, so clients SHOULD NOT close a stream for sending while they still expect to receive data from the target of the CONNECT. A TCP connection error is signaled by abruptly terminating the stream. A proxy treats any error in the TCP connection, which includes receiving a TCP segment with the RST bit set, as a stream error of type H3\_CONNECT\_ERROR. Correspondingly, if a proxy detects an error with the stream or the QUIC connection, it MUST close the TCP connection. If the proxy detects that the client has reset the stream or aborted reading from the stream, it MUST close the TCP connection. If the stream is reset or reading is aborted by the client, a proxy SHOULD perform the same operation on the other direction in order to ensure that both directions of the stream are cancelled. In all these cases, if the underlying TCP implementation permits it, the proxy SHOULD send a TCP segment with the RST bit set. Since CONNECT creates a tunnel to an arbitrary server, proxies that support CONNECT SHOULD restrict its use to a set of known ports or a list of safe request targets; see Section 9.3.6 of [[HTTP](#ref-HTTP)] for more details. ### 4.5. HTTP Upgrade HTTP/3 does not support the HTTP Upgrade mechanism (Section 7.8 of [[HTTP](#ref-HTTP)]) or the 101 (Switching Protocols) informational status code (Section 15.2.2 of [[HTTP](#ref-HTTP)]). ### 4.6. Server Push Server push is an interaction mode that permits a server to push a request-response exchange to a client in anticipation of the client making the indicated request. This trades off network usage against a potential latency gain. HTTP/3 server push is similar to what is described in [Section 8.2](#section-8.2) of [HTTP/2], but it uses different mechanisms. Each server push is assigned a unique push ID by the server. The push ID is used to refer to the push in various contexts throughout the lifetime of the HTTP/3 connection. The push ID space begins at zero and ends at a maximum value set by the MAX\_PUSH\_ID frame. In particular, a server is not able to push until after the client sends a MAX\_PUSH\_ID frame. A client sends MAX\_PUSH\_ID frames to control the number of pushes that a server can promise. A server SHOULD use push IDs sequentially, beginning from zero. A client MUST treat receipt of a push stream as a connection error of type H3\_ID\_ERROR when no MAX\_PUSH\_ID frame has been sent or when the stream references a push ID that is greater than the maximum push ID. The push ID is used in one or more PUSH\_PROMISE frames that carry the control data and header fields of the request message. These frames are sent on the request stream that generated the push. This allows the server push to be associated with a client request. When the same push ID is promised on multiple request streams, the decompressed request field sections MUST contain the same fields in the same order, and both the name and the value in each field MUST be identical. The push ID is then included with the push stream that ultimately fulfills those promises. The push stream identifies the push ID of the promise that it fulfills, then contains a response to the promised request as described in [Section 4.1](#section-4.1). Finally, the push ID can be used in CANCEL\_PUSH frames; see [Section 7.2.3](#section-7.2.3). Clients use this frame to indicate they do not wish to receive a promised resource. Servers use this frame to indicate they will not be fulfilling a previous promise. Not all requests can be pushed. A server MAY push requests that have the following properties: \* cacheable; see Section 9.2.3 of [[HTTP](#ref-HTTP)] \* safe; see Section 9.2.1 of [[HTTP](#ref-HTTP)] \* does not include request content or a trailer section The server MUST include a value in the :authority pseudo-header field for which the server is authoritative. If the client has not yet validated the connection for the origin indicated by the pushed request, it MUST perform the same verification process it would do before sending a request for that origin on the connection; see [Section 3.3](#section-3.3). If this verification fails, the client MUST NOT consider the server authoritative for that origin. Clients SHOULD send a CANCEL\_PUSH frame upon receipt of a PUSH\_PROMISE frame carrying a request that is not cacheable, is not known to be safe, that indicates the presence of request content, or for which it does not consider the server authoritative. Any corresponding responses MUST NOT be used or cached. Each pushed response is associated with one or more client requests. The push is associated with the request stream on which the PUSH\_PROMISE frame was received. The same server push can be associated with additional client requests using a PUSH\_PROMISE frame with the same push ID on multiple request streams. These associations do not affect the operation of the protocol, but they MAY be considered by user agents when deciding how to use pushed resources. Ordering of a PUSH\_PROMISE frame in relation to certain parts of the response is important. The server SHOULD send PUSH\_PROMISE frames prior to sending HEADERS or DATA frames that reference the promised responses. This reduces the chance that a client requests a resource that will be pushed by the server. Due to reordering, push stream data can arrive before the corresponding PUSH\_PROMISE frame. When a client receives a new push stream with an as-yet-unknown push ID, both the associated client request and the pushed request header fields are unknown. The client can buffer the stream data in expectation of the matching PUSH\_PROMISE. The client can use stream flow control (Section 4.1 of [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]) to limit the amount of data a server may commit to the pushed stream. Clients SHOULD abort reading and discard data already read from push streams if no corresponding PUSH\_PROMISE frame is processed in a reasonable amount of time. Push stream data can also arrive after a client has cancelled a push. In this case, the client can abort reading the stream with an error code of H3\_REQUEST\_CANCELLED. This asks the server not to transfer additional data and indicates that it will be discarded upon receipt. Pushed responses that are cacheable (see Section 3 of [[HTTP-CACHING](#ref-HTTP-CACHING)]) can be stored by the client, if it implements an HTTP cache. Pushed responses are considered successfully validated on the origin server (e.g., if the "no-cache" cache response directive is present; see Section 5.2.2.4 of [[HTTP-CACHING](#ref-HTTP-CACHING)]) at the time the pushed response is received. Pushed responses that are not cacheable MUST NOT be stored by any HTTP cache. They MAY be made available to the application separately. 5. Connection Closure --------------------- Once established, an HTTP/3 connection can be used for many requests and responses over time until the connection is closed. Connection closure can happen in any of several different ways. ### 5.1. Idle Connections Each QUIC endpoint declares an idle timeout during the handshake. If the QUIC connection remains idle (no packets received) for longer than this duration, the peer will assume that the connection has been closed. HTTP/3 implementations will need to open a new HTTP/3 connection for new requests if the existing connection has been idle for longer than the idle timeout negotiated during the QUIC handshake, and they SHOULD do so if approaching the idle timeout; see Section 10.1 of [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. HTTP clients are expected to request that the transport keep connections open while there are responses outstanding for requests or server pushes, as described in Section 10.1.2 of [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. If the client is not expecting a response from the server, allowing an idle connection to time out is preferred over expending effort maintaining a connection that might not be needed. A gateway MAY maintain connections in anticipation of need rather than incur the latency cost of connection establishment to servers. Servers SHOULD NOT actively keep connections open. ### 5.2. Connection Shutdown Even when a connection is not idle, either endpoint can decide to stop using the connection and initiate a graceful connection close. Endpoints initiate the graceful shutdown of an HTTP/3 connection by sending a GOAWAY frame. The GOAWAY frame contains an identifier that indicates to the receiver the range of requests or pushes that were or might be processed in this connection. The server sends a client- initiated bidirectional stream ID; the client sends a push ID. Requests or pushes with the indicated identifier or greater are rejected ([Section 4.1.1](#section-4.1.1)) by the sender of the GOAWAY. This identifier MAY be zero if no requests or pushes were processed. The information in the GOAWAY frame enables a client and server to agree on which requests or pushes were accepted prior to the shutdown of the HTTP/3 connection. Upon sending a GOAWAY frame, the endpoint SHOULD explicitly cancel (see Sections [4.1.1](#section-4.1.1) and [7.2.3](#section-7.2.3)) any requests or pushes that have identifiers greater than or equal to the one indicated, in order to clean up transport state for the affected streams. The endpoint SHOULD continue to do so as more requests or pushes arrive. Endpoints MUST NOT initiate new requests or promise new pushes on the connection after receipt of a GOAWAY frame from the peer. Clients MAY establish a new connection to send additional requests. Some requests or pushes might already be in transit: \* Upon receipt of a GOAWAY frame, if the client has already sent requests with a stream ID greater than or equal to the identifier contained in the GOAWAY frame, those requests will not be processed. Clients can safely retry unprocessed requests on a different HTTP connection. A client that is unable to retry requests loses all requests that are in flight when the server closes the connection. Requests on stream IDs less than the stream ID in a GOAWAY frame from the server might have been processed; their status cannot be known until a response is received, the stream is reset individually, another GOAWAY is received with a lower stream ID than that of the request in question, or the connection terminates. Servers MAY reject individual requests on streams below the indicated ID if these requests were not processed. \* If a server receives a GOAWAY frame after having promised pushes with a push ID greater than or equal to the identifier contained in the GOAWAY frame, those pushes will not be accepted. Servers SHOULD send a GOAWAY frame when the closing of a connection is known in advance, even if the advance notice is small, so that the remote peer can know whether or not a request has been partially processed. For example, if an HTTP client sends a POST at the same time that a server closes a QUIC connection, the client cannot know if the server started to process that POST request if the server does not send a GOAWAY frame to indicate what streams it might have acted on. An endpoint MAY send multiple GOAWAY frames indicating different identifiers, but the identifier in each frame MUST NOT be greater than the identifier in any previous frame, since clients might already have retried unprocessed requests on another HTTP connection. Receiving a GOAWAY containing a larger identifier than previously received MUST be treated as a connection error of type H3\_ID\_ERROR. An endpoint that is attempting to gracefully shut down a connection can send a GOAWAY frame with a value set to the maximum possible value (2^62-4 for servers, 2^62-1 for clients). This ensures that the peer stops creating new requests or pushes. After allowing time for any in-flight requests or pushes to arrive, the endpoint can send another GOAWAY frame indicating which requests or pushes it might accept before the end of the connection. This ensures that a connection can be cleanly shut down without losing requests. A client has more flexibility in the value it chooses for the Push ID field in a GOAWAY that it sends. A value of 2^62-1 indicates that the server can continue fulfilling pushes that have already been promised. A smaller value indicates the client will reject pushes with push IDs greater than or equal to this value. Like the server, the client MAY send subsequent GOAWAY frames so long as the specified push ID is no greater than any previously sent value. Even when a GOAWAY indicates that a given request or push will not be processed or accepted upon receipt, the underlying transport resources still exist. The endpoint that initiated these requests can cancel them to clean up transport state. Once all accepted requests and pushes have been processed, the endpoint can permit the connection to become idle, or it MAY initiate an immediate closure of the connection. An endpoint that completes a graceful shutdown SHOULD use the H3\_NO\_ERROR error code when closing the connection. If a client has consumed all available bidirectional stream IDs with requests, the server need not send a GOAWAY frame, since the client is unable to make further requests. ### 5.3. Immediate Application Closure An HTTP/3 implementation can immediately close the QUIC connection at any time. This results in sending a QUIC CONNECTION\_CLOSE frame to the peer indicating that the application layer has terminated the connection. The application error code in this frame indicates to the peer why the connection is being closed. See [Section 8](#section-8) for error codes that can be used when closing a connection in HTTP/3. Before closing the connection, a GOAWAY frame MAY be sent to allow the client to retry some requests. Including the GOAWAY frame in the same packet as the QUIC CONNECTION\_CLOSE frame improves the chances of the frame being received by clients. If there are open streams that have not been explicitly closed, they are implicitly closed when the connection is closed; see Section 10.2 of [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. ### 5.4. Transport Closure For various reasons, the QUIC transport could indicate to the application layer that the connection has terminated. This might be due to an explicit closure by the peer, a transport-level error, or a change in network topology that interrupts connectivity. If a connection terminates without a GOAWAY frame, clients MUST assume that any request that was sent, whether in whole or in part, might have been processed. 6. Stream Mapping and Usage --------------------------- A QUIC stream provides reliable in-order delivery of bytes, but makes no guarantees about order of delivery with regard to bytes on other streams. In version 1 of QUIC, the stream data containing HTTP frames is carried by QUIC STREAM frames, but this framing is invisible to the HTTP framing layer. The transport layer buffers and orders received stream data, exposing a reliable byte stream to the application. Although QUIC permits out-of-order delivery within a stream, HTTP/3 does not make use of this feature. QUIC streams can be either unidirectional, carrying data only from initiator to receiver, or bidirectional, carrying data in both directions. Streams can be initiated by either the client or the server. For more detail on QUIC streams, see Section 2 of [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. When HTTP fields and data are sent over QUIC, the QUIC layer handles most of the stream management. HTTP does not need to do any separate multiplexing when using QUIC: data sent over a QUIC stream always maps to a particular HTTP transaction or to the entire HTTP/3 connection context. ### 6.1. Bidirectional Streams All client-initiated bidirectional streams are used for HTTP requests and responses. A bidirectional stream ensures that the response can be readily correlated with the request. These streams are referred to as request streams. This means that the client's first request occurs on QUIC stream 0, with subsequent requests on streams 4, 8, and so on. In order to permit these streams to open, an HTTP/3 server SHOULD configure non- zero minimum values for the number of permitted streams and the initial stream flow-control window. So as to not unnecessarily limit parallelism, at least 100 request streams SHOULD be permitted at a time. HTTP/3 does not use server-initiated bidirectional streams, though an extension could define a use for these streams. Clients MUST treat receipt of a server-initiated bidirectional stream as a connection error of type H3\_STREAM\_CREATION\_ERROR unless such an extension has been negotiated. ### 6.2. Unidirectional Streams Unidirectional streams, in either direction, are used for a range of purposes. The purpose is indicated by a stream type, which is sent as a variable-length integer at the start of the stream. The format and structure of data that follows this integer is determined by the stream type. Unidirectional Stream Header { Stream Type (i), } Figure 1: Unidirectional Stream Header Two stream types are defined in this document: control streams ([Section 6.2.1](#section-6.2.1)) and push streams ([Section 6.2.2](#section-6.2.2)). [[QPACK](#ref-QPACK)] defines two additional stream types. Other stream types can be defined by extensions to HTTP/3; see [Section 9](#section-9) for more details. Some stream types are reserved ([Section 6.2.3](#section-6.2.3)). The performance of HTTP/3 connections in the early phase of their lifetime is sensitive to the creation and exchange of data on unidirectional streams. Endpoints that excessively restrict the number of streams or the flow-control window of these streams will increase the chance that the remote peer reaches the limit early and becomes blocked. In particular, implementations should consider that remote peers may wish to exercise reserved stream behavior ([Section 6.2.3](#section-6.2.3)) with some of the unidirectional streams they are permitted to use. Each endpoint needs to create at least one unidirectional stream for the HTTP control stream. QPACK requires two additional unidirectional streams, and other extensions might require further streams. Therefore, the transport parameters sent by both clients and servers MUST allow the peer to create at least three unidirectional streams. These transport parameters SHOULD also provide at least 1,024 bytes of flow-control credit to each unidirectional stream. Note that an endpoint is not required to grant additional credits to create more unidirectional streams if its peer consumes all the initial credits before creating the critical unidirectional streams. Endpoints SHOULD create the HTTP control stream as well as the unidirectional streams required by mandatory extensions (such as the QPACK encoder and decoder streams) first, and then create additional streams as allowed by their peer. If the stream header indicates a stream type that is not supported by the recipient, the remainder of the stream cannot be consumed as the semantics are unknown. Recipients of unknown stream types MUST either abort reading of the stream or discard incoming data without further processing. If reading is aborted, the recipient SHOULD use the H3\_STREAM\_CREATION\_ERROR error code or a reserved error code ([Section 8.1](#section-8.1)). The recipient MUST NOT consider unknown stream types to be a connection error of any kind. As certain stream types can affect connection state, a recipient SHOULD NOT discard data from incoming unidirectional streams prior to reading the stream type. Implementations MAY send stream types before knowing whether the peer supports them. However, stream types that could modify the state or semantics of existing protocol components, including QPACK or other extensions, MUST NOT be sent until the peer is known to support them. A sender can close or reset a unidirectional stream unless otherwise specified. A receiver MUST tolerate unidirectional streams being closed or reset prior to the reception of the unidirectional stream header. #### 6.2.1. Control Streams A control stream is indicated by a stream type of 0x00. Data on this stream consists of HTTP/3 frames, as defined in [Section 7.2](#section-7.2). Each side MUST initiate a single control stream at the beginning of the connection and send its SETTINGS frame as the first frame on this stream. If the first frame of the control stream is any other frame type, this MUST be treated as a connection error of type H3\_MISSING\_SETTINGS. Only one control stream per peer is permitted; receipt of a second stream claiming to be a control stream MUST be treated as a connection error of type H3\_STREAM\_CREATION\_ERROR. The sender MUST NOT close the control stream, and the receiver MUST NOT request that the sender close the control stream. If either control stream is closed at any point, this MUST be treated as a connection error of type H3\_CLOSED\_CRITICAL\_STREAM. Connection errors are described in [Section 8](#section-8). Because the contents of the control stream are used to manage the behavior of other streams, endpoints SHOULD provide enough flow- control credit to keep the peer's control stream from becoming blocked. A pair of unidirectional streams is used rather than a single bidirectional stream. This allows either peer to send data as soon as it is able. Depending on whether 0-RTT is available on the QUIC connection, either client or server might be able to send stream data first. #### 6.2.2. Push Streams Server push is an optional feature introduced in HTTP/2 that allows a server to initiate a response before a request has been made. See [Section 4.6](#section-4.6) for more details. A push stream is indicated by a stream type of 0x01, followed by the push ID of the promise that it fulfills, encoded as a variable-length integer. The remaining data on this stream consists of HTTP/3 frames, as defined in [Section 7.2](#section-7.2), and fulfills a promised server push by zero or more interim HTTP responses followed by a single final HTTP response, as defined in [Section 4.1](#section-4.1). Server push and push IDs are described in [Section 4.6](#section-4.6). Only servers can push; if a server receives a client-initiated push stream, this MUST be treated as a connection error of type H3\_STREAM\_CREATION\_ERROR. Push Stream Header { Stream Type (i) = 0x01, Push ID (i), } Figure 2: Push Stream Header A client SHOULD NOT abort reading on a push stream prior to reading the push stream header, as this could lead to disagreement between client and server on which push IDs have already been consumed. Each push ID MUST only be used once in a push stream header. If a client detects that a push stream header includes a push ID that was used in another push stream header, the client MUST treat this as a connection error of type H3\_ID\_ERROR. #### 6.2.3. Reserved Stream Types Stream types of the format 0x1f \* N + 0x21 for non-negative integer values of N are reserved to exercise the requirement that unknown types be ignored. These streams have no semantics, and they can be sent when application-layer padding is desired. They MAY also be sent on connections where no data is currently being transferred. Endpoints MUST NOT consider these streams to have any meaning upon receipt. The payload and length of the stream are selected in any manner the sending implementation chooses. When sending a reserved stream type, the implementation MAY either terminate the stream cleanly or reset it. When resetting the stream, either the H3\_NO\_ERROR error code or a reserved error code ([Section 8.1](#section-8.1)) SHOULD be used. 7. HTTP Framing Layer --------------------- HTTP frames are carried on QUIC streams, as described in [Section 6](#section-6). HTTP/3 defines three stream types: control stream, request stream, and push stream. This section describes HTTP/3 frame formats and their permitted stream types; see Table 1 for an overview. A comparison between HTTP/2 and HTTP/3 frames is provided in [Appendix A.2](#appendix-A.2). +==============+================+================+========+=========+ | Frame | Control Stream | Request | Push | Section | | | | Stream | Stream | | +==============+================+================+========+=========+ | DATA | No | Yes | Yes | Section | | | | | | 7.2.1 | +--------------+----------------+----------------+--------+---------+ | HEADERS | No | Yes | Yes | Section | | | | | | 7.2.2 | +--------------+----------------+----------------+--------+---------+ | CANCEL\_PUSH | Yes | No | No | Section | | | | | | 7.2.3 | +--------------+----------------+----------------+--------+---------+ | SETTINGS | Yes (1) | No | No | Section | | | | | | 7.2.4 | +--------------+----------------+----------------+--------+---------+ | PUSH\_PROMISE | No | Yes | No | Section | | | | | | 7.2.5 | +--------------+----------------+----------------+--------+---------+ | GOAWAY | Yes | No | No | Section | | | | | | 7.2.6 | +--------------+----------------+----------------+--------+---------+ | MAX\_PUSH\_ID | Yes | No | No | Section | | | | | | 7.2.7 | +--------------+----------------+----------------+--------+---------+ | Reserved | Yes | Yes | Yes | Section | | | | | | 7.2.8 | +--------------+----------------+----------------+--------+---------+ Table 1: HTTP/3 Frames and Stream Type Overview The SETTINGS frame can only occur as the first frame of a Control stream; this is indicated in Table 1 with a (1). Specific guidance is provided in the relevant section. Note that, unlike QUIC frames, HTTP/3 frames can span multiple packets. ### 7.1. Frame Layout All frames have the following format: HTTP/3 Frame Format { Type (i), Length (i), Frame Payload (..), } Figure 3: HTTP/3 Frame Format A frame includes the following fields: Type: A variable-length integer that identifies the frame type. Length: A variable-length integer that describes the length in bytes of the Frame Payload. Frame Payload: A payload, the semantics of which are determined by the Type field. Each frame's payload MUST contain exactly the fields identified in its description. A frame payload that contains additional bytes after the identified fields or a frame payload that terminates before the end of the identified fields MUST be treated as a connection error of type H3\_FRAME\_ERROR. In particular, redundant length encodings MUST be verified to be self-consistent; see [Section 10.8](#section-10.8). When a stream terminates cleanly, if the last frame on the stream was truncated, this MUST be treated as a connection error of type H3\_FRAME\_ERROR. Streams that terminate abruptly may be reset at any point in a frame. ### 7.2. Frame Definitions #### 7.2.1. DATA DATA frames (type=0x00) convey arbitrary, variable-length sequences of bytes associated with HTTP request or response content. DATA frames MUST be associated with an HTTP request or response. If a DATA frame is received on a control stream, the recipient MUST respond with a connection error of type H3\_FRAME\_UNEXPECTED. DATA Frame { Type (i) = 0x00, Length (i), Data (..), } Figure 4: DATA Frame #### 7.2.2. HEADERS The HEADERS frame (type=0x01) is used to carry an HTTP field section that is encoded using QPACK. See [[QPACK](#ref-QPACK)] for more details. HEADERS Frame { Type (i) = 0x01, Length (i), Encoded Field Section (..), } Figure 5: HEADERS Frame HEADERS frames can only be sent on request streams or push streams. If a HEADERS frame is received on a control stream, the recipient MUST respond with a connection error of type H3\_FRAME\_UNEXPECTED. #### 7.2.3. CANCEL\_PUSH The CANCEL\_PUSH frame (type=0x03) is used to request cancellation of a server push prior to the push stream being received. The CANCEL\_PUSH frame identifies a server push by push ID (see [Section 4.6](#section-4.6)), encoded as a variable-length integer. When a client sends a CANCEL\_PUSH frame, it is indicating that it does not wish to receive the promised resource. The server SHOULD abort sending the resource, but the mechanism to do so depends on the state of the corresponding push stream. If the server has not yet created a push stream, it does not create one. If the push stream is open, the server SHOULD abruptly terminate that stream. If the push stream has already ended, the server MAY still abruptly terminate the stream or MAY take no action. A server sends a CANCEL\_PUSH frame to indicate that it will not be fulfilling a promise that was previously sent. The client cannot expect the corresponding promise to be fulfilled, unless it has already received and processed the promised response. Regardless of whether a push stream has been opened, a server SHOULD send a CANCEL\_PUSH frame when it determines that promise will not be fulfilled. If a stream has already been opened, the server can abort sending on the stream with an error code of H3\_REQUEST\_CANCELLED. Sending a CANCEL\_PUSH frame has no direct effect on the state of existing push streams. A client SHOULD NOT send a CANCEL\_PUSH frame when it has already received a corresponding push stream. A push stream could arrive after a client has sent a CANCEL\_PUSH frame, because a server might not have processed the CANCEL\_PUSH. The client SHOULD abort reading the stream with an error code of H3\_REQUEST\_CANCELLED. A CANCEL\_PUSH frame is sent on the control stream. Receiving a CANCEL\_PUSH frame on a stream other than the control stream MUST be treated as a connection error of type H3\_FRAME\_UNEXPECTED. CANCEL\_PUSH Frame { Type (i) = 0x03, Length (i), Push ID (i), } Figure 6: CANCEL\_PUSH Frame The CANCEL\_PUSH frame carries a push ID encoded as a variable-length integer. The Push ID field identifies the server push that is being cancelled; see [Section 4.6](#section-4.6). If a CANCEL\_PUSH frame is received that references a push ID greater than currently allowed on the connection, this MUST be treated as a connection error of type H3\_ID\_ERROR. If the client receives a CANCEL\_PUSH frame, that frame might identify a push ID that has not yet been mentioned by a PUSH\_PROMISE frame due to reordering. If a server receives a CANCEL\_PUSH frame for a push ID that has not yet been mentioned by a PUSH\_PROMISE frame, this MUST be treated as a connection error of type H3\_ID\_ERROR. #### 7.2.4. SETTINGS The SETTINGS frame (type=0x04) conveys configuration parameters that affect how endpoints communicate, such as preferences and constraints on peer behavior. Individually, a SETTINGS parameter can also be referred to as a "setting"; the identifier and value of each setting parameter can be referred to as a "setting identifier" and a "setting value". SETTINGS frames always apply to an entire HTTP/3 connection, never a single stream. A SETTINGS frame MUST be sent as the first frame of each control stream (see [Section 6.2.1](#section-6.2.1)) by each peer, and it MUST NOT be sent subsequently. If an endpoint receives a second SETTINGS frame on the control stream, the endpoint MUST respond with a connection error of type H3\_FRAME\_UNEXPECTED. SETTINGS frames MUST NOT be sent on any stream other than the control stream. If an endpoint receives a SETTINGS frame on a different stream, the endpoint MUST respond with a connection error of type H3\_FRAME\_UNEXPECTED. SETTINGS parameters are not negotiated; they describe characteristics of the sending peer that can be used by the receiving peer. However, a negotiation can be implied by the use of SETTINGS: each peer uses SETTINGS to advertise a set of supported values. The definition of the setting would describe how each peer combines the two sets to conclude which choice will be used. SETTINGS does not provide a mechanism to identify when the choice takes effect. Different values for the same parameter can be advertised by each peer. For example, a client might be willing to consume a very large response field section, while servers are more cautious about request size. The same setting identifier MUST NOT occur more than once in the SETTINGS frame. A receiver MAY treat the presence of duplicate setting identifiers as a connection error of type H3\_SETTINGS\_ERROR. The payload of a SETTINGS frame consists of zero or more parameters. Each parameter consists of a setting identifier and a value, both encoded as QUIC variable-length integers. Setting { Identifier (i), Value (i), } SETTINGS Frame { Type (i) = 0x04, Length (i), Setting (..) ..., } Figure 7: SETTINGS Frame An implementation MUST ignore any parameter with an identifier it does not understand. ##### 7.2.4.1. Defined SETTINGS Parameters The following settings are defined in HTTP/3: SETTINGS\_MAX\_FIELD\_SECTION\_SIZE (0x06): The default value is unlimited. See [Section 4.2.2](#section-4.2.2) for usage. Setting identifiers of the format 0x1f \* N + 0x21 for non-negative integer values of N are reserved to exercise the requirement that unknown identifiers be ignored. Such settings have no defined meaning. Endpoints SHOULD include at least one such setting in their SETTINGS frame. Endpoints MUST NOT consider such settings to have any meaning upon receipt. Because the setting has no defined meaning, the value of the setting can be any value the implementation selects. Setting identifiers that were defined in [HTTP/2] where there is no corresponding HTTP/3 setting have also been reserved ([Section 11.2.2](#section-11.2.2)). These reserved settings MUST NOT be sent, and their receipt MUST be treated as a connection error of type H3\_SETTINGS\_ERROR. Additional settings can be defined by extensions to HTTP/3; see [Section 9](#section-9) for more details. ##### 7.2.4.2. Initialization An HTTP implementation MUST NOT send frames or requests that would be invalid based on its current understanding of the peer's settings. All settings begin at an initial value. Each endpoint SHOULD use these initial values to send messages before the peer's SETTINGS frame has arrived, as packets carrying the settings can be lost or delayed. When the SETTINGS frame arrives, any settings are changed to their new values. This removes the need to wait for the SETTINGS frame before sending messages. Endpoints MUST NOT require any data to be received from the peer prior to sending the SETTINGS frame; settings MUST be sent as soon as the transport is ready to send data. For servers, the initial value of each client setting is the default value. For clients using a 1-RTT QUIC connection, the initial value of each server setting is the default value. 1-RTT keys will always become available prior to the packet containing SETTINGS being processed by QUIC, even if the server sends SETTINGS immediately. Clients SHOULD NOT wait indefinitely for SETTINGS to arrive before sending requests, but they SHOULD process received datagrams in order to increase the likelihood of processing SETTINGS before sending the first request. When a 0-RTT QUIC connection is being used, the initial value of each server setting is the value used in the previous session. Clients SHOULD store the settings the server provided in the HTTP/3 connection where resumption information was provided, but they MAY opt not to store settings in certain cases (e.g., if the session ticket is received before the SETTINGS frame). A client MUST comply with stored settings -- or default values if no values are stored -- when attempting 0-RTT. Once a server has provided new settings, clients MUST comply with those values. A server can remember the settings that it advertised or store an integrity-protected copy of the values in the ticket and recover the information when accepting 0-RTT data. A server uses the HTTP/3 settings values in determining whether to accept 0-RTT data. If the server cannot determine that the settings remembered by a client are compatible with its current settings, it MUST NOT accept 0-RTT data. Remembered settings are compatible if a client complying with those settings would not violate the server's current settings. A server MAY accept 0-RTT and subsequently provide different settings in its SETTINGS frame. If 0-RTT data is accepted by the server, its SETTINGS frame MUST NOT reduce any limits or alter any values that might be violated by the client with its 0-RTT data. The server MUST include all settings that differ from their default values. If a server accepts 0-RTT but then sends settings that are not compatible with the previously specified settings, this MUST be treated as a connection error of type H3\_SETTINGS\_ERROR. If a server accepts 0-RTT but then sends a SETTINGS frame that omits a setting value that the client understands (apart from reserved setting identifiers) that was previously specified to have a non-default value, this MUST be treated as a connection error of type H3\_SETTINGS\_ERROR. #### 7.2.5. PUSH\_PROMISE The PUSH\_PROMISE frame (type=0x05) is used to carry a promised request header section from server to client on a request stream. PUSH\_PROMISE Frame { Type (i) = 0x05, Length (i), Push ID (i), Encoded Field Section (..), } Figure 8: PUSH\_PROMISE Frame The payload consists of: Push ID: A variable-length integer that identifies the server push operation. A push ID is used in push stream headers ([Section 4.6](#section-4.6)) and CANCEL\_PUSH frames. Encoded Field Section: QPACK-encoded request header fields for the promised response. See [[QPACK](#ref-QPACK)] for more details. A server MUST NOT use a push ID that is larger than the client has provided in a MAX\_PUSH\_ID frame ([Section 7.2.7](#section-7.2.7)). A client MUST treat receipt of a PUSH\_PROMISE frame that contains a larger push ID than the client has advertised as a connection error of H3\_ID\_ERROR. A server MAY use the same push ID in multiple PUSH\_PROMISE frames. If so, the decompressed request header sets MUST contain the same fields in the same order, and both the name and the value in each field MUST be exact matches. Clients SHOULD compare the request header sections for resources promised multiple times. If a client receives a push ID that has already been promised and detects a mismatch, it MUST respond with a connection error of type H3\_GENERAL\_PROTOCOL\_ERROR. If the decompressed field sections match exactly, the client SHOULD associate the pushed content with each stream on which a PUSH\_PROMISE frame was received. Allowing duplicate references to the same push ID is primarily to reduce duplication caused by concurrent requests. A server SHOULD avoid reusing a push ID over a long period. Clients are likely to consume server push responses and not retain them for reuse over time. Clients that see a PUSH\_PROMISE frame that uses a push ID that they have already consumed and discarded are forced to ignore the promise. If a PUSH\_PROMISE frame is received on the control stream, the client MUST respond with a connection error of type H3\_FRAME\_UNEXPECTED. A client MUST NOT send a PUSH\_PROMISE frame. A server MUST treat the receipt of a PUSH\_PROMISE frame as a connection error of type H3\_FRAME\_UNEXPECTED. See [Section 4.6](#section-4.6) for a description of the overall server push mechanism. #### 7.2.6. GOAWAY The GOAWAY frame (type=0x07) is used to initiate graceful shutdown of an HTTP/3 connection by either endpoint. GOAWAY allows an endpoint to stop accepting new requests or pushes while still finishing processing of previously received requests and pushes. This enables administrative actions, like server maintenance. GOAWAY by itself does not close a connection. GOAWAY Frame { Type (i) = 0x07, Length (i), Stream ID/Push ID (i), } Figure 9: GOAWAY Frame The GOAWAY frame is always sent on the control stream. In the server-to-client direction, it carries a QUIC stream ID for a client- initiated bidirectional stream encoded as a variable-length integer. A client MUST treat receipt of a GOAWAY frame containing a stream ID of any other type as a connection error of type H3\_ID\_ERROR. In the client-to-server direction, the GOAWAY frame carries a push ID encoded as a variable-length integer. The GOAWAY frame applies to the entire connection, not a specific stream. A client MUST treat a GOAWAY frame on a stream other than the control stream as a connection error of type H3\_FRAME\_UNEXPECTED. See [Section 5.2](#section-5.2) for more information on the use of the GOAWAY frame. #### 7.2.7. MAX\_PUSH\_ID The MAX\_PUSH\_ID frame (type=0x0d) is used by clients to control the number of server pushes that the server can initiate. This sets the maximum value for a push ID that the server can use in PUSH\_PROMISE and CANCEL\_PUSH frames. Consequently, this also limits the number of push streams that the server can initiate in addition to the limit maintained by the QUIC transport. The MAX\_PUSH\_ID frame is always sent on the control stream. Receipt of a MAX\_PUSH\_ID frame on any other stream MUST be treated as a connection error of type H3\_FRAME\_UNEXPECTED. A server MUST NOT send a MAX\_PUSH\_ID frame. A client MUST treat the receipt of a MAX\_PUSH\_ID frame as a connection error of type H3\_FRAME\_UNEXPECTED. The maximum push ID is unset when an HTTP/3 connection is created, meaning that a server cannot push until it receives a MAX\_PUSH\_ID frame. A client that wishes to manage the number of promised server pushes can increase the maximum push ID by sending MAX\_PUSH\_ID frames as the server fulfills or cancels server pushes. MAX\_PUSH\_ID Frame { Type (i) = 0x0d, Length (i), Push ID (i), } Figure 10: MAX\_PUSH\_ID Frame The MAX\_PUSH\_ID frame carries a single variable-length integer that identifies the maximum value for a push ID that the server can use; see [Section 4.6](#section-4.6). A MAX\_PUSH\_ID frame cannot reduce the maximum push ID; receipt of a MAX\_PUSH\_ID frame that contains a smaller value than previously received MUST be treated as a connection error of type H3\_ID\_ERROR. #### 7.2.8. Reserved Frame Types Frame types of the format 0x1f \* N + 0x21 for non-negative integer values of N are reserved to exercise the requirement that unknown types be ignored ([Section 9](#section-9)). These frames have no semantics, and they MAY be sent on any stream where frames are allowed to be sent. This enables their use for application-layer padding. Endpoints MUST NOT consider these frames to have any meaning upon receipt. The payload and length of the frames are selected in any manner the implementation chooses. Frame types that were used in HTTP/2 where there is no corresponding HTTP/3 frame have also been reserved ([Section 11.2.1](#section-11.2.1)). These frame types MUST NOT be sent, and their receipt MUST be treated as a connection error of type H3\_FRAME\_UNEXPECTED. 8. Error Handling ----------------- When a stream cannot be completed successfully, QUIC allows the application to abruptly terminate (reset) that stream and communicate a reason; see Section 2.4 of [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. This is referred to as a "stream error". An HTTP/3 implementation can decide to close a QUIC stream and communicate the type of error. Wire encodings of error codes are defined in [Section 8.1](#section-8.1). Stream errors are distinct from HTTP status codes that indicate error conditions. Stream errors indicate that the sender did not transfer or consume the full request or response, while HTTP status codes indicate the result of a request that was successfully received. If an entire connection needs to be terminated, QUIC similarly provides mechanisms to communicate a reason; see Section 5.3 of [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. This is referred to as a "connection error". Similar to stream errors, an HTTP/3 implementation can terminate a QUIC connection and communicate the reason using an error code from [Section 8.1](#section-8.1). Although the reasons for closing streams and connections are called "errors", these actions do not necessarily indicate a problem with the connection or either implementation. For example, a stream can be reset if the requested resource is no longer needed. An endpoint MAY choose to treat a stream error as a connection error under certain circumstances, closing the entire connection in response to a condition on a single stream. Implementations need to consider the impact on outstanding requests before making this choice. Because new error codes can be defined without negotiation (see [Section 9](#section-9)), use of an error code in an unexpected context or receipt of an unknown error code MUST be treated as equivalent to H3\_NO\_ERROR. However, closing a stream can have other effects regardless of the error code; for example, see [Section 4.1](#section-4.1). ### 8.1. HTTP/3 Error Codes The following error codes are defined for use when abruptly terminating streams, aborting reading of streams, or immediately closing HTTP/3 connections. H3\_NO\_ERROR (0x0100): No error. This is used when the connection or stream needs to be closed, but there is no error to signal. H3\_GENERAL\_PROTOCOL\_ERROR (0x0101): Peer violated protocol requirements in a way that does not match a more specific error code or endpoint declines to use the more specific error code. H3\_INTERNAL\_ERROR (0x0102): An internal error has occurred in the HTTP stack. H3\_STREAM\_CREATION\_ERROR (0x0103): The endpoint detected that its peer created a stream that it will not accept. H3\_CLOSED\_CRITICAL\_STREAM (0x0104): A stream required by the HTTP/3 connection was closed or reset. H3\_FRAME\_UNEXPECTED (0x0105): A frame was received that was not permitted in the current state or on the current stream. H3\_FRAME\_ERROR (0x0106): A frame that fails to satisfy layout requirements or with an invalid size was received. H3\_EXCESSIVE\_LOAD (0x0107): The endpoint detected that its peer is exhibiting a behavior that might be generating excessive load. H3\_ID\_ERROR (0x0108): A stream ID or push ID was used incorrectly, such as exceeding a limit, reducing a limit, or being reused. H3\_SETTINGS\_ERROR (0x0109): An endpoint detected an error in the payload of a SETTINGS frame. H3\_MISSING\_SETTINGS (0x010a): No SETTINGS frame was received at the beginning of the control stream. H3\_REQUEST\_REJECTED (0x010b): A server rejected a request without performing any application processing. H3\_REQUEST\_CANCELLED (0x010c): The request or its response (including pushed response) is cancelled. H3\_REQUEST\_INCOMPLETE (0x010d): The client's stream terminated without containing a fully formed request. H3\_MESSAGE\_ERROR (0x010e): An HTTP message was malformed and cannot be processed. H3\_CONNECT\_ERROR (0x010f): The TCP connection established in response to a CONNECT request was reset or abnormally closed. H3\_VERSION\_FALLBACK (0x0110): The requested operation cannot be served over HTTP/3. The peer should retry over HTTP/1.1. Error codes of the format 0x1f \* N + 0x21 for non-negative integer values of N are reserved to exercise the requirement that unknown error codes be treated as equivalent to H3\_NO\_ERROR ([Section 9](#section-9)). Implementations SHOULD select an error code from this space with some probability when they would have sent H3\_NO\_ERROR. 9. Extensions to HTTP/3 ----------------------- HTTP/3 permits extension of the protocol. Within the limitations described in this section, protocol extensions can be used to provide additional services or alter any aspect of the protocol. Extensions are effective only within the scope of a single HTTP/3 connection. This applies to the protocol elements defined in this document. This does not affect the existing options for extending HTTP, such as defining new methods, status codes, or fields. Extensions are permitted to use new frame types ([Section 7.2](#section-7.2)), new settings ([Section 7.2.4.1](#section-7.2.4.1)), new error codes ([Section 8](#section-8)), or new unidirectional stream types ([Section 6.2](#section-6.2)). Registries are established for managing these extension points: frame types ([Section 11.2.1](#section-11.2.1)), settings ([Section 11.2.2](#section-11.2.2)), error codes ([Section 11.2.3](#section-11.2.3)), and stream types ([Section 11.2.4](#section-11.2.4)). Implementations MUST ignore unknown or unsupported values in all extensible protocol elements. Implementations MUST discard data or abort reading on unidirectional streams that have unknown or unsupported types. This means that any of these extension points can be safely used by extensions without prior arrangement or negotiation. However, where a known frame type is required to be in a specific location, such as the SETTINGS frame as the first frame of the control stream (see [Section 6.2.1](#section-6.2.1)), an unknown frame type does not satisfy that requirement and SHOULD be treated as an error. Extensions that could change the semantics of existing protocol components MUST be negotiated before being used. For example, an extension that changes the layout of the HEADERS frame cannot be used until the peer has given a positive signal that this is acceptable. Coordinating when such a revised layout comes into effect could prove complex. As such, allocating new identifiers for new definitions of existing protocol elements is likely to be more effective. This document does not mandate a specific method for negotiating the use of an extension, but it notes that a setting ([Section 7.2.4.1](#section-7.2.4.1)) could be used for that purpose. If both peers set a value that indicates willingness to use the extension, then the extension can be used. If a setting is used for extension negotiation, the default value MUST be defined in such a fashion that the extension is disabled if the setting is omitted. 10. Security Considerations --------------------------- The security considerations of HTTP/3 should be comparable to those of HTTP/2 with TLS. However, many of the considerations from [Section 10](#section-10) of [HTTP/2] apply to [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)] and are discussed in that document. ### 10.1. Server Authority HTTP/3 relies on the HTTP definition of authority. The security considerations of establishing authority are discussed in Section 17.1 of [[HTTP](#ref-HTTP)]. ### 10.2. Cross-Protocol Attacks The use of ALPN in the TLS and QUIC handshakes establishes the target application protocol before application-layer bytes are processed. This ensures that endpoints have strong assurances that peers are using the same protocol. This does not guarantee protection from all cross-protocol attacks. Section 21.5 of [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)] describes some ways in which the plaintext of QUIC packets can be used to perform request forgery against endpoints that don't use authenticated transports. ### 10.3. Intermediary-Encapsulation Attacks The HTTP/3 field encoding allows the expression of names that are not valid field names in the syntax used by HTTP (Section 5.1 of [[HTTP](#ref-HTTP)]). Requests or responses containing invalid field names MUST be treated as malformed. Therefore, an intermediary cannot translate an HTTP/3 request or response containing an invalid field name into an HTTP/1.1 message. Similarly, HTTP/3 can transport field values that are not valid. While most values that can be encoded will not alter field parsing, carriage return (ASCII 0x0d), line feed (ASCII 0x0a), and the null character (ASCII 0x00) might be exploited by an attacker if they are translated verbatim. Any request or response that contains a character not permitted in a field value MUST be treated as malformed. Valid characters are defined by the "field-content" ABNF rule in Section 5.5 of [[HTTP](#ref-HTTP)]. ### 10.4. Cacheability of Pushed Responses Pushed responses do not have an explicit request from the client; the request is provided by the server in the PUSH\_PROMISE frame. Caching responses that are pushed is possible based on the guidance provided by the origin server in the Cache-Control header field. However, this can cause issues if a single server hosts more than one tenant. For example, a server might offer multiple users each a small portion of its URI space. Where multiple tenants share space on the same server, that server MUST ensure that tenants are not able to push representations of resources that they do not have authority over. Failure to enforce this would allow a tenant to provide a representation that would be served out of cache, overriding the actual representation that the authoritative tenant provides. Clients are required to reject pushed responses for which an origin server is not authoritative; see [Section 4.6](#section-4.6). ### 10.5. Denial-of-Service Considerations An HTTP/3 connection can demand a greater commitment of resources to operate than an HTTP/1.1 or HTTP/2 connection. The use of field compression and flow control depend on a commitment of resources for storing a greater amount of state. Settings for these features ensure that memory commitments for these features are strictly bounded. The number of PUSH\_PROMISE frames is constrained in a similar fashion. A client that accepts server push SHOULD limit the number of push IDs it issues at a time. Processing capacity cannot be guarded as effectively as state capacity. The ability to send undefined protocol elements that the peer is required to ignore can be abused to cause a peer to expend additional processing time. This might be done by setting multiple undefined SETTINGS parameters, unknown frame types, or unknown stream types. Note, however, that some uses are entirely legitimate, such as optional-to-understand extensions and padding to increase resistance to traffic analysis. Compression of field sections also offers some opportunities to waste processing resources; see Section 7 of [[QPACK](#ref-QPACK)] for more details on potential abuses. All these features -- i.e., server push, unknown protocol elements, field compression -- have legitimate uses. These features become a burden only when they are used unnecessarily or to excess. An endpoint that does not monitor such behavior exposes itself to a risk of denial-of-service attack. Implementations SHOULD track the use of these features and set limits on their use. An endpoint MAY treat activity that is suspicious as a connection error of type H3\_EXCESSIVE\_LOAD, but false positives will result in disrupting valid connections and requests. #### 10.5.1. Limits on Field Section Size A large field section ([Section 4.1](#section-4.1)) can cause an implementation to commit a large amount of state. Header fields that are critical for routing can appear toward the end of a header section, which prevents streaming of the header section to its ultimate destination. This ordering and other reasons, such as ensuring cache correctness, mean that an endpoint likely needs to buffer the entire header section. Since there is no hard limit to the size of a field section, some endpoints could be forced to commit a large amount of available memory for header fields. An endpoint can use the SETTINGS\_MAX\_FIELD\_SECTION\_SIZE ([Section 4.2.2](#section-4.2.2)) setting to advise peers of limits that might apply on the size of field sections. This setting is only advisory, so endpoints MAY choose to send field sections that exceed this limit and risk having the request or response being treated as malformed. This setting is specific to an HTTP/3 connection, so any request or response could encounter a hop with a lower, unknown limit. An intermediary can attempt to avoid this problem by passing on values presented by different peers, but they are not obligated to do so. A server that receives a larger field section than it is willing to handle can send an HTTP 431 (Request Header Fields Too Large) status code ([[RFC6585](https://datatracker.ietf.org/doc/html/rfc6585)]). A client can discard responses that it cannot process. #### 10.5.2. CONNECT Issues The CONNECT method can be used to create disproportionate load on a proxy, since stream creation is relatively inexpensive when compared to the creation and maintenance of a TCP connection. Therefore, a proxy that supports CONNECT might be more conservative in the number of simultaneous requests it accepts. A proxy might also maintain some resources for a TCP connection beyond the closing of the stream that carries the CONNECT request, since the outgoing TCP connection remains in the TIME\_WAIT state. To account for this, a proxy might delay increasing the QUIC stream limits for some time after a TCP connection terminates. ### 10.6. Use of Compression Compression can allow an attacker to recover secret data when it is compressed in the same context as data under attacker control. HTTP/3 enables compression of fields ([Section 4.2](#section-4.2)); the following concerns also apply to the use of HTTP compressed content-codings; see Section 8.4.1 of [[HTTP](#ref-HTTP)]. There are demonstrable attacks on compression that exploit the characteristics of the web (e.g., [[BREACH](#ref-BREACH)]). The attacker induces multiple requests containing varying plaintext, observing the length of the resulting ciphertext in each, which reveals a shorter length when a guess about the secret is correct. Implementations communicating on a secure channel MUST NOT compress content that includes both confidential and attacker-controlled data unless separate compression contexts are used for each source of data. Compression MUST NOT be used if the source of data cannot be reliably determined. Further considerations regarding the compression of field sections are described in [[QPACK](#ref-QPACK)]. ### 10.7. Padding and Traffic Analysis Padding can be used to obscure the exact size of frame content and is provided to mitigate specific attacks within HTTP, for example, attacks where compressed content includes both attacker-controlled plaintext and secret data (e.g., [[BREACH](#ref-BREACH)]). Where HTTP/2 employs PADDING frames and Padding fields in other frames to make a connection more resistant to traffic analysis, HTTP/3 can either rely on transport-layer padding or employ the reserved frame and stream types discussed in Sections [7.2.8](#section-7.2.8) and 6.2.3. These methods of padding produce different results in terms of the granularity of padding, how padding is arranged in relation to the information that is being protected, whether padding is applied in the case of packet loss, and how an implementation might control padding. Reserved stream types can be used to give the appearance of sending traffic even when the connection is idle. Because HTTP traffic often occurs in bursts, apparent traffic can be used to obscure the timing or duration of such bursts, even to the point of appearing to send a constant stream of data. However, as such traffic is still flow controlled by the receiver, a failure to promptly drain such streams and provide additional flow-control credit can limit the sender's ability to send real traffic. To mitigate attacks that rely on compression, disabling or limiting compression might be preferable to padding as a countermeasure. Use of padding can result in less protection than might seem immediately obvious. Redundant padding could even be counterproductive. At best, padding only makes it more difficult for an attacker to infer length information by increasing the number of frames an attacker has to observe. Incorrectly implemented padding schemes can be easily defeated. In particular, randomized padding with a predictable distribution provides very little protection; similarly, padding payloads to a fixed size exposes information as payload sizes cross the fixed-sized boundary, which could be possible if an attacker can control plaintext. ### 10.8. Frame Parsing Several protocol elements contain nested length elements, typically in the form of frames with an explicit length containing variable- length integers. This could pose a security risk to an incautious implementer. An implementation MUST ensure that the length of a frame exactly matches the length of the fields it contains. ### 10.9. Early Data The use of 0-RTT with HTTP/3 creates an exposure to replay attack. The anti-replay mitigations in [[HTTP-REPLAY](#ref-HTTP-REPLAY)] MUST be applied when using HTTP/3 with 0-RTT. When applying [[HTTP-REPLAY](#ref-HTTP-REPLAY)] to HTTP/3, references to the TLS layer refer to the handshake performed within QUIC, while all references to application data refer to the contents of streams. ### 10.10. Migration Certain HTTP implementations use the client address for logging or access-control purposes. Since a QUIC client's address might change during a connection (and future versions might support simultaneous use of multiple addresses), such implementations will need to either actively retrieve the client's current address or addresses when they are relevant or explicitly accept that the original address might change. ### 10.11. Privacy Considerations Several characteristics of HTTP/3 provide an observer an opportunity to correlate actions of a single client or server over time. These include the value of settings, the timing of reactions to stimulus, and the handling of any features that are controlled by settings. As far as these create observable differences in behavior, they could be used as a basis for fingerprinting a specific client. HTTP/3's preference for using a single QUIC connection allows correlation of a user's activity on a site. Reusing connections for different origins allows for correlation of activity across those origins. Several features of QUIC solicit immediate responses and can be used by an endpoint to measure latency to their peer; this might have privacy implications in certain scenarios. 11. IANA Considerations ----------------------- This document registers a new ALPN protocol ID ([Section 11.1](#section-11.1)) and creates new registries that manage the assignment of code points in HTTP/3. ### 11.1. Registration of HTTP/3 Identification String This document creates a new registration for the identification of HTTP/3 in the "TLS Application-Layer Protocol Negotiation (ALPN) Protocol IDs" registry established in [[RFC7301](https://datatracker.ietf.org/doc/html/rfc7301)]. The "h3" string identifies HTTP/3: Protocol: HTTP/3 Identification Sequence: 0x68 0x33 ("h3") Specification: This document ### 11.2. New Registries New registries created in this document operate under the QUIC registration policy documented in Section 22.1 of [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. These registries all include the common set of fields listed in Section 22.1.1 of [[QUIC-TRANSPORT](#ref-QUIC-TRANSPORT)]. These registries are collected under the "Hypertext Transfer Protocol version 3 (HTTP/3)" heading. The initial allocations in these registries are all assigned permanent status and list a change controller of the IETF and a contact of the HTTP working group ([email protected]). #### 11.2.1. Frame Types This document establishes a registry for HTTP/3 frame type codes. The "HTTP/3 Frame Types" registry governs a 62-bit space. This registry follows the QUIC registry policy; see [Section 11.2](#section-11.2). Permanent registrations in this registry are assigned using the Specification Required policy ([[RFC8126](https://datatracker.ietf.org/doc/html/rfc8126)]), except for values between 0x00 and 0x3f (in hexadecimal; inclusive), which are assigned using Standards Action or IESG Approval as defined in Sections [4.9](#section-4.9) and [4.10](#section-4.10) of [[RFC8126](https://datatracker.ietf.org/doc/html/rfc8126)]. While this registry is separate from the "HTTP/2 Frame Type" registry defined in [HTTP/2], it is preferable that the assignments parallel each other where the code spaces overlap. If an entry is present in only one registry, every effort SHOULD be made to avoid assigning the corresponding value to an unrelated operation. Expert reviewers MAY reject unrelated registrations that would conflict with the same value in the corresponding registry. In addition to common fields as described in [Section 11.2](#section-11.2), permanent registrations in this registry MUST include the following field: Frame Type: A name or label for the frame type. Specifications of frame types MUST include a description of the frame layout and its semantics, including any parts of the frame that are conditionally present. The entries in Table 2 are registered by this document. +==============+=======+===============+ | Frame Type | Value | Specification | +==============+=======+===============+ | DATA | 0x00 | [Section 7.2.1](#section-7.2.1) | +--------------+-------+---------------+ | HEADERS | 0x01 | [Section 7.2.2](#section-7.2.2) | +--------------+-------+---------------+ | Reserved | 0x02 | This document | +--------------+-------+---------------+ | CANCEL\_PUSH | 0x03 | [Section 7.2.3](#section-7.2.3) | +--------------+-------+---------------+ | SETTINGS | 0x04 | [Section 7.2.4](#section-7.2.4) | +--------------+-------+---------------+ | PUSH\_PROMISE | 0x05 | [Section 7.2.5](#section-7.2.5) | +--------------+-------+---------------+ | Reserved | 0x06 | This document | +--------------+-------+---------------+ | GOAWAY | 0x07 | [Section 7.2.6](#section-7.2.6) | +--------------+-------+---------------+ | Reserved | 0x08 | This document | +--------------+-------+---------------+ | Reserved | 0x09 | This document | +--------------+-------+---------------+ | MAX\_PUSH\_ID | 0x0d | [Section 7.2.7](#section-7.2.7) | +--------------+-------+---------------+ Table 2: Initial HTTP/3 Frame Types Each code of the format 0x1f \* N + 0x21 for non-negative integer values of N (that is, 0x21, 0x40, ..., through 0x3ffffffffffffffe) MUST NOT be assigned by IANA and MUST NOT appear in the listing of assigned values. #### 11.2.2. Settings Parameters This document establishes a registry for HTTP/3 settings. The "HTTP/3 Settings" registry governs a 62-bit space. This registry follows the QUIC registry policy; see [Section 11.2](#section-11.2). Permanent registrations in this registry are assigned using the Specification Required policy ([[RFC8126](https://datatracker.ietf.org/doc/html/rfc8126)]), except for values between 0x00 and 0x3f (in hexadecimal; inclusive), which are assigned using Standards Action or IESG Approval as defined in Sections [4.9](#section-4.9) and [4.10](#section-4.10) of [[RFC8126](https://datatracker.ietf.org/doc/html/rfc8126)]. While this registry is separate from the "HTTP/2 Settings" registry defined in [HTTP/2], it is preferable that the assignments parallel each other. If an entry is present in only one registry, every effort SHOULD be made to avoid assigning the corresponding value to an unrelated operation. Expert reviewers MAY reject unrelated registrations that would conflict with the same value in the corresponding registry. In addition to common fields as described in [Section 11.2](#section-11.2), permanent registrations in this registry MUST include the following fields: Setting Name: A symbolic name for the setting. Specifying a setting name is optional. Default: The value of the setting unless otherwise indicated. A default SHOULD be the most restrictive possible value. The entries in Table 3 are registered by this document. +========================+=======+=================+===========+ | Setting Name | Value | Specification | Default | +========================+=======+=================+===========+ | Reserved | 0x00 | This document | N/A | +------------------------+-------+-----------------+-----------+ | Reserved | 0x02 | This document | N/A | +------------------------+-------+-----------------+-----------+ | Reserved | 0x03 | This document | N/A | +------------------------+-------+-----------------+-----------+ | Reserved | 0x04 | This document | N/A | +------------------------+-------+-----------------+-----------+ | Reserved | 0x05 | This document | N/A | +------------------------+-------+-----------------+-----------+ | MAX\_FIELD\_SECTION\_SIZE | 0x06 | [Section 7.2.4.1](#section-7.2.4.1) | Unlimited | +------------------------+-------+-----------------+-----------+ Table 3: Initial HTTP/3 Settings For formatting reasons, setting names can be abbreviated by removing the 'SETTINGS\_' prefix. Each code of the format 0x1f \* N + 0x21 for non-negative integer values of N (that is, 0x21, 0x40, ..., through 0x3ffffffffffffffe) MUST NOT be assigned by IANA and MUST NOT appear in the listing of assigned values. #### 11.2.3. Error Codes This document establishes a registry for HTTP/3 error codes. The "HTTP/3 Error Codes" registry manages a 62-bit space. This registry follows the QUIC registry policy; see [Section 11.2](#section-11.2). Permanent registrations in this registry are assigned using the Specification Required policy ([[RFC8126](https://datatracker.ietf.org/doc/html/rfc8126)]), except for values between 0x00 and 0x3f (in hexadecimal; inclusive), which are assigned using Standards Action or IESG Approval as defined in Sections [4.9](#section-4.9) and [4.10](#section-4.10) of [[RFC8126](https://datatracker.ietf.org/doc/html/rfc8126)]. Registrations for error codes are required to include a description of the error code. An expert reviewer is advised to examine new registrations for possible duplication with existing error codes. Use of existing registrations is to be encouraged, but not mandated. Use of values that are registered in the "HTTP/2 Error Code" registry is discouraged, and expert reviewers MAY reject such registrations. In addition to common fields as described in [Section 11.2](#section-11.2), this registry includes two additional fields. Permanent registrations in this registry MUST include the following field: Name: A name for the error code. Description: A brief description of the error code semantics. The entries in Table 4 are registered by this document. These error codes were selected from the range that operates on a Specification Required policy to avoid collisions with HTTP/2 error codes. +===========================+========+==============+===============+ | Name | Value | Description | Specification | +===========================+========+==============+===============+ | H3\_NO\_ERROR | 0x0100 | No error | [Section 8.1](#section-8.1) | +---------------------------+--------+--------------+---------------+ | H3\_GENERAL\_PROTOCOL\_ERROR | 0x0101 | General | [Section 8.1](#section-8.1) | | | | protocol | | | | | error | | +---------------------------+--------+--------------+---------------+ | H3\_INTERNAL\_ERROR | 0x0102 | Internal | [Section 8.1](#section-8.1) | | | | error | | +---------------------------+--------+--------------+---------------+ | H3\_STREAM\_CREATION\_ERROR | 0x0103 | Stream | [Section 8.1](#section-8.1) | | | | creation | | | | | error | | +---------------------------+--------+--------------+---------------+ | H3\_CLOSED\_CRITICAL\_STREAM | 0x0104 | Critical | [Section 8.1](#section-8.1) | | | | stream was | | | | | closed | | +---------------------------+--------+--------------+---------------+ | H3\_FRAME\_UNEXPECTED | 0x0105 | Frame not | [Section 8.1](#section-8.1) | | | | permitted | | | | | in the | | | | | current | | | | | state | | +---------------------------+--------+--------------+---------------+ | H3\_FRAME\_ERROR | 0x0106 | Frame | [Section 8.1](#section-8.1) | | | | violated | | | | | layout or | | | | | size rules | | +---------------------------+--------+--------------+---------------+ | H3\_EXCESSIVE\_LOAD | 0x0107 | Peer | [Section 8.1](#section-8.1) | | | | generating | | | | | excessive | | | | | load | | +---------------------------+--------+--------------+---------------+ | H3\_ID\_ERROR | 0x0108 | An | [Section 8.1](#section-8.1) | | | | identifier | | | | | was used | | | | | incorrectly | | +---------------------------+--------+--------------+---------------+ | H3\_SETTINGS\_ERROR | 0x0109 | SETTINGS | [Section 8.1](#section-8.1) | | | | frame | | | | | contained | | | | | invalid | | | | | values | | +---------------------------+--------+--------------+---------------+ | H3\_MISSING\_SETTINGS | 0x010a | No SETTINGS | [Section 8.1](#section-8.1) | | | | frame | | | | | received | | +---------------------------+--------+--------------+---------------+ | H3\_REQUEST\_REJECTED | 0x010b | Request not | [Section 8.1](#section-8.1) | | | | processed | | +---------------------------+--------+--------------+---------------+ | H3\_REQUEST\_CANCELLED | 0x010c | Data no | [Section 8.1](#section-8.1) | | | | longer | | | | | needed | | +---------------------------+--------+--------------+---------------+ | H3\_REQUEST\_INCOMPLETE | 0x010d | Stream | [Section 8.1](#section-8.1) | | | | terminated | | | | | early | | +---------------------------+--------+--------------+---------------+ | H3\_MESSAGE\_ERROR | 0x010e | Malformed | [Section 8.1](#section-8.1) | | | | message | | +---------------------------+--------+--------------+---------------+ | H3\_CONNECT\_ERROR | 0x010f | TCP reset | [Section 8.1](#section-8.1) | | | | or error on | | | | | CONNECT | | | | | request | | +---------------------------+--------+--------------+---------------+ | H3\_VERSION\_FALLBACK | 0x0110 | Retry over | [Section 8.1](#section-8.1) | | | | HTTP/1.1 | | +---------------------------+--------+--------------+---------------+ Table 4: Initial HTTP/3 Error Codes Each code of the format 0x1f \* N + 0x21 for non-negative integer values of N (that is, 0x21, 0x40, ..., through 0x3ffffffffffffffe) MUST NOT be assigned by IANA and MUST NOT appear in the listing of assigned values. #### 11.2.4. Stream Types This document establishes a registry for HTTP/3 unidirectional stream types. The "HTTP/3 Stream Types" registry governs a 62-bit space. This registry follows the QUIC registry policy; see [Section 11.2](#section-11.2). Permanent registrations in this registry are assigned using the Specification Required policy ([[RFC8126](https://datatracker.ietf.org/doc/html/rfc8126)]), except for values between 0x00 and 0x3f (in hexadecimal; inclusive), which are assigned using Standards Action or IESG Approval as defined in Sections [4.9](#section-4.9) and [4.10](#section-4.10) of [[RFC8126](https://datatracker.ietf.org/doc/html/rfc8126)]. In addition to common fields as described in [Section 11.2](#section-11.2), permanent registrations in this registry MUST include the following fields: Stream Type: A name or label for the stream type. Sender: Which endpoint on an HTTP/3 connection may initiate a stream of this type. Values are "Client", "Server", or "Both". Specifications for permanent registrations MUST include a description of the stream type, including the layout and semantics of the stream contents. The entries in Table 5 are registered by this document. +================+=======+===============+========+ | Stream Type | Value | Specification | Sender | +================+=======+===============+========+ | Control Stream | 0x00 | [Section 6.2.1](#section-6.2.1) | Both | +----------------+-------+---------------+--------+ | Push Stream | 0x01 | [Section 4.6](#section-4.6) | Server | +----------------+-------+---------------+--------+ Table 5: Initial Stream Types Each code of the format 0x1f \* N + 0x21 for non-negative integer values of N (that is, 0x21, 0x40, ..., through 0x3ffffffffffffffe) MUST NOT be assigned by IANA and MUST NOT appear in the listing of assigned values. 12. References -------------- ### 12.1. Normative References [ALTSVC] Nottingham, M., McManus, P., and J. Reschke, "HTTP Alternative Services", [RFC 7838](https://datatracker.ietf.org/doc/html/rfc7838), DOI 10.17487/RFC7838, April 2016, <<https://www.rfc-editor.org/info/rfc7838>>. [COOKIES] Barth, A., "HTTP State Management Mechanism", [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265), DOI 10.17487/RFC6265, April 2011, <<https://www.rfc-editor.org/info/rfc6265>>. [HTTP] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP Semantics", STD 97, [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110), DOI 10.17487/RFC9110, June 2022, <<https://www.rfc-editor.org/info/rfc9110>>. [HTTP-CACHING] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP Caching", STD 98, [RFC 9111](https://datatracker.ietf.org/doc/html/rfc9111), DOI 10.17487/RFC9111, June 2022, <<https://www.rfc-editor.org/info/rfc9111>>. [HTTP-REPLAY] Thomson, M., Nottingham, M., and W. Tarreau, "Using Early Data in HTTP", [RFC 8470](https://datatracker.ietf.org/doc/html/rfc8470), DOI 10.17487/RFC8470, September 2018, <<https://www.rfc-editor.org/info/rfc8470>>. [QPACK] Krasic, C., Bishop, M., and A. Frindell, Ed., "QPACK: Field Compression for HTTP/3", [RFC 9204](https://datatracker.ietf.org/doc/html/rfc9204), DOI 10.17487/RFC9204, June 2022, <<https://www.rfc-editor.org/info/rfc9204>>. [QUIC-TRANSPORT] Iyengar, J., Ed. and M. Thomson, Ed., "QUIC: A UDP-Based Multiplexed and Secure Transport", [RFC 9000](https://datatracker.ietf.org/doc/html/rfc9000), DOI 10.17487/RFC9000, May 2021, <<https://www.rfc-editor.org/info/rfc9000>>. [RFC0793] Postel, J., "Transmission Control Protocol", STD 7, [RFC 793](https://datatracker.ietf.org/doc/html/rfc793), DOI 10.17487/RFC0793, September 1981, <<https://www.rfc-editor.org/info/rfc793>>. [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", [BCP 14](https://datatracker.ietf.org/doc/html/bcp14), [RFC 2119](https://datatracker.ietf.org/doc/html/rfc2119), DOI 10.17487/RFC2119, March 1997, <<https://www.rfc-editor.org/info/rfc2119>>. [RFC6066] Eastlake 3rd, D., "Transport Layer Security (TLS) Extensions: Extension Definitions", [RFC 6066](https://datatracker.ietf.org/doc/html/rfc6066), DOI 10.17487/RFC6066, January 2011, <<https://www.rfc-editor.org/info/rfc6066>>. [RFC7301] Friedl, S., Popov, A., Langley, A., and E. Stephan, "Transport Layer Security (TLS) Application-Layer Protocol Negotiation Extension", [RFC 7301](https://datatracker.ietf.org/doc/html/rfc7301), DOI 10.17487/RFC7301, July 2014, <<https://www.rfc-editor.org/info/rfc7301>>. [RFC8126] Cotton, M., Leiba, B., and T. Narten, "Guidelines for Writing an IANA Considerations Section in RFCs", [BCP 26](https://datatracker.ietf.org/doc/html/bcp26), [RFC 8126](https://datatracker.ietf.org/doc/html/rfc8126), DOI 10.17487/RFC8126, June 2017, <<https://www.rfc-editor.org/info/rfc8126>>. [RFC8174] Leiba, B., "Ambiguity of Uppercase vs Lowercase in [RFC](https://datatracker.ietf.org/doc/html/rfc2119) [2119](https://datatracker.ietf.org/doc/html/rfc2119) Key Words", [BCP 14](https://datatracker.ietf.org/doc/html/bcp14), [RFC 8174](https://datatracker.ietf.org/doc/html/rfc8174), DOI 10.17487/RFC8174, May 2017, <<https://www.rfc-editor.org/info/rfc8174>>. [URI] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform Resource Identifier (URI): Generic Syntax", STD 66, [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986), DOI 10.17487/RFC3986, January 2005, <<https://www.rfc-editor.org/info/rfc3986>>. ### 12.2. Informative References [BREACH] Gluck, Y., Harris, N., and A. Prado, "BREACH: Reviving the CRIME Attack", July 2013, <<http://breachattack.com/resources/> BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf>. [DNS-TERMS] Hoffman, P., Sullivan, A., and K. Fujiwara, "DNS Terminology", [BCP 219](https://datatracker.ietf.org/doc/html/bcp219), [RFC 8499](https://datatracker.ietf.org/doc/html/rfc8499), DOI 10.17487/RFC8499, January 2019, <<https://www.rfc-editor.org/info/rfc8499>>. [HPACK] Peon, R. and H. Ruellan, "HPACK: Header Compression for HTTP/2", [RFC 7541](https://datatracker.ietf.org/doc/html/rfc7541), DOI 10.17487/RFC7541, May 2015, <<https://www.rfc-editor.org/info/rfc7541>>. [HTTP/1.1] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP/1.1", STD 99, [RFC 9112](https://datatracker.ietf.org/doc/html/rfc9112), DOI 10.17487/RFC9112, June 2022, <<https://www.rfc-editor.org/info/rfc9112>>. [HTTP/2] Thomson, M., Ed. and C. Benfield, Ed., "HTTP/2", [RFC 9113](https://datatracker.ietf.org/doc/html/rfc9113), DOI 10.17487/RFC9113, June 2022, <<https://www.rfc-editor.org/info/rfc9113>>. [RFC6585] Nottingham, M. and R. Fielding, "Additional HTTP Status Codes", [RFC 6585](https://datatracker.ietf.org/doc/html/rfc6585), DOI 10.17487/RFC6585, April 2012, <<https://www.rfc-editor.org/info/rfc6585>>. [RFC8164] Nottingham, M. and M. Thomson, "Opportunistic Security for HTTP/2", [RFC 8164](https://datatracker.ietf.org/doc/html/rfc8164), DOI 10.17487/RFC8164, May 2017, <<https://www.rfc-editor.org/info/rfc8164>>. [TFO] Cheng, Y., Chu, J., Radhakrishnan, S., and A. Jain, "TCP Fast Open", [RFC 7413](https://datatracker.ietf.org/doc/html/rfc7413), DOI 10.17487/RFC7413, December 2014, <<https://www.rfc-editor.org/info/rfc7413>>. [TLS] Rescorla, E., "The Transport Layer Security (TLS) Protocol Version 1.3", [RFC 8446](https://datatracker.ietf.org/doc/html/rfc8446), DOI 10.17487/RFC8446, August 2018, <<https://www.rfc-editor.org/info/rfc8446>>. Appendix A. Considerations for Transitioning from HTTP/2 -------------------------------------------------------- HTTP/3 is strongly informed by HTTP/2, and it bears many similarities. This section describes the approach taken to design HTTP/3, points out important differences from HTTP/2, and describes how to map HTTP/2 extensions into HTTP/3. HTTP/3 begins from the premise that similarity to HTTP/2 is preferable, but not a hard requirement. HTTP/3 departs from HTTP/2 where QUIC differs from TCP, either to take advantage of QUIC features (like streams) or to accommodate important shortcomings (such as a lack of total ordering). While HTTP/3 is similar to HTTP/2 in key aspects, such as the relationship of requests and responses to streams, the details of the HTTP/3 design are substantially different from HTTP/2. Some important departures are noted in this section. ### A.1. Streams HTTP/3 permits use of a larger number of streams (2^62-1) than HTTP/2. The same considerations about exhaustion of stream identifier space apply, though the space is significantly larger such that it is likely that other limits in QUIC are reached first, such as the limit on the connection flow-control window. In contrast to HTTP/2, stream concurrency in HTTP/3 is managed by QUIC. QUIC considers a stream closed when all data has been received and sent data has been acknowledged by the peer. HTTP/2 considers a stream closed when the frame containing the END\_STREAM bit has been committed to the transport. As a result, the stream for an equivalent exchange could remain "active" for a longer period of time. HTTP/3 servers might choose to permit a larger number of concurrent client-initiated bidirectional streams to achieve equivalent concurrency to HTTP/2, depending on the expected usage patterns. In HTTP/2, only request and response bodies (the frame payload of DATA frames) are subject to flow control. All HTTP/3 frames are sent on QUIC streams, so all frames on all streams are flow controlled in HTTP/3. Due to the presence of other unidirectional stream types, HTTP/3 does not rely exclusively on the number of concurrent unidirectional streams to control the number of concurrent in-flight pushes. Instead, HTTP/3 clients use the MAX\_PUSH\_ID frame to control the number of pushes received from an HTTP/3 server. ### A.2. HTTP Frame Types Many framing concepts from HTTP/2 can be elided on QUIC, because the transport deals with them. Because frames are already on a stream, they can omit the stream number. Because frames do not block multiplexing (QUIC's multiplexing occurs below this layer), the support for variable-maximum-length packets can be removed. Because stream termination is handled by QUIC, an END\_STREAM flag is not required. This permits the removal of the Flags field from the generic frame layout. Frame payloads are largely drawn from [HTTP/2]. However, QUIC includes many features (e.g., flow control) that are also present in HTTP/2. In these cases, the HTTP mapping does not re-implement them. As a result, several HTTP/2 frame types are not required in HTTP/3. Where an HTTP/2-defined frame is no longer used, the frame ID has been reserved in order to maximize portability between HTTP/2 and HTTP/3 implementations. However, even frame types that appear in both mappings do not have identical semantics. Many of the differences arise from the fact that HTTP/2 provides an absolute ordering between frames across all streams, while QUIC provides this guarantee on each stream only. As a result, if a frame type makes assumptions that frames from different streams will still be received in the order sent, HTTP/3 will break them. Some examples of feature adaptations are described below, as well as general guidance to extension frame implementors converting an HTTP/2 extension to HTTP/3. #### A.2.1. Prioritization Differences HTTP/2 specifies priority assignments in PRIORITY frames and (optionally) in HEADERS frames. HTTP/3 does not provide a means of signaling priority. Note that, while there is no explicit signaling for priority, this does not mean that prioritization is not important for achieving good performance. #### A.2.2. Field Compression Differences HPACK was designed with the assumption of in-order delivery. A sequence of encoded field sections must arrive (and be decoded) at an endpoint in the same order in which they were encoded. This ensures that the dynamic state at the two endpoints remains in sync. Because this total ordering is not provided by QUIC, HTTP/3 uses a modified version of HPACK, called QPACK. QPACK uses a single unidirectional stream to make all modifications to the dynamic table, ensuring a total order of updates. All frames that contain encoded fields merely reference the table state at a given time without modifying it. [QPACK] provides additional details. #### A.2.3. Flow-Control Differences HTTP/2 specifies a stream flow-control mechanism. Although all HTTP/2 frames are delivered on streams, only the DATA frame payload is subject to flow control. QUIC provides flow control for stream data and all HTTP/3 frame types defined in this document are sent on streams. Therefore, all frame headers and payload are subject to flow control. #### A.2.4. Guidance for New Frame Type Definitions Frame type definitions in HTTP/3 often use the QUIC variable-length integer encoding. In particular, stream IDs use this encoding, which allows for a larger range of possible values than the encoding used in HTTP/2. Some frames in HTTP/3 use an identifier other than a stream ID (e.g., push IDs). Redefinition of the encoding of extension frame types might be necessary if the encoding includes a stream ID. Because the Flags field is not present in generic HTTP/3 frames, those frames that depend on the presence of flags need to allocate space for flags as part of their frame payload. Other than these issues, frame type HTTP/2 extensions are typically portable to QUIC simply by replacing stream 0 in HTTP/2 with a control stream in HTTP/3. HTTP/3 extensions will not assume ordering, but would not be harmed by ordering, and are expected to be portable to HTTP/2. #### A.2.5. Comparison of HTTP/2 and HTTP/3 Frame Types DATA (0x00): Padding is not defined in HTTP/3 frames. See [Section 7.2.1](#section-7.2.1). HEADERS (0x01): The PRIORITY region of HEADERS is not defined in HTTP/3 frames. Padding is not defined in HTTP/3 frames. See [Section 7.2.2](#section-7.2.2). PRIORITY (0x02): As described in [Appendix A.2.1](#appendix-A.2.1), HTTP/3 does not provide a means of signaling priority. RST\_STREAM (0x03): RST\_STREAM frames do not exist in HTTP/3, since QUIC provides stream lifecycle management. The same code point is used for the CANCEL\_PUSH frame ([Section 7.2.3](#section-7.2.3)). SETTINGS (0x04): SETTINGS frames are sent only at the beginning of the connection. See [Section 7.2.4](#section-7.2.4) and [Appendix A.3](#appendix-A.3). PUSH\_PROMISE (0x05): The PUSH\_PROMISE frame does not reference a stream; instead, the push stream references the PUSH\_PROMISE frame using a push ID. See [Section 7.2.5](#section-7.2.5). PING (0x06): PING frames do not exist in HTTP/3, as QUIC provides equivalent functionality. GOAWAY (0x07): GOAWAY does not contain an error code. In the client-to-server direction, it carries a push ID instead of a server-initiated stream ID. See [Section 7.2.6](#section-7.2.6). WINDOW\_UPDATE (0x08): WINDOW\_UPDATE frames do not exist in HTTP/3, since QUIC provides flow control. CONTINUATION (0x09): CONTINUATION frames do not exist in HTTP/3; instead, larger HEADERS/PUSH\_PROMISE frames than HTTP/2 are permitted. Frame types defined by extensions to HTTP/2 need to be separately registered for HTTP/3 if still applicable. The IDs of frames defined in [HTTP/2] have been reserved for simplicity. Note that the frame type space in HTTP/3 is substantially larger (62 bits versus 8 bits), so many HTTP/3 frame types have no equivalent HTTP/2 code points. See [Section 11.2.1](#section-11.2.1). ### A.3. HTTP/2 SETTINGS Parameters An important difference from HTTP/2 is that settings are sent once, as the first frame of the control stream, and thereafter cannot change. This eliminates many corner cases around synchronization of changes. Some transport-level options that HTTP/2 specifies via the SETTINGS frame are superseded by QUIC transport parameters in HTTP/3. The HTTP-level setting that is retained in HTTP/3 has the same value as in HTTP/2. The superseded settings are reserved, and their receipt is an error. See [Section 7.2.4.1](#section-7.2.4.1) for discussion of both the retained and reserved values. Below is a listing of how each HTTP/2 SETTINGS parameter is mapped: SETTINGS\_HEADER\_TABLE\_SIZE (0x01): See [[QPACK](#ref-QPACK)]. SETTINGS\_ENABLE\_PUSH (0x02): This is removed in favor of the MAX\_PUSH\_ID frame, which provides a more granular control over server push. Specifying a setting with the identifier 0x02 (corresponding to the SETTINGS\_ENABLE\_PUSH parameter) in the HTTP/3 SETTINGS frame is an error. SETTINGS\_MAX\_CONCURRENT\_STREAMS (0x03): QUIC controls the largest open stream ID as part of its flow-control logic. Specifying a setting with the identifier 0x03 (corresponding to the SETTINGS\_MAX\_CONCURRENT\_STREAMS parameter) in the HTTP/3 SETTINGS frame is an error. SETTINGS\_INITIAL\_WINDOW\_SIZE (0x04): QUIC requires both stream and connection flow-control window sizes to be specified in the initial transport handshake. Specifying a setting with the identifier 0x04 (corresponding to the SETTINGS\_INITIAL\_WINDOW\_SIZE parameter) in the HTTP/3 SETTINGS frame is an error. SETTINGS\_MAX\_FRAME\_SIZE (0x05): This setting has no equivalent in HTTP/3. Specifying a setting with the identifier 0x05 (corresponding to the SETTINGS\_MAX\_FRAME\_SIZE parameter) in the HTTP/3 SETTINGS frame is an error. SETTINGS\_MAX\_HEADER\_LIST\_SIZE (0x06): This setting identifier has been renamed SETTINGS\_MAX\_FIELD\_SECTION\_SIZE. In HTTP/3, setting values are variable-length integers (6, 14, 30, or 62 bits long) rather than fixed-length 32-bit fields as in HTTP/2. This will often produce a shorter encoding, but can produce a longer encoding for settings that use the full 32-bit space. Settings ported from HTTP/2 might choose to redefine their value to limit it to 30 bits for more efficient encoding or to make use of the 62-bit space if more than 30 bits are required. Settings need to be defined separately for HTTP/2 and HTTP/3. The IDs of settings defined in [HTTP/2] have been reserved for simplicity. Note that the settings identifier space in HTTP/3 is substantially larger (62 bits versus 16 bits), so many HTTP/3 settings have no equivalent HTTP/2 code point. See [Section 11.2.2](#section-11.2.2). As QUIC streams might arrive out of order, endpoints are advised not to wait for the peers' settings to arrive before responding to other streams. See [Section 7.2.4.2](#section-7.2.4.2). ### A.4. HTTP/2 Error Codes QUIC has the same concepts of "stream" and "connection" errors that HTTP/2 provides. However, the differences between HTTP/2 and HTTP/3 mean that error codes are not directly portable between versions. The HTTP/2 error codes defined in [Section 7](#section-7) of [HTTP/2] logically map to the HTTP/3 error codes as follows: NO\_ERROR (0x00): H3\_NO\_ERROR in [Section 8.1](#section-8.1). PROTOCOL\_ERROR (0x01): This is mapped to H3\_GENERAL\_PROTOCOL\_ERROR except in cases where more specific error codes have been defined. Such cases include H3\_FRAME\_UNEXPECTED, H3\_MESSAGE\_ERROR, and H3\_CLOSED\_CRITICAL\_STREAM defined in [Section 8.1](#section-8.1). INTERNAL\_ERROR (0x02): H3\_INTERNAL\_ERROR in [Section 8.1](#section-8.1). FLOW\_CONTROL\_ERROR (0x03): Not applicable, since QUIC handles flow control. SETTINGS\_TIMEOUT (0x04): Not applicable, since no acknowledgment of SETTINGS is defined. STREAM\_CLOSED (0x05): Not applicable, since QUIC handles stream management. FRAME\_SIZE\_ERROR (0x06): H3\_FRAME\_ERROR error code defined in [Section 8.1](#section-8.1). REFUSED\_STREAM (0x07): H3\_REQUEST\_REJECTED (in [Section 8.1](#section-8.1)) is used to indicate that a request was not processed. Otherwise, not applicable because QUIC handles stream management. CANCEL (0x08): H3\_REQUEST\_CANCELLED in [Section 8.1](#section-8.1). COMPRESSION\_ERROR (0x09): Multiple error codes are defined in [[QPACK](#ref-QPACK)]. CONNECT\_ERROR (0x0a): H3\_CONNECT\_ERROR in [Section 8.1](#section-8.1). ENHANCE\_YOUR\_CALM (0x0b): H3\_EXCESSIVE\_LOAD in [Section 8.1](#section-8.1). INADEQUATE\_SECURITY (0x0c): Not applicable, since QUIC is assumed to provide sufficient security on all connections. HTTP\_1\_1\_REQUIRED (0x0d): H3\_VERSION\_FALLBACK in [Section 8.1](#section-8.1). Error codes need to be defined for HTTP/2 and HTTP/3 separately. See [Section 11.2.3](#section-11.2.3). #### A.4.1. Mapping between HTTP/2 and HTTP/3 Errors An intermediary that converts between HTTP/2 and HTTP/3 may encounter error conditions from either upstream. It is useful to communicate the occurrence of errors to the downstream, but error codes largely reflect connection-local problems that generally do not make sense to propagate. An intermediary that encounters an error from an upstream origin can indicate this by sending an HTTP status code such as 502 (Bad Gateway), which is suitable for a broad class of errors. There are some rare cases where it is beneficial to propagate the error by mapping it to the closest matching error type to the receiver. For example, an intermediary that receives an HTTP/2 stream error of type REFUSED\_STREAM from the origin has a clear signal that the request was not processed and that the request is safe to retry. Propagating this error condition to the client as an HTTP/3 stream error of type H3\_REQUEST\_REJECTED allows the client to take the action it deems most appropriate. In the reverse direction, the intermediary might deem it beneficial to pass on client request cancellations that are indicated by terminating a stream with H3\_REQUEST\_CANCELLED; see [Section 4.1.1](#section-4.1.1). Conversion between errors is described in the logical mapping. The error codes are defined in non-overlapping spaces in order to protect against accidental conversion that could result in the use of inappropriate or unknown error codes for the target version. An intermediary is permitted to promote stream errors to connection errors but they should be aware of the cost to the HTTP/3 connection for what might be a temporary or intermittent error. Acknowledgments Robbie Shade and Mike Warres were the authors of [draft-shade-quic-](https://datatracker.ietf.org/doc/html/draft-shade-quic-http2-mapping) [http2-mapping](https://datatracker.ietf.org/doc/html/draft-shade-quic-http2-mapping), a precursor of this document. The IETF QUIC Working Group received an enormous amount of support from many people. Among others, the following people provided substantial contributions to this document: \* Bence Beky \* Daan De Meyer \* Martin Duke \* Roy Fielding \* Alan Frindell \* Alessandro Ghedini \* Nick Harper \* Ryan Hamilton \* Christian Huitema \* Subodh Iyengar \* Robin Marx \* Patrick McManus \* Luca Niccolini \* 奥 一穂 (Kazuho Oku) \* Lucas Pardue \* Roberto Peon \* Julian Reschke \* Eric Rescorla \* Martin Seemann \* Ben Schwartz \* Ian Swett \* Willy Taureau \* Martin Thomson \* Dmitri Tikhonov \* Tatsuhiro Tsujikawa A portion of Mike Bishop's contribution was supported by Microsoft during his employment there. Index C D G H M P R S C CANCEL\_PUSH [Section 2](#section-2), Paragraph 5; [Section 4.6](#section-4.6), Paragraph 6; [Section 4.6](#section-4.6), Paragraph 10; Table 1; \*\_[Section 7.2.3](#section-7.2.3)\_\*; [Section 7.2.5](#section-7.2.5), Paragraph 4.2.1; [Section 7.2.7](#section-7.2.7), Paragraph 1; Table 2; [Appendix A.2.5](#appendix-A.2.5), Paragraph 1.8.1 connection error [Section 2.2](#section-2.2); [Section 4.1](#section-4.1), Paragraph 7; [Section 4.1](#section-4.1), Paragraph 8; [Section 4.4](#section-4.4), Paragraph 8; [Section 4.4](#section-4.4), Paragraph 10; [Section 4.6](#section-4.6), Paragraph 3; [Section 5.2](#section-5.2), Paragraph 7; [Section 6.1](#section-6.1), Paragraph 3; [Section 6.2](#section-6.2), Paragraph 7; [Section 6.2.1](#section-6.2.1), Paragraph 2; [Section 6.2.1](#section-6.2.1), Paragraph 2; [Section 6.2.1](#section-6.2.1), Paragraph 2; [Section 6.2.2](#section-6.2.2), Paragraph 3; [Section 6.2.2](#section-6.2.2), Paragraph 6; [Section 7.1](#section-7.1), Paragraph 5; [Section 7.1](#section-7.1), Paragraph 6; [Section 7.2.1](#section-7.2.1), Paragraph 2; [Section 7.2.2](#section-7.2.2), Paragraph 3; [Section 7.2.3](#section-7.2.3), Paragraph 5; [Section 7.2.3](#section-7.2.3), Paragraph 7; [Section 7.2.3](#section-7.2.3), Paragraph 8; [Section 7.2.4](#section-7.2.4), Paragraph 2; [Section 7.2.4](#section-7.2.4), Paragraph 3; [Section 7.2.4](#section-7.2.4), Paragraph 6; [Section 7.2.4.1](#section-7.2.4.1), Paragraph 5; [Section 7.2.4.2](#section-7.2.4.2), Paragraph 8; [Section 7.2.4.2](#section-7.2.4.2), Paragraph 8; [Section 7.2.5](#section-7.2.5), Paragraph 5; [Section 7.2.5](#section-7.2.5), Paragraph 6; [Section 7.2.5](#section-7.2.5), Paragraph 8; [Section 7.2.5](#section-7.2.5), Paragraph 9; [Section 7.2.6](#section-7.2.6), Paragraph 3; [Section 7.2.6](#section-7.2.6), Paragraph 5; [Section 7.2.7](#section-7.2.7), Paragraph 2; [Section 7.2.7](#section-7.2.7), Paragraph 3; [Section 7.2.7](#section-7.2.7), Paragraph 6; [Section 7.2.8](#section-7.2.8), Paragraph 3; \*\_[Section 8](#section-8)\_\*; [Section 10.5](#section-10.5), Paragraph 7; [Appendix A.4.1](#appendix-A.4.1), Paragraph 4 control stream [Section 2](#section-2), Paragraph 3; [Section 3.2](#section-3.2), Paragraph 4; [Section 6.2](#section-6.2), Paragraph 3; [Section 6.2](#section-6.2), Paragraph 5; [Section 6.2](#section-6.2), Paragraph 6; \*\_[Section 6.2.1](#section-6.2.1)\_\*; [Section 7](#section-7), Paragraph 1; [Section 7.2.1](#section-7.2.1), Paragraph 2; [Section 7.2.2](#section-7.2.2), Paragraph 3; [Section 7.2.3](#section-7.2.3), Paragraph 5; [Section 7.2.3](#section-7.2.3), Paragraph 5; [Section 7.2.4](#section-7.2.4), Paragraph 2; [Section 7.2.4](#section-7.2.4), Paragraph 2; [Section 7.2.4](#section-7.2.4), Paragraph 3; [Section 7.2.5](#section-7.2.5), Paragraph 8; [Section 7.2.6](#section-7.2.6), Paragraph 3; [Section 7.2.6](#section-7.2.6), Paragraph 5; [Section 7.2.7](#section-7.2.7), Paragraph 2; [Section 8.1](#section-8.1), Paragraph 2.22.1; [Section 9](#section-9), Paragraph 4; [Appendix A.2.4](#appendix-A.2.4), Paragraph 3; [Appendix A.3](#appendix-A.3), Paragraph 1 D DATA [Section 2](#section-2), Paragraph 3; [Section 4.1](#section-4.1), Paragraph 5, Item 2; [Section 4.1](#section-4.1), Paragraph 7; [Section 4.1](#section-4.1), Paragraph 7; [Section 4.1.2](#section-4.1.2), Paragraph 3; [Section 4.1.2](#section-4.1.2), Paragraph 3; [Section 4.4](#section-4.4), Paragraph 7; [Section 4.4](#section-4.4), Paragraph 7; [Section 4.4](#section-4.4), Paragraph 7; [Section 4.4](#section-4.4), Paragraph 7; [Section 4.4](#section-4.4), Paragraph 8; [Section 4.6](#section-4.6), Paragraph 12; Table 1; \*\_[Section 7.2.1](#section-7.2.1)\_\*; Table 2; [Appendix A.1](#appendix-A.1), Paragraph 3; [Appendix A.2.3](#appendix-A.2.3), Paragraph 1; [Appendix A.2.5](#appendix-A.2.5) G GOAWAY [Section 3.3](#section-3.3), Paragraph 5; [Section 5.2](#section-5.2), Paragraph 1; [Section 5.2](#section-5.2), Paragraph 1; [Section 5.2](#section-5.2), Paragraph 1; [Section 5.2](#section-5.2), Paragraph 2; [Section 5.2](#section-5.2), Paragraph 2; [Section 5.2](#section-5.2), Paragraph 3; [Section 5.2](#section-5.2), Paragraph 5.1.1; [Section 5.2](#section-5.2), Paragraph 5.1.1; [Section 5.2](#section-5.2), Paragraph 5.1.2; [Section 5.2](#section-5.2), Paragraph 5.1.2; [Section 5.2](#section-5.2), Paragraph 5, Item 2; [Section 5.2](#section-5.2), Paragraph 5, Item 2; [Section 5.2](#section-5.2), Paragraph 6; [Section 5.2](#section-5.2), Paragraph 6; [Section 5.2](#section-5.2), Paragraph 7; [Section 5.2](#section-5.2), Paragraph 7; [Section 5.2](#section-5.2), Paragraph 8; [Section 5.2](#section-5.2), Paragraph 8; [Section 5.2](#section-5.2), Paragraph 9; [Section 5.2](#section-5.2), Paragraph 9; [Section 5.2](#section-5.2), Paragraph 10; [Section 5.2](#section-5.2), Paragraph 12; [Section 5.3](#section-5.3), Paragraph 2; [Section 5.3](#section-5.3), Paragraph 2; [Section 5.4](#section-5.4), Paragraph 2; Table 1; \*\_[Section 7.2.6](#section-7.2.6)\_\*; Table 2; [Appendix A.2.5](#appendix-A.2.5); [Appendix A.2.5](#appendix-A.2.5), Paragraph 1.16.1 H H3\_CLOSED\_CRITICAL\_STREAM [Section 6.2.1](#section-6.2.1), Paragraph 2; [Section 8.1](#section-8.1); Table 4; [Appendix A.4](#appendix-A.4), Paragraph 3.4.1 H3\_CONNECT\_ERROR [Section 4.4](#section-4.4), Paragraph 10; [Section 8.1](#section-8.1); Table 4; [Appendix A.4](#appendix-A.4), Paragraph 3.22.1 H3\_EXCESSIVE\_LOAD [Section 8.1](#section-8.1); [Section 10.5](#section-10.5), Paragraph 7; Table 4; [Appendix A.4](#appendix-A.4), Paragraph 3.24.1 H3\_FRAME\_ERROR [Section 7.1](#section-7.1), Paragraph 5; [Section 7.1](#section-7.1), Paragraph 6; [Section 8.1](#section-8.1); Table 4; [Appendix A.4](#appendix-A.4), Paragraph 3.14.1 H3\_FRAME\_UNEXPECTED [Section 4.1](#section-4.1), Paragraph 7; [Section 4.1](#section-4.1), Paragraph 8; [Section 4.4](#section-4.4), Paragraph 8; [Section 7.2.1](#section-7.2.1), Paragraph 2; [Section 7.2.2](#section-7.2.2), Paragraph 3; [Section 7.2.3](#section-7.2.3), Paragraph 5; [Section 7.2.4](#section-7.2.4), Paragraph 2; [Section 7.2.4](#section-7.2.4), Paragraph 3; [Section 7.2.5](#section-7.2.5), Paragraph 8; [Section 7.2.5](#section-7.2.5), Paragraph 9; [Section 7.2.6](#section-7.2.6), Paragraph 5; [Section 7.2.7](#section-7.2.7), Paragraph 2; [Section 7.2.7](#section-7.2.7), Paragraph 3; [Section 7.2.8](#section-7.2.8), Paragraph 3; [Section 8.1](#section-8.1); Table 4; [Appendix A.4](#appendix-A.4), Paragraph 3.4.1 H3\_GENERAL\_PROTOCOL\_ERROR [Section 7.2.5](#section-7.2.5), Paragraph 6; [Section 8.1](#section-8.1); Table 4; [Appendix A.4](#appendix-A.4), Paragraph 3.4.1 H3\_ID\_ERROR [Section 4.6](#section-4.6), Paragraph 3; [Section 5.2](#section-5.2), Paragraph 7; [Section 6.2.2](#section-6.2.2), Paragraph 6; [Section 7.2.3](#section-7.2.3), Paragraph 7; [Section 7.2.3](#section-7.2.3), Paragraph 8; [Section 7.2.5](#section-7.2.5), Paragraph 5; [Section 7.2.6](#section-7.2.6), Paragraph 3; [Section 7.2.7](#section-7.2.7), Paragraph 6; [Section 8.1](#section-8.1); Table 4 H3\_INTERNAL\_ERROR [Section 8.1](#section-8.1); Table 4; [Appendix A.4](#appendix-A.4), Paragraph 3.6.1 H3\_MESSAGE\_ERROR [Section 4.1.2](#section-4.1.2), Paragraph 4; [Section 8.1](#section-8.1); Table 4; [Appendix A.4](#appendix-A.4), Paragraph 3.4.1 H3\_MISSING\_SETTINGS [Section 6.2.1](#section-6.2.1), Paragraph 2; [Section 8.1](#section-8.1); Table 4 H3\_NO\_ERROR [Section 4.1](#section-4.1), Paragraph 15; [Section 5.2](#section-5.2), Paragraph 11; [Section 6.2.3](#section-6.2.3), Paragraph 2; [Section 8](#section-8), Paragraph 5; [Section 8.1](#section-8.1); [Section 8.1](#section-8.1), Paragraph 3; [Section 8.1](#section-8.1), Paragraph 3; Table 4; [Appendix A.4](#appendix-A.4), Paragraph 3.2.1 H3\_REQUEST\_CANCELLED [Section 4.1.1](#section-4.1.1), Paragraph 4; [Section 4.1.1](#section-4.1.1), Paragraph 5; [Section 4.6](#section-4.6), Paragraph 14; [Section 7.2.3](#section-7.2.3), Paragraph 3; [Section 7.2.3](#section-7.2.3), Paragraph 4; [Section 8.1](#section-8.1); Table 4; [Appendix A.4](#appendix-A.4), Paragraph 3.18.1; [Appendix A.4.1](#appendix-A.4.1), Paragraph 3 H3\_REQUEST\_INCOMPLETE [Section 4.1](#section-4.1), Paragraph 14; [Section 8.1](#section-8.1); Table 4 H3\_REQUEST\_REJECTED [Section 4.1.1](#section-4.1.1), Paragraph 3; [Section 4.1.1](#section-4.1.1), Paragraph 4; [Section 4.1.1](#section-4.1.1), Paragraph 5; [Section 4.1.1](#section-4.1.1), Paragraph 5; [Section 8.1](#section-8.1); Table 4; [Appendix A.4](#appendix-A.4), Paragraph 3.16.1; [Appendix A.4.1](#appendix-A.4.1), Paragraph 3 H3\_SETTINGS\_ERROR [Section 7.2.4](#section-7.2.4), Paragraph 6; [Section 7.2.4.1](#section-7.2.4.1), Paragraph 5; [Section 7.2.4.2](#section-7.2.4.2), Paragraph 8; [Section 7.2.4.2](#section-7.2.4.2), Paragraph 8; [Section 8.1](#section-8.1); Table 4 H3\_STREAM\_CREATION\_ERROR [Section 6.1](#section-6.1), Paragraph 3; [Section 6.2](#section-6.2), Paragraph 7; [Section 6.2.1](#section-6.2.1), Paragraph 2; [Section 6.2.2](#section-6.2.2), Paragraph 3; [Section 8.1](#section-8.1); Table 4 H3\_VERSION\_FALLBACK [Section 8.1](#section-8.1); Table 4; [Appendix A.4](#appendix-A.4), Paragraph 3.28.1 HEADERS [Section 2](#section-2), Paragraph 3; [Section 4.1](#section-4.1), Paragraph 5, Item 1; [Section 4.1](#section-4.1), Paragraph 5, Item 3; [Section 4.1](#section-4.1), Paragraph 7; [Section 4.1](#section-4.1), Paragraph 7; [Section 4.1](#section-4.1), Paragraph 7; [Section 4.1](#section-4.1), Paragraph 10; [Section 4.4](#section-4.4), Paragraph 6; [Section 4.6](#section-4.6), Paragraph 12; Table 1; \*\_[Section 7.2.2](#section-7.2.2)\_\*; [Section 9](#section-9), Paragraph 5; Table 2; [Appendix A.2.1](#appendix-A.2.1), Paragraph 1; [Appendix A.2.5](#appendix-A.2.5); [Appendix A.2.5](#appendix-A.2.5), Paragraph 1.4.1; [Appendix A.2.5](#appendix-A.2.5), Paragraph 1.20.1 M malformed [Section 4.1](#section-4.1), Paragraph 3; \*\_[Section 4.1.2](#section-4.1.2)\_\*; [Section 4.2](#section-4.2), Paragraph 2; [Section 4.2](#section-4.2), Paragraph 3; [Section 4.2](#section-4.2), Paragraph 5; [Section 4.3](#section-4.3), Paragraph 3; [Section 4.3](#section-4.3), Paragraph 4; [Section 4.3.1](#section-4.3.1), Paragraph 5; [Section 4.3.2](#section-4.3.2), Paragraph 1; [Section 4.4](#section-4.4), Paragraph 5; [Section 8.1](#section-8.1), Paragraph 2.30.1; [Section 10.3](#section-10.3), Paragraph 1; [Section 10.3](#section-10.3), Paragraph 2; [Section 10.5.1](#section-10.5.1), Paragraph 2 MAX\_PUSH\_ID [Section 2](#section-2), Paragraph 5; [Section 4.6](#section-4.6), Paragraph 3; [Section 4.6](#section-4.6), Paragraph 3; [Section 4.6](#section-4.6), Paragraph 3; [Section 4.6](#section-4.6), Paragraph 3; Table 1; [Section 7.2.5](#section-7.2.5), Paragraph 5; \*\_[Section 7.2.7](#section-7.2.7)\_\*; Table 2; [Appendix A.1](#appendix-A.1), Paragraph 4; [Appendix A.3](#appendix-A.3), Paragraph 4.4.1 P push ID \*\_[Section 4.6](#section-4.6)\_\*; [Section 5.2](#section-5.2), Paragraph 1; [Section 5.2](#section-5.2), Paragraph 5, Item 2; [Section 5.2](#section-5.2), Paragraph 9; [Section 6.2.2](#section-6.2.2), Paragraph 2; [Section 6.2.2](#section-6.2.2), Paragraph 6; [Section 6.2.2](#section-6.2.2), Paragraph 6; [Section 7.2.3](#section-7.2.3), Paragraph 1; [Section 7.2.3](#section-7.2.3), Paragraph 7; [Section 7.2.3](#section-7.2.3), Paragraph 7; [Section 7.2.3](#section-7.2.3), Paragraph 8; [Section 7.2.3](#section-7.2.3), Paragraph 8; [Section 7.2.5](#section-7.2.5), Paragraph 4.2.1; [Section 7.2.5](#section-7.2.5), Paragraph 5; [Section 7.2.5](#section-7.2.5), Paragraph 5; [Section 7.2.5](#section-7.2.5), Paragraph 6; [Section 7.2.5](#section-7.2.5), Paragraph 6; [Section 7.2.5](#section-7.2.5), Paragraph 7; [Section 7.2.5](#section-7.2.5), Paragraph 7; [Section 7.2.5](#section-7.2.5), Paragraph 7; [Section 7.2.6](#section-7.2.6), Paragraph 4; [Section 7.2.7](#section-7.2.7), Paragraph 1; [Section 7.2.7](#section-7.2.7), Paragraph 4; [Section 7.2.7](#section-7.2.7), Paragraph 4; [Section 7.2.7](#section-7.2.7), Paragraph 6; [Section 7.2.7](#section-7.2.7), Paragraph 6; [Section 8.1](#section-8.1), Paragraph 2.18.1; [Appendix A.2.5](#appendix-A.2.5), Paragraph 1.12.1; [Appendix A.2.5](#appendix-A.2.5), Paragraph 1.16.1 push stream [Section 4.1](#section-4.1), Paragraph 8; [Section 4.1](#section-4.1), Paragraph 9; [Section 4.6](#section-4.6), Paragraph 3; [Section 4.6](#section-4.6), Paragraph 5; [Section 4.6](#section-4.6), Paragraph 5; [Section 4.6](#section-4.6), Paragraph 13; [Section 4.6](#section-4.6), Paragraph 13; [Section 4.6](#section-4.6), Paragraph 13; [Section 6.2](#section-6.2), Paragraph 3; \*\_[Section 6.2.2](#section-6.2.2)\_\*; [Section 7](#section-7), Paragraph 1; [Section 7.2.2](#section-7.2.2), Paragraph 3; [Section 7.2.3](#section-7.2.3), Paragraph 1; [Section 7.2.3](#section-7.2.3), Paragraph 2; [Section 7.2.3](#section-7.2.3), Paragraph 2; [Section 7.2.3](#section-7.2.3), Paragraph 2; [Section 7.2.3](#section-7.2.3), Paragraph 2; [Section 7.2.3](#section-7.2.3), Paragraph 3; [Section 7.2.3](#section-7.2.3), Paragraph 4; [Section 7.2.3](#section-7.2.3), Paragraph 4; [Section 7.2.3](#section-7.2.3), Paragraph 4; [Section 7.2.5](#section-7.2.5), Paragraph 4.2.1; [Section 7.2.7](#section-7.2.7), Paragraph 1; [Appendix A.2.5](#appendix-A.2.5), Paragraph 1.12.1 PUSH\_PROMISE [Section 2](#section-2), Paragraph 5; [Section 4.1](#section-4.1), Paragraph 8; [Section 4.1](#section-4.1), Paragraph 8; [Section 4.1](#section-4.1), Paragraph 8; [Section 4.1](#section-4.1), Paragraph 8; [Section 4.1](#section-4.1), Paragraph 10; [Section 4.6](#section-4.6), Paragraph 4; [Section 4.6](#section-4.6), Paragraph 10; [Section 4.6](#section-4.6), Paragraph 11; [Section 4.6](#section-4.6), Paragraph 11; [Section 4.6](#section-4.6), Paragraph 12; [Section 4.6](#section-4.6), Paragraph 12; [Section 4.6](#section-4.6), Paragraph 13; [Section 4.6](#section-4.6), Paragraph 13; [Section 4.6](#section-4.6), Paragraph 13; Table 1; [Section 7.2.3](#section-7.2.3), Paragraph 8; [Section 7.2.3](#section-7.2.3), Paragraph 8; \*\_[Section 7.2.5](#section-7.2.5)\_\*; [Section 7.2.7](#section-7.2.7), Paragraph 1; [Section 10.4](#section-10.4), Paragraph 1; [Section 10.5](#section-10.5), Paragraph 2; Table 2; [Appendix A.2.5](#appendix-A.2.5); [Appendix A.2.5](#appendix-A.2.5), Paragraph 1.12.1; [Appendix A.2.5](#appendix-A.2.5), Paragraph 1.12.1; [Appendix A.2.5](#appendix-A.2.5), Paragraph 1.20.1 R request stream [Section 4.1](#section-4.1), Paragraph 1; [Section 4.1](#section-4.1), Paragraph 15; [Section 4.1](#section-4.1), Paragraph 15; [Section 4.1.1](#section-4.1.1), Paragraph 1; [Section 4.1.1](#section-4.1.1), Paragraph 5; [Section 4.4](#section-4.4), Paragraph 5; [Section 4.4](#section-4.4), Paragraph 9; [Section 4.6](#section-4.6), Paragraph 4; [Section 4.6](#section-4.6), Paragraph 4; [Section 4.6](#section-4.6), Paragraph 11; [Section 4.6](#section-4.6), Paragraph 11; \*\_[Section 6.1](#section-6.1)\_\*; [Section 7](#section-7), Paragraph 1; [Section 7.2.2](#section-7.2.2), Paragraph 3; [Section 7.2.5](#section-7.2.5), Paragraph 1 S SETTINGS [Section 3.2](#section-3.2), Paragraph 4; [Section 3.2](#section-3.2), Paragraph 4; [Section 6.2.1](#section-6.2.1), Paragraph 2; Table 1; [Section 7](#section-7), Paragraph 3; \*\_[Section 7.2.4](#section-7.2.4)\_\*; [Section 8.1](#section-8.1), Paragraph 2.20.1; [Section 8.1](#section-8.1), Paragraph 2.22.1; [Section 9](#section-9), Paragraph 4; [Section 10.5](#section-10.5), Paragraph 4; Table 2; Table 4; Table 4; [Appendix A.2.5](#appendix-A.2.5); [Appendix A.2.5](#appendix-A.2.5), Paragraph 1.10.1; [Appendix A.3](#appendix-A.3), Paragraph 2; [Appendix A.3](#appendix-A.3), Paragraph 3; [Appendix A.3](#appendix-A.3), Paragraph 4.4.1; [Appendix A.3](#appendix-A.3), Paragraph 4.6.1; [Appendix A.3](#appendix-A.3), Paragraph 4.8.1; [Appendix A.3](#appendix-A.3), Paragraph 4.10.1; [Appendix A.4](#appendix-A.4), Paragraph 3.10.1 SETTINGS\_MAX\_FIELD\_SECTION\_SIZE [Section 4.2.2](#section-4.2.2), Paragraph 2; [Section 7.2.4.1](#section-7.2.4.1); [Section 10.5.1](#section-10.5.1), Paragraph 2; [Appendix A.3](#appendix-A.3), Paragraph 4.12.1 stream error [Section 2.2](#section-2.2); [Section 4.1.2](#section-4.1.2), Paragraph 4; [Section 4.4](#section-4.4), Paragraph 10; \*\_[Section 8](#section-8)\_\*; [Appendix A.4.1](#appendix-A.4.1), Paragraph 3; [Appendix A.4.1](#appendix-A.4.1), Paragraph 3; [Appendix A.4.1](#appendix-A.4.1), Paragraph 4 Author's Address Mike Bishop (editor) Akamai Email: [email protected]
programming_docs
http Client hints Client hints ============ HTTP Client hints ================= **Client hints** are a set of [HTTP request header](headers) fields that a server can proactively request from a client to get information about the device, network, user, and user-agent-specific preferences. The server can determine which resources to send, based on the information that the client chooses to provide. The set of "hint" headers are listed in the topic [HTTP Headers](headers#client_hints) and [summarized below](#hint_types). Overview -------- A server must announce that it supports client hints, using the [`Accept-CH`](headers/accept-ch) header to specify the hints that it is interested in receiving. When a client that supports client hints receives the `Accept-CH` header it can choose to append some or all of the listed client hint headers in its subsequent requests. For example, following `Accept-CH` in a response below, the client could append [`Width`](headers/width), [`Downlink`](headers/downlink) and [`Sec-CH-UA`](headers/sec-ch-ua) headers to all subsequent requests. ``` Accept-CH: Width, Downlink, Sec-CH-UA ``` This approach is efficient in that the server only requests the information that it is able to usefully handle. It is also relatively "privacy-preserving", in that it is up to the client to decide what information it can safely share. There is a small set of [low entropy client hint headers](#low_entropy_hints) that may be sent by a client event if not requested. **Note:** Client hints can also be specified in HTML using the [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) element with the [`http-equiv`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#attr-http-equiv) attribute. ``` <meta http-equiv="Accept-CH" content="Width, Downlink, Sec-CH-UA" /> ``` Caching and Client Hints ------------------------ Client hints that determine which resources are sent in responses should generally also be included in the affected response's [`Vary`](headers/vary) header. This ensures that a different resource is cached for every different value of the hint header. ``` Vary: Accept, Width, ECT ``` You may prefer to omit specifying [`Vary`](headers/vary) or use some other strategy for client hint headers where the value changes a lot, as this effectively makes the resource uncacheable. (A new cache entry is created for every unique value.) This applies in particular to network client hints like [`Downlink`](headers/downlink) and [`RTT`](headers/rtt). For more information see [HTTP Caching > Varying responses](caching#varying_responses). Hint life-time -------------- A server specifies the client hint headers that it is interested in getting in the `Accept-CH` response header. The user agent appends the requested client hint headers, or at least the subset that it wants to share with that server, to all subsequent requests in the current browsing session. In other words, the request for a specific set of hints does not expire until the browser is shut down. A server can replace the set of client hints it is interested in receiving by resending the `Accept-CH` response header with a new list. For example, to stop requesting any hints it would send `Accept-CH` with an empty list. Low entropy hints ----------------- Client hints are broadly divided into high and low entropy hints. The low entropy hints are those that don't give away much information that might be used to "fingerprint" (identify) a particular user. They may be sent by default on every client request, irrespective of the server `Accept-CH` response header, depending on the permission policy. These hints include: [`Save-Data`](headers/save-data), [`Sec-CH-UA`](headers/sec-ch-ua), [`Sec-CH-UA-Mobile`](headers/sec-ch-ua-mobile), [`Sec-CH-UA-Platform`](headers/sec-ch-ua-platform). The high entropy hints are those that have the potential to give away more information that can be used for user fingerprinting, and therefore are gated in such a way that the user agent can make a decision as to whether to provide them. The decision might be based on user preferences, a permission request, or the permission policy. All client hints that are not low entropy hints are considered high entropy hints. Hint types ---------- ### User-agent client hints User agent (UA) client hint headers allow a server to vary responses based on the user agent (browser), operating system, and device. Headers include: [`Sec-CH-UA`](headers/sec-ch-ua), [`Sec-CH-UA-Arch`](headers/sec-ch-ua-arch), [`Sec-CH-UA-Bitness`](headers/sec-ch-ua-bitness), [`Sec-CH-UA-Full-Version-List`](headers/sec-ch-ua-full-version-list), [`Sec-CH-UA-Full-Version`](headers/sec-ch-ua-full-version), [`Sec-CH-UA-Mobile`](headers/sec-ch-ua-mobile), [`Sec-CH-UA-Model`](headers/sec-ch-ua-model), [`Sec-CH-UA-Platform`](headers/sec-ch-ua-platform), and [`Sec-CH-UA-Platform-Version`](headers/sec-ch-ua-platform-version). Client hints are available to web page JavaScript via the [User Agent Client Hints API](https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API). **Note:** Servers currently get most of the same information by parsing the [`User-Agent`](headers/user-agent) header. For historical reasons this header contains a lot of largely irrelevant information, and information that might be used to identify a *particular user*. UA client hints provide a more efficient and privacy preserving way of getting the desired information. They are eventually expected to replace this older approach. ### Device client hints Device client hints allow a server to vary responses based on device characteristics including available memory and screen properties. Headers include: [`Device-Memory`](headers/device-memory), [`DPR`](headers/dpr), [`Width`](headers/width), [`Viewport-Width`](headers/viewport-width). ### Network client hints Network client hints allow a server to vary responses based on the user's choice, network bandwidth, and latency. Headers include: [`Save-Data`](headers/save-data), [`Downlink`](headers/downlink), [`ECT`](headers/ect), [`RTT`](headers/rtt). See also -------- * [Client Hints headers](headers#client_hints) * [`Vary` HTTP Header](headers/vary) * [Client Hints Infrastructure](https://wicg.github.io/client-hints-infrastructure/) * [User Agent Client Hints API](https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API) * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) http Session Session ======= A typical HTTP session ====================== In client-server protocols, like HTTP, sessions consist of three phases: 1. The client establishes a TCP connection (or the appropriate connection if the transport layer is not TCP). 2. The client sends its request, and waits for the answer. 3. The server processes the request, sending back its answer, providing a status code and appropriate data. As of HTTP/1.1, the connection is no longer closed after completing the third phase, and the client is now granted a further request: this means the second and third phases can now be performed any number of times. Establishing a connection ------------------------- In client-server protocols, it is the client which establishes the connection. Opening a connection in HTTP means initiating a connection in the underlying transport layer, usually this is TCP. With TCP the default port, for an HTTP server on a computer, is port 80. Other ports can also be used, like 8000 or 8080. The URL of a page to fetch contains both the domain name, and the port number, though the latter can be omitted if it is 80. See [Identifying resources on the Web](basics_of_http/identifying_resources_on_the_web) for more details. **Note:** The client-server model does not allow the server to send data to the client without an explicit request for it. To work around this problem, web developers use several techniques: ping the server periodically via the [`XMLHTTPRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) APIs, using the [WebSockets API](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API), or similar protocols. Sending a client request ------------------------ Once the connection is established, the user-agent can send the request (a user-agent is typically a web browser, but can be anything else, a crawler, for example). A client request consists of text directives, separated by CRLF (carriage return, followed by line feed), divided into three blocks: 1. The first line contains a request method followed by its parameters: * the path of the document, as an absolute URL without the protocol or domain name * the HTTP protocol version 2. Subsequent lines represent an HTTP header, giving the server information about what type of data is appropriate (for example, what language, what MIME types), or other data altering its behavior (for example, not sending an answer if it is already cached). These HTTP headers form a block which ends with an empty line. 3. The final block is an optional data block, which may contain further data mainly used by the POST method. ### Example requests Fetching the root page of developer.mozilla.org, (`https://developer.mozilla.org/`), and telling the server that the user-agent would prefer the page in French, if possible: ``` GET / HTTP/1.1 Host: developer.mozilla.org Accept-Language: fr ``` Observe that final empty line, this separates the data block from the header block. As there is no `Content-Length` provided in an HTTP header, this data block is presented empty, marking the end of the headers, allowing the server to process the request the moment it receives this empty line. For example, sending the result of a form: ``` POST /contact\_form.php HTTP/1.1 Host: developer.mozilla.org Content-Length: 64 Content-Type: application/x-www-form-urlencoded name=Joe%20User&request=Send%20me%20one%20of%20your%20catalogue ``` ### Request methods HTTP defines a set of [request methods](methods) indicating the desired action to be performed upon a resource. Although they can also be nouns, these requests methods are sometimes referred as HTTP verbs. The most common requests are `GET` and `POST`: * The [`GET`](methods/get) method requests a data representation of the specified resource. Requests using `GET` should only retrieve data. * The [`POST`](methods/post) method sends data to a server so it may change its state. This is the method often used for [HTML Forms](https://developer.mozilla.org/en-US/docs/Learn/Forms). Structure of a server response ------------------------------ After the connected agent has sent its request, the web server processes it, and ultimately returns a response. Similar to a client request, a server response is formed of text directives, separated by CRLF, though divided into three blocks: 1. The first line, the *status line*, consists of an acknowledgment of the HTTP version used, followed by a response status code (and its brief meaning in human-readable text). 2. Subsequent lines represent specific HTTP headers, giving the client information about the data sent (for example, type, data size, compression algorithm used, hints about caching). Similarly to the block of HTTP headers for a client request, these HTTP headers form a block ending with an empty line. 3. The final block is a data block, which contains the optional data. ### Example responses Successful web page response: ``` HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 Content-Length: 55743 Connection: keep-alive Cache-Control: s-maxage=300, public, max-age=0 Content-Language: en-US Date: Thu, 06 Dec 2018 17:37:18 GMT ETag: "2e77ad1dc6ab0b53a2996dfd4653c1c3" Server: meinheld/0.6.1 Strict-Transport-Security: max-age=63072000 X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-Protection: 1; mode=block Vary: Accept-Encoding,Cookie Age: 7 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>A simple webpage</title> </head> <body> <h1>Simple HTML webpage</h1> <p>Hello, world!</p> </body> </html> ``` Notification that the requested resource has permanently moved: ``` HTTP/1.1 301 Moved Permanently Server: Apache/2.4.37 (Red Hat) Content-Type: text/html; charset=utf-8 Date: Thu, 06 Dec 2018 17:33:08 GMT Location: https://developer.mozilla.org/ (this is the new link to the resource; it is expected that the user-agent will fetch it) Keep-Alive: timeout=15, max=98 Accept-Ranges: bytes Via: Moz-Cache-zlb05 Connection: Keep-Alive Content-Length: 325 (the content contains a default page to display if the user-agent is not able to follow the link) <!DOCTYPE html>… (contains a site-customized page helping the user to find the missing resource) ``` Notification that the requested resource doesn't exist: ``` HTTP/1.1 404 Not Found Content-Type: text/html; charset=utf-8 Content-Length: 38217 Connection: keep-alive Cache-Control: no-cache, no-store, must-revalidate, max-age=0 Content-Language: en-US Date: Thu, 06 Dec 2018 17:35:13 GMT Expires: Thu, 06 Dec 2018 17:35:13 GMT Server: meinheld/0.6.1 Strict-Transport-Security: max-age=63072000 X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-Protection: 1; mode=block Vary: Accept-Encoding,Cookie X-Cache: Error from cloudfront <!DOCTYPE html>… (contains a site-customized page helping the user to find the missing resource) ``` ### Response status codes [HTTP response status codes](status) indicate if a specific HTTP request has been successfully completed. Responses are grouped into five classes: informational responses, successful responses, redirects, client errors, and servers errors. * [`200`](status/200): OK. The request has succeeded. * [`301`](status/301): Moved Permanently. This response code means that the URI of requested resource has been changed. * [`404`](status/404): Not Found. The server cannot find the requested resource. See also -------- * [Identifying resources on the Web](basics_of_http/identifying_resources_on_the_web) * [HTTP headers](headers) * [HTTP request methods](methods) * [HTTP response status codes](status) http Conditional requests Conditional requests ==================== HTTP conditional requests ========================= HTTP has a concept of *conditional requests*, where the result, and even the success of a request, can be changed by comparing the affected resources with the value of a *validator*. Such requests can be useful to validate the content of a cache, and sparing a useless control, to verify the integrity of a document, like when resuming a download, or when preventing lost updates when uploading or modifying a document on the server. Principles ---------- HTTP conditional requests are requests that are executed differently, depending on the value of specific headers. These headers define a precondition, and the result of the request will be different if the precondition is matched or not. The different behaviors are defined by the method of the request used, and by the set of headers used for a precondition: * for [safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) methods, like [`GET`](methods/get), which usually tries to fetch a document, the conditional request can be used to send back the document, if relevant only. Therefore, this spares bandwidth. * for [unsafe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) methods, like [`PUT`](methods/put), which usually uploads a document, the conditional request can be used to upload the document, only if the original it is based on is the same as that stored on the server. Validators ---------- All conditional headers try to check if the resource stored on the server matches a specific version. To achieve this, the conditional requests need to indicate the version of the resource. As comparing the whole resource byte to byte is impracticable, and not always what is wanted, the request transmits a value describing the version. Such values are called *validators*, and are of two kinds: * the date of last modification of the document, the *last-modified* date. * an opaque string, uniquely identifying each version, called the *entity tag*, or the *etag*. Comparing versions of the same resource is a bit tricky: depending on the context, there are two kinds of *equality checks*: * *Strong validation* is used when byte to byte identity is expected, for example when resuming a download. * *Weak validation* is used when the user-agent only needs to determine if the two resources have the same content. This is even if they are minor differences; like different ads, or a footer with a different date. The kind of validation is independent of the validator used. Both [`Last-Modified`](headers/last-modified) and [`ETag`](headers/etag) allow both types of validation, though the complexity to implement it on the server side may vary. HTTP uses strong validation by default, and it specifies when weak validation can be used. ### Strong validation Strong validation consists of guaranteeing that the resource is, byte to byte, identical to the one it is compared to. This is mandatory for some conditional headers, and the default for the others. Strong validation is very strict and may be difficult to guarantee at the server level, but it does guarantee no data loss at any time, sometimes at the expense of performance. It is quite difficult to have a unique identifier for strong validation with [`Last-Modified`](headers/last-modified). Often this is done using an [`ETag`](headers/etag) with the MD5 hash of the resource (or a derivative). ### Weak validation Weak validation differs from strong validation, as it considers two versions of the document as identical if the content is equivalent. For example, a page that would differ from another only by a different date in its footer, or different advertising, would be considered *identical* to the other with weak validation. These same two versions are considered *different* when using strong validation. Building a system of etags that creates weak validation may be complex, as it involves knowing the importance of the different elements of a page, but is very useful towards optimizing cache performance. Conditional headers ------------------- Several HTTP headers, called conditional headers, lead to conditional requests. These are: [`If-Match`](headers/if-match) Succeeds if the [`ETag`](headers/etag) of the distant resource is equal to one listed in this header. By default, unless the etag is prefixed with `'W/'`, it performs a strong validation. [`If-None-Match`](headers/if-none-match) Succeeds if the [`ETag`](headers/etag) of the distant resource is different to each listed in this header. By default, unless the etag is prefixed with `'W/'`, it performs a strong validation. [`If-Modified-Since`](headers/if-modified-since) Succeeds if the [`Last-Modified`](headers/last-modified) date of the distant resource is more recent than the one given in this header. [`If-Unmodified-Since`](headers/if-unmodified-since) Succeeds if the [`Last-Modified`](headers/last-modified) date of the distant resource is older or the same as the one given in this header. [`If-Range`](headers/if-range) Similar to [`If-Match`](headers/if-match), or [`If-Unmodified-Since`](headers/if-unmodified-since), but can have only one single etag, or one date. If it fails, the range request fails, and instead of a [`206`](status/206) `Partial Content` response, a [`200`](status/200) `OK` is sent with the complete resource. Use cases --------- ### Cache update The most common use case for conditional requests is updating a cache. With an empty cache, or without a cache, the requested resource is sent back with a status of [`200`](status/200) `OK`. Together with the resource, the validators are sent in the headers. In this example, both [`Last-Modified`](headers/last-modified) and [`ETag`](headers/etag) are sent, but it could equally have been only one of them. These validators are cached with the resource (like all headers) and will be used to craft conditional requests, once the cache becomes stale. As long as the cache is not stale, no requests are issued at all. But once it has become stale, this is mostly controlled by the [`Cache-Control`](headers/cache-control) header, the client doesn't use the cached value directly but issues a *conditional request*. The value of the validator is used as a parameter of the [`If-Modified-Since`](headers/if-modified-since) and [`If-None-Match`](headers/if-none-match) headers. If the resource has not changed, the server sends back a [`304`](status/304) `Not Modified` response. This makes the cache fresh again, and the client uses the cached resource. Although there is a response/request round-trip that consumes some resources, this is more efficient than to transmit the whole resource over the wire again. If the resource has changed, the server just sends back a [`200 OK`](status/200) response, with the new version of the resource (as though the request wasn't conditional). The client uses this new resource (and caches it). Besides the setting of the validators on the server side, this mechanism is transparent: all browsers manage a cache and send such conditional requests without any special work to be done by Web developers. ### Integrity of a partial download Partial downloading of files is a functionality of HTTP that allows resuming previous operations, saving bandwidth and time, by keeping the already obtained information: A server supporting partial downloads broadcasts this by sending the [`Accept-Ranges`](headers/accept-ranges) header. Once this happens, the client can resume a download by sending a [`Ranges`](headers/range) header with the missing ranges: The principle is simple, but there is one potential problem: if the downloaded resource has been modified between both downloads, the obtained ranges will correspond to two different versions of the resource, and the final document will be corrupted. To prevent this, conditional requests are used. For ranges, there are two ways of doing this. The more flexible one makes use of [`If-Unmodified-Since`](headers/if-unmodified-since) and [`If-Match`](headers/if-match) and the server returns an error if the precondition fails; the client then restarts the download from the beginning: Even if this method works, it adds an extra response/request exchange when the document has been changed. This impairs performance, and HTTP has a specific header to avoid this scenario: [`If-Range`](headers/if-range): This solution is more efficient, but slightly less flexible, as only one etag can be used in the condition. Rarely is such additional flexibility needed. ### Avoiding the lost update problem with optimistic locking A common operation in Web applications is to *update* a remote document. This is very common in any file system or source control applications, but any application that allows to store remote resources needs such a mechanism. Common Web sites, like wikis and other CMS, have such a need. With the [`PUT`](methods/put) method you are able to implement this. The client first reads the original files, modifies them, and finally pushes them to the server: Unfortunately, things get a little inaccurate as soon as we take into account concurrency. While a client is locally modifying its new copy of the resource, a second client can fetch the same resource and do the same on its copy. What happens next is very unfortunate: when they commit back to the server, the modifications from the first client are discarded by the next client push, as this second client is unaware of the first client's changes to the resource. The decision on who wins is not communicated to the other party. Which client's changes are to be kept, will vary with the speed they commit; this depends on the performance of the clients, of the server, and even of the human editing the document at the client. The winner will change from one time to the next. This is a *race condition* and leads to problematic behaviors, which are difficult to detect and to debug: There is no way to deal with this problem without annoying one of the two clients. However, lost updates and race conditions are to be avoided. We want predictable results, and expect that the clients are notified when their changes are rejected. Conditional requests allow implementing the *optimistic locking algorithm* (used by most wikis or source control systems). The concept is to allow all clients to get copies of the resource, then let them modify it locally, controlling concurrency by successfully allowing the first client to submit an update. All subsequent updates, based on the now obsolete version of the resource, are rejected: This is implemented using the [`If-Match`](headers/if-match) or [`If-Unmodified-Since`](headers/if-unmodified-since) headers. If the etag doesn't match the original file, or if the file has been modified since it has been obtained, the change is rejected with a [`412`](status/412) `Precondition Failed` error. It is then up to the client to deal with the error: either by notifying the user to start again (this time on the newest version), or by showing the user a *diff* of both versions, helping them decide which changes they wish to keep. ### Dealing with the first upload of a resource The first upload of a resource is an edge case of the previous. Like any update of a resource, it is subject to a race condition if two clients try to perform at similar times. To prevent this, conditional requests can be used: by adding [`If-None-Match`](headers/if-none-match) with the special value of `'*'`, representing any etag. The request will succeed, only if the resource didn't exist before: `If-None-Match` will only work with HTTP/1.1 (and later) compliant servers. If unsure if the server will be compliant, you need first to issue a [`HEAD`](methods/head) request to the resource to check this. Conclusion ---------- Conditional requests are a key feature of HTTP, and allow the building of efficient and complex applications. For caching or resuming downloads, the only work required for webmasters is to configure the server correctly; setting correct etags in some environments can be tricky. Once achieved, the browser will serve the expected conditional requests. For locking mechanisms, it is the opposite: Web developers need to issue a request with the proper headers, while webmasters can mostly rely on the application to carry out the checks for them. In both cases it's clear, conditional requests are a fundamental feature behind the Web.
programming_docs
http Proxy servers and tunneling: Proxy Auto-Configuration PAC file Proxy servers and tunneling: Proxy Auto-Configuration PAC file ============================================================== Proxy Auto-Configuration (PAC) file =================================== A **Proxy Auto-Configuration (PAC)** file is a JavaScript function that determines whether web browser requests (HTTP, HTTPS, and FTP) go directly to the destination or are forwarded to a web proxy server. The JavaScript function contained in the PAC file defines the function: Syntax ------ ``` function FindProxyForURL(url, host) { // … } ``` ### Parameters `url` The URL being accessed. The path and query components of `https://` URLs are stripped. In Chrome (versions 52 to 73), you can disable this by setting `PacHttpsUrlStrippingEnabled` to `false` in policy or by launching with the `--unsafe-pac-url` command-line flag (in Chrome 74, only the flag works, and from 75 onward, there is no way to disable path-stripping; as of Chrome 81, path-stripping does not apply to HTTP URLs, but there is interest in changing this behavior to match HTTPS); in Firefox, the preference is `network.proxy.autoconfig_url.include_path`. `host` The hostname extracted from the URL. This is only for convenience; it is the same string as between `://` and the first `:` or `/` after that. The port number is not included in this parameter. It can be extracted from the URL when necessary. Description ----------- Returns a string describing the configuration. The format of this string is defined in **return value format** below. ### Return value format * The JavaScript function returns a single string * If the string is null, no proxies should be used * The string can contain any number of the following building blocks, separated by a semicolon: `DIRECT` Connections should be made directly, without any proxies `PROXY host:port` The specified proxy should be used `SOCKS host:port` The specified SOCKS server should be used Recent versions of Firefox support as well: `HTTP host:port` The specified proxy should be used `HTTPS host:port` The specified HTTPS proxy should be used `SOCKS4 host:port`, `SOCKS5 host:port` The specified SOCKS server (with the specified SOCK version) should be used If there are multiple semicolon-separated settings, the left-most setting will be used, until Firefox fails to establish the connection to the proxy. In that case, the next value will be used, etc. The browser will automatically retry a previously unresponsive proxy after 30 minutes. Additional attempts will continue beginning at one hour, always adding 30 minutes to the elapsed time between attempts. If all proxies are down, and there was no DIRECT option specified, the browser will ask if proxies should be temporarily ignored, and direct connections attempted. After 20 minutes, the browser will ask if proxies should be retried, asking again after an additional 40 minutes. Queries will continue, always adding 20 minutes to the elapsed time between queries. #### Examples `PROXY w3proxy.netscape.com:8080; PROXY mozilla.netscape.com:8081` Primary proxy is w3proxy:8080; if that goes down start using mozilla:8081 until the primary proxy comes up again. `PROXY w3proxy.netscape.com:8080; PROXY mozilla.netscape.com:8081; DIRECT` Same as above, but if both proxies go down, automatically start making direct connections. (In the first example above, Netscape will ask user confirmation about making direct connections; in this case, there is no user intervention.) `PROXY w3proxy.netscape.com:8080; SOCKS socks:1080` Use SOCKS if the primary proxy goes down. The auto-config file should be saved to a file with a .pac filename extension: `proxy.pac`. And the MIME type should be set to `application/x-ns-proxy-autoconfig`. Next, you should configure your server to map the .pac filename extension to the MIME type. **Note:** * The JavaScript function should always be saved to a file by itself but not be embedded in a HTML file or any other file. * The examples at the end of this document are complete. There is no additional syntax needed to save it into a file and use it. (Of course, the JavaScripts must be edited to reflect your site's domain name and/or subnets.) Predefined functions and environment ------------------------------------ These functions can be used in building the PAC file: * Hostname based conditions + [`isPlainHostName()`](#isplainhostname) + [`dnsDomainIs()`](#dnsdomainis) + [`localHostOrDomainIs()`](#localhostordomainis) + [`isResolvable()`](#isresolvable) + [`isInNet()`](#isinnet) * Related utility functions + [`dnsResolve()`](#dnsresolve) + [`convert_addr()`](#convert_addr) + [`myIpAddress()`](#myipaddress) + [`dnsDomainLevels()`](#dnsdomainlevels) * URL/hostname based conditions + [`shExpMatch()`](#shexpmatch) * Time based conditions + [`weekdayRange()`](#weekdayrange) + [`dateRange()`](#daterange) + [`timeRange()`](#timerange) * Logging utility + [`alert()`](#alert) * There was one associative array (object) already defined, because at the time JavaScript code was unable to define it by itself: + `ProxyConfig.bindings` Deprecated **Note:** pactester (part of the [pacparser](https://github.com/manugarg/pacparser) package) was used to test the following syntax examples. * The PAC file is named `proxy.pac` * Command line: `pactester -p ~/pacparser-master/tests/proxy.pac -u http://www.mozilla.org` (passes the `host` parameter `www.mozilla.org` and the `url` parameter `http://www.mozilla.org`) ### isPlainHostName() #### Syntax ``` isPlainHostName(host) ``` #### Parameters host The hostname from the URL (excluding port number). #### Description True if and only if there is no domain name in the hostname (no dots). #### Examples ``` isPlainHostName("www.mozilla.org") // false isPlainHostName("www") // true ``` ### `dnsDomainIs()` #### Syntax ``` dnsDomainIs(host, domain) ``` #### Parameters host Is the hostname from the URL. domain Is the domain name to test the hostname against. #### Description Returns true if and only if the domain of hostname matches. #### Examples ``` dnsDomainIs("www.mozilla.org", ".mozilla.org") // true dnsDomainIs("www", ".mozilla.org") // false ``` ### localHostOrDomainIs() #### Syntax ``` localHostOrDomainIs(host, hostdom) ``` #### Parameters host The hostname from the URL. hostdom Fully qualified hostname to match against. #### Description Is true if the hostname matches *exactly* the specified hostname, or if there is no domain name part in the hostname, but the unqualified hostname matches. #### Examples ``` localHostOrDomainIs("www.mozilla.org", "www.mozilla.org") // true (exact match) localHostOrDomainIs("www", "www.mozilla.org") // true (hostname match, domain not specified) localHostOrDomainIs("www.google.com", "www.mozilla.org") // false (domain name mismatch) localHostOrDomainIs("home.mozilla.org", "www.mozilla.org") // false (hostname mismatch) ``` ### isResolvable() #### Syntax ``` isResolvable(host) ``` #### Parameters host is the hostname from the URL. Tries to resolve the hostname. Returns true if succeeds. #### Examples ``` isResolvable("www.mozilla.org") // true ``` ### isInNet() #### Syntax ``` isInNet(host, pattern, mask) ``` #### Parameters host a DNS hostname, or IP address. If a hostname is passed, it will be resolved into an IP address by this function. pattern an IP address pattern in the dot-separated format. mask mask for the IP address pattern informing which parts of the IP address should be matched against. 0 means ignore, 255 means match. True if and only if the IP address of the host matches the specified IP address pattern. Pattern and mask specification is done the same way as for SOCKS configuration. #### Examples ``` function alertEval(str) { alert(`${str} is ${eval(str)}`); } function FindProxyForURL(url, host) { alertEval('isInNet(host, "63.245.213.24", "255.255.255.255")'); // "PAC-alert: isInNet(host, "63.245.213.24", "255.255.255.255") is true" } ``` ### dnsResolve() ``` dnsResolve(host) ``` #### Parameters host hostname to resolve. Resolves the given DNS hostname into an IP address, and returns it in the dot-separated format as a string. #### Example ``` dnsResolve("www.mozilla.org"); // returns the string "104.16.41.2" ``` ### convert\_addr() #### Syntax ``` convert\_addr(ipaddr) ``` #### Parameters ipaddr Any dotted address such as an IP address or mask. Concatenates the four dot-separated bytes into one 4-byte word and converts it to decimal. #### Example ``` convert\_addr("104.16.41.2"); // returns the decimal number 1745889538 ``` ### myIpAddress() #### Syntax ``` myIpAddress() ``` #### Parameters (none) #### Return value Returns the server IP address of the machine Firefox is running on, as a string in the dot-separated integer format. **Warning:** myIpAddress() returns the same IP address as the server address returned by `nslookup localhost` on a Linux machine. It does not return the public IP address. #### Example ``` myIpAddress() //returns the string "127.0.1.1" if you were running Firefox on that localhost ``` ### dnsDomainLevels() #### Syntax ``` dnsDomainLevels(host) ``` #### Parameters host is the hostname from the URL. Returns the number (integer) of DNS domain levels (number of dots) in the hostname. #### Examples ``` dnsDomainLevels("www"); // 0 dnsDomainLevels("mozilla.org"); // 1 dnsDomainLevels("www.mozilla.org"); // 2 ``` ### shExpMatch() #### Syntax ``` shExpMatch(str, shexp) ``` #### Parameters str is any string to compare (e.g. the URL, or the hostname). shexp is a shell expression to compare against. Returns `true` if the string matches the specified shell glob expression. Support for particular glob expression syntax varies across browsers: `*` (match any number of characters) and `?` (match one character) are always supported, while `[characters]` and `[^characters]` are additionally supported by some implementations (including Firefox). **Note:** If supported by the client, JavaScript regular expressions typically provide a more powerful and consistent way to pattern-match URLs (and other strings). #### Examples ``` shExpMatch("http://home.netscape.com/people/ari/index.html", "\*/ari/\*"); // returns true shExpMatch("http://home.netscape.com/people/montulli/index.html", "\*/ari/\*"); // returns false ``` ### weekdayRange() #### Syntax ``` weekdayRange(wd1, wd2, [gmt]) ``` **Note:** (Before Firefox 49) wd1 must be less than wd2 if you want the function to evaluate these parameters as a range. See the warning below. #### Parameters wd1 and wd2 One of the ordered weekday strings: `"SUN"`, `"MON"`, `"TUE"`, `"WED"`, `"THU"`, `"FRI"`, `"SAT"` gmt Is either the string "GMT" or is left out. Only the first parameter is mandatory. Either the second, the third, or both may be left out. If only one parameter is present, the function returns a value of true on the weekday that the parameter represents. If the string "GMT" is specified as a second parameter, times are taken to be in GMT. Otherwise, they are assumed to be in the local timezone. If both **wd1** and **wd1** are defined, the condition is true if the current weekday is in between those two *ordered* weekdays. Bounds are inclusive, *but the bounds are ordered*. If the "GMT" parameter is specified, times are taken to be in GMT. Otherwise, the local timezone is used. **Warning:** *The order of the days matters*. Before Firefox 49, `weekdayRange("SUN", "SAT")` will always evaluate to `true`. Now `weekdayRange("WED", "SUN")` will only evaluate to `true` if the current day is Wednesday or Sunday. #### Examples ``` weekdayRange("MON", "FRI"); // returns true Monday through Friday (local timezone) weekdayRange("MON", "FRI", "GMT"); // returns true Monday through Friday (GMT timezone) weekdayRange("SAT"); // returns true on Saturdays local time weekdayRange("SAT", "GMT"); // returns true on Saturdays GMT time weekdayRange("FRI", "MON"); // returns true Friday and Monday only (note, order does matter!) ``` ### dateRange() #### Syntax ``` dateRange(<day> | <month> | <year>, [gmt]) // ambiguity is resolved by assuming year is greater than 31 dateRange(<day1>, <day2>, [gmt]) dateRange(<month1>, <month2>, [gmt]) dateRange(<year1>, <year2>, [gmt]) dateRange(<day1>, <month1>, <day2>, <month2>, [gmt]) dateRange(<month1>, <year1>, <month2>, <year2>, [gmt]) dateRange(<day1>, <month1>, <year1>, <day2>, <month2>, <year2>, [gmt]) ``` **Note:** (Before Firefox 49) day1 must be less than day2, month1 must be less than month2, and year1 must be less than year2 if you want the function to evaluate these parameters as a range. See the warning below. #### Parameters day Is the ordered day of the month between 1 and 31 (as an integer). ``` 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 ``` month Is one of the ordered month strings below. ``` "JAN"|"FEB"|"MAR"|"APR"|"MAY"|"JUN"|"JUL"|"AUG"|"SEP"|"OCT"|"NOV"|"DEC" ``` year Is the ordered full year integer number. For example, 2016 (**not** 16). gmt Is either the string "GMT", which makes time comparison occur in GMT timezone, or is left out. If left unspecified, times are taken to be in the local timezone. If only a single value is specified (from each category: day, month, year), the function returns a true value only on days that match that specification. If both values are specified, the result is true between those times, including bounds, *but the bounds are ordered*. **Warning:** **The order of the days, months, and years matter**; Before Firefox 49, `dateRange("JAN", "DEC")` will always evaluate to `true`. Now `dateRange("DEC", "JAN")` will only evaluate true if the current month is December or January. #### Examples ``` dateRange(1); // returns true on the first day of each month, local timezone dateRange(1, "GMT") // returns true on the first day of each month, GMT timezone dateRange(1, 15); // returns true on the first half of each month dateRange(24, "DEC"); // returns true on 24th of December each year dateRange("JAN", "MAR"); // returns true on the first quarter of the year dateRange(1, "JUN", 15, "AUG"); // returns true from June 1st until August 15th, each year // (including June 1st and August 15th) dateRange(1, "JUN", 1995, 15, "AUG", 1995); // returns true from June 1st, 1995, until August 15th, same year dateRange("OCT", 1995, "MAR", 1996); // returns true from October 1995 until March 1996 // (including the entire month of October 1995 and March 1996) dateRange(1995); // returns true during the entire year of 1995 dateRange(1995, 1997); // returns true from beginning of year 1995 until the end of year 1997 ``` ### timeRange() #### Syntax ``` // The full range of expansions is analogous to dateRange. timeRange(<hour1>, <min1>, <sec1>, <hour2>, <min2>, <sec2>, [gmt]) ``` **Note:** (Before Firefox 49) the category hour1, min1, sec1 must be less than the category hour2, min2, sec2 if you want the function to evaluate these parameters as a range. See the warning below. #### Parameters hour Is the hour from 0 to 23. (0 is midnight, 23 is 11 pm.) min Minutes from 0 to 59. sec Seconds from 0 to 59. gmt Either the string "GMT" for GMT timezone, or not specified, for local timezone. If only a single value is specified (from each category: hour, minute, second), the function returns a true value only at times that match that specification. If both values are specified, the result is true between those times, including bounds, *but the bounds are ordered*. **Warning:** **The order of the hour, minute, second matter**; Before Firefox 49, `timeRange(0, 23)` will always evaluate to true. Now `timeRange(23, 0)` will only evaluate true if the current hour is 23:00 or midnight. #### Examples ``` timerange(12); // returns true from noon to 1pm timerange(12, 13); // returns true from noon to 1pm timerange(12, "GMT"); // returns true from noon to 1pm, in GMT timezone timerange(9, 17); // returns true from 9am to 5pm timerange(8, 30, 17, 0); // returns true from 8:30am to 5:00pm timerange(0, 0, 0, 0, 0, 30); // returns true between midnight and 30 seconds past midnight ``` ### alert() #### Syntax ``` alert(message) ``` #### Parameters message The string to log Logs the message in the browser console. #### Examples ``` alert(`${host} = ${dnsResolve(host)}`); // logs the host name and its IP address alert("Error: shouldn't reach this clause."); // log a simple message ``` Example 1 --------- ### Use proxy for everything except local hosts **Note:** Since all of the examples that follow are very specific, they have not been tested. All hosts which aren't fully qualified, or the ones that are in local domain, will be connected to directly. Everything else will go through `w3proxy.mozilla.org:8080`. If the proxy goes down, connections become direct automatically: ``` function FindProxyForURL(url, host) { if (isPlainHostName(host) || dnsDomainIs(host, ".mozilla.org")) { return "DIRECT"; } else { return "PROXY w3proxy.mozilla.org:8080; DIRECT"; } } ``` **Note:** This is the simplest and most efficient autoconfig file for cases where there's only one proxy. Example 2 --------- ### As above, but use proxy for local servers which are outside the firewall If there are hosts (such as the main Web server) that belong to the local domain but are outside the firewall and are only reachable through the proxy server, those exceptions can be handled using the `localHostOrDomainIs()` function: ``` function FindProxyForURL(url, host) { if ( (isPlainHostName(host) || dnsDomainIs(host, ".mozilla.org")) && !localHostOrDomainIs(host, "www.mozilla.org") && !localHostOrDomainIs(host, "merchant.mozilla.org") ) { return "DIRECT"; } else { return "PROXY w3proxy.mozilla.org:8080; DIRECT"; } } ``` The above example will use the proxy for everything except local hosts in the mozilla.org domain, with the further exception that hosts `www.mozilla.org` and `merchant.mozilla.org` will go through the proxy. **Note:** The order of the above exceptions for efficiency: `localHostOrDomainIs()` functions only get executed for URLs that are in local domain, not for every URL. Be careful to note the parentheses around the *or* expression before the *and* expression to achieve the above-mentioned efficient behavior. Example 3 --------- ### Use proxy only if cannot resolve host This example will work in an environment where the internal DNS server is set up so that it can only resolve internal host names, and the goal is to use a proxy only for hosts that aren't resolvable: ``` function FindProxyForURL(url, host) { if (isResolvable(host)) { return "DIRECT"; } return "PROXY proxy.mydomain.com:8080"; } ``` The above requires consulting the DNS every time; it can be grouped intelligently with other rules so that DNS is consulted only if other rules do not yield a result: ``` function FindProxyForURL(url, host) { if ( isPlainHostName(host) || dnsDomainIs(host, ".mydomain.com") || isResolvable(host) ) { return "DIRECT"; } return "PROXY proxy.mydomain.com:8080"; } ``` Example 4 --------- ### Subnet based decisions In this example all of the hosts in a given subnet are connected-to directly, others are connected through the proxy: ``` function FindProxyForURL(url, host) { if (isInNet(host, "198.95.0.0", "255.255.0.0")) { return "DIRECT"; } return "PROXY proxy.mydomain.com:8080"; } ``` Again, use of the DNS server in the above can be minimized by adding redundant rules in the beginning: ``` function FindProxyForURL(url, host) { if ( isPlainHostName(host) || dnsDomainIs(host, ".mydomain.com") || isInNet(host, "198.95.0.0", "255.255.0.0") ) { return "DIRECT"; } else { return "PROXY proxy.mydomain.com:8080"; } } ``` Example 5 --------- ### Load balancing/routing based on URL patterns This example is more sophisticated. There are four (4) proxy servers; one of them is a hot stand-by for all of the other ones, so if any of the remaining three goes down the fourth one will take over. Furthermore, the three remaining proxy servers share the load based on URL patterns, which makes their caching more effective (there is only one copy of any document on the three servers - as opposed to one copy on each of them). The load is distributed like this: | Proxy | Purpose | | --- | --- | | #1 | .com domain | | #2 | .edu domain | | #3 | all other domains | | #4 | hot stand-by | All local accesses are desired to be direct. All proxy servers run on the port 8080 (they don't need to, you can just change your port but remember to modify your configurations on both side). Note how strings can be concatenated with the `+` operator in JavaScript. ``` function FindProxyForURL(url, host) { if (isPlainHostName(host) || dnsDomainIs(host, ".mydomain.com")) { return "DIRECT"; } else if (shExpMatch(host, "\*.com")) { return "PROXY proxy1.mydomain.com:8080; PROXY proxy4.mydomain.com:8080"; } else if (shExpMatch(host, "\*.edu")) { return "PROXY proxy2.mydomain.com:8080; PROXY proxy4.mydomain.com:8080"; } else { return "PROXY proxy3.mydomain.com:8080; PROXY proxy4.mydomain.com:8080"; } } ``` Example 6 --------- ### Setting a proxy for a specific protocol Most of the standard JavaScript functionality is available for use in the `FindProxyForURL()` function. As an example, to set different proxies based on the protocol the [`startsWith()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith) function can be used: ``` function FindProxyForURL(url, host) { if (url.startsWith("http:")) { return "PROXY http-proxy.mydomain.com:8080"; } else if (url.startsWith("ftp:")) { return "PROXY ftp-proxy.mydomain.com:8080"; } else if (url.startsWith("gopher:")) { return "PROXY gopher-proxy.mydomain.com:8080"; } else if (url.startsWith("https:") || url.startsWith("snews:")) { return "PROXY security-proxy.mydomain.com:8080"; } return "DIRECT"; } ``` **Note:** The same can be accomplished using the [`shExpMatch()`](#shexpmatch) function described earlier. For example: ``` if (shExpMatch(url, "http:\*")) { return "PROXY http-proxy.mydomain.com:8080"; } ``` **Note:** The autoconfig file can be output by a CGI script. This is useful, for example, when making the autoconfig file act differently based on the client IP address (the `REMOTE_ADDR` environment variable in CGI). Usage of `isInNet()`, `isResolvable()` and `dnsResolve()` functions should be carefully considered, as they require the DNS server to be consulted. All the other autoconfig-related functions are mere string-matching functions that don't require the use of a DNS server. If a proxy is used, the proxy will perform its DNS lookup which would double the impact on the DNS server. Most of the time these functions are not necessary to achieve the desired result. History and implementation -------------------------- Proxy auto-config was introduced into Netscape Navigator 2.0 in the late 1990s, at the same time when JavaScript was introduced. Open-sourcing Netscape eventually lead to Firefox itself. The most "original" implementation of PAC and its JavaScript libraries is, therefore, `nsProxyAutoConfig.js` found in early versions of Firefox. These utilities are found in many other open-source systems including [Chromium](https://source.chromium.org/chromium/chromium/src/+/main:services/proxy_resolver/pac_js_library.h). Firefox later integrated the file into [`ProxyAutoConfig.cpp`](https://searchfox.org/mozilla-central/source/netwerk/base/ProxyAutoConfig.cpp) as a C++ string literal. To extract it into its own file, it suffices to copy the chunk into JavaScript with a `console.log` directive to print it. Microsoft in general made its own implementation. There used to be [some problems with their libraries](https://en.wikipedia.org/wiki/Proxy_auto-config#Old_Microsoft_problems), but most are resolved by now. They have defined [some new "Ex" suffixed functions](https://docs.microsoft.com/windows/win32/winhttp/ipv6-extensions-to-navigator-auto-config-file-format) around the address handling parts to support IPv6. The feature is supported by Chromium, but not yet by Firefox ([bugzilla #558253](https://bugzilla.mozilla.org/show_bug.cgi?id=558253)).
programming_docs
http Content negotiation: List of default Accept values Content negotiation: List of default Accept values ================================================== List of default Accept values ============================= This article documents the default values for the HTTP [`Accept`](../headers/accept) header for specific inputs and browser versions. Default values -------------- These are the values sent when the context doesn't give better information. Note that all browsers add the `*/*` MIME Type to cover all cases. This is typically used for requests initiated via the address bar of a browser, or via an HTML [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) element. | User Agent | Value | | --- | --- | | Firefox 92 and later [1] | `text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8` | | Firefox 72 to 91 [1] | `text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8` | | Firefox 66 to 71 [1] | `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` | | Firefox 65 [1] | `text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8` | | Firefox 64 and earlier [1] | `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` | | Safari, Chrome | `text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8` | | Safari 5 [2] | `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` | | Internet Explorer 8 [3] | `image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/msword, */*` | | Edge | `text/html, application/xhtml+xml, image/jxr, */*` | | Opera | `text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1` | [1] This value can be modified using the [`network.http.accept.default`](https://kb.mozillazine.org/Network.http.accept.default) parameter. [2] This is an improvement over earlier `Accept` headers as it no longer ranks `image/png` above `text/html`. [3] See [IE and the Accept Header (IEInternals' MSDN blog)](https://docs.microsoft.com/archive/blogs/ieinternals/ie-and-the-accept-header). Values for an image ------------------- When requesting an image, like through an HTML [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) element, user-agent often sets a specific list of media types to be welcomed. | User Agent | Value | | --- | --- | | Firefox 92 and later [1] | `image/avif,image/webp,*/*` | | Firefox 65 to 91 [1] | `image/webp,*/*` | | Firefox 47 to 63 [1] | `*/*` | | Firefox prior to 47 [1] | `image/png,image/*;q=0.8,*/*;q=0.5` | | Safari (since Mac OS Big Sur) | `image/webp,image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5` | | Safari (before Mac OS Big Sur) | `image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5` | | Chrome | `image/avif,image/webp,image/apng,image/*,*/*;q=0.8` | | Internet Explorer 9 | `image/png,image/svg+xml,image/*;q=0.8, */*;q=0.5` | | Internet Explorer 8 or earlier *[source](https://docs.microsoft.com/archive/blogs/ieinternals/ie-and-the-accept-header)* | `*/*` | [1] This value can be modified using the `image.http.accept` parameter (*[source](https://searchfox.org/mozilla-central/search?q=image.http.accept)*). Values for a video ------------------ When a video is requested, via the [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) HTML element, most browsers use specific values. | User Agent | Value | | --- | --- | | Firefox 3.6 and later | `video/webm,video/ogg,video/*;q=0.9,application/ogg;q=0.7,audio/*;q=0.6,*/*;q=0.5` | | Firefox earlier than 3.6 | *no support for [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video)* | | Chrome | `*/*` | | Internet Explorer 8 or earlier | *no support for [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video)* | Values for audio resources -------------------------- When an audio file is requested, like via the [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) HTML element, most browsers use specific values. | User Agent | Value | | --- | --- | | Firefox 3.6 and later [1] | `audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5` | | Safari, Chrome | `*/*` | | Internet Explorer 8 or earlier | *no support for [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio)* | | Internet Explorer 9 | ? | [1] See [bug 489071](https://bugzilla.mozilla.org/show_bug.cgi?id=489071). Values for scripts ------------------ When a script is requested, like via the [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) HTML element, some browsers use specific values. | User Agent | Value | | --- | --- | | Firefox [1] | `*/*` | | Safari, Chrome | `*/*` | | Internet Explorer 8 or earlier [2] | `*/*` | | Internet Explorer 9 | `application/javascript, */*;q=0.8` | [1] See [bug 170789](https://bugzilla.mozilla.org/show_bug.cgi?id=170789). [2] See [IE and the Accept Header (IEInternals' MSDN blog)](https://docs.microsoft.com/archive/blogs/ieinternals/ie-and-the-accept-header). Values for a CSS stylesheet --------------------------- When a CSS stylesheet is requested, via the `<link rel="stylesheet">` HTML element, most browsers use specific values. | User Agent | Value | | --- | --- | | Firefox 4 [1] | `text/css,*/*;q=0.1` | | Internet Explorer 8 or earlier [2] | `*/*` | | Internet Explorer 9 | `text/css` | | Safari, Chrome | `text/css,*/*;q=0.1` | | Opera 11.10 | `text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1` | | Konqueror 4.6 | `text/css,*/*;q=0.1` | [1] See [bug 170789](https://bugzilla.mozilla.org/show_bug.cgi?id=170789). [2] See [IE and the Accept Header (IEInternals' MSDN blog)](https://docs.microsoft.com/archive/blogs/ieinternals/ie-and-the-accept-header). http POST POST ==== POST ==== The `POST` sends data to the server. The type of the body of the request is indicated by the [`Content-Type`](../headers/content-type) header. The difference between [`PUT`](put) and `POST` is that `PUT` is idempotent: calling it once or several times successively has the same effect (that is no *side* effect), where successive identical `POST` may have additional effects, like passing an order several times. A `POST` request is typically sent via an [HTML form](https://developer.mozilla.org/en-US/docs/Learn/Forms) and results in a change on the server. In this case, the content type is selected by putting the adequate string in the [`enctype`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-enctype) attribute of the [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) element or the [`formenctype`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-formenctype) attribute of the [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) or [`<button>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button) elements: * `application/x-www-form-urlencoded`: the keys and values are encoded in key-value tuples separated by `'&'`, with a `'='` between the key and the value. Non-alphanumeric characters in both keys and values are [percent encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding): this is the reason why this type is not suitable to use with binary data (use `multipart/form-data` instead) * `multipart/form-data`: each value is sent as a block of data ("body part"), with a user agent-defined delimiter ("boundary") separating each part. The keys are given in the `Content-Disposition` header of each part. * `text/plain` When the `POST` request is sent via a method other than an HTML form — like via an [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) — the body can take any type. As described in the HTTP 1.1 specification, `POST` is designed to allow a uniform method to cover the following functions: * Annotation of existing resources * Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; * Adding a new user through a signup modal; * Providing a block of data, such as the result of submitting a form, to a data-handling process; * Extending a database through an append operation. | | | | --- | --- | | Request has body | Yes | | Successful response has body | Yes | | [Safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) | No | | [Idempotent](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent) | No | | [Cacheable](https://developer.mozilla.org/en-US/docs/Glossary/cacheable) | Only if freshness information is included | | Allowed in [HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) | Yes | Syntax ------ ``` POST /test ``` Example ------- A simple form using the default `application/x-www-form-urlencoded` content type: ``` POST /test HTTP/1.1 Host: foo.example Content-Type: application/x-www-form-urlencoded Content-Length: 27 field1=value1&field2=value2 ``` A form using the `multipart/form-data` content type: ``` POST /test HTTP/1.1 Host: foo.example Content-Type: multipart/form-data;boundary="boundary" --boundary Content-Disposition: form-data; name="field1" value1 --boundary Content-Disposition: form-data; name="field2"; filename="example.txt" value2 --boundary-- ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # POST](https://httpwg.org/specs/rfc9110.html#POST) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `POST` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Content-Type`](../headers/content-type) * [`Content-Disposition`](../headers/content-disposition) * [`GET`](get) http PATCH PATCH ===== PATCH ===== The `PATCH` applies partial modifications to a resource. `PATCH` is somewhat analogous to the "update" concept found in [CRUD](https://developer.mozilla.org/en-US/docs/Glossary/CRUD) (in general, HTTP is different than [CRUD](https://developer.mozilla.org/en-US/docs/Glossary/CRUD), and the two should not be confused). A `PATCH` request is considered a set of instructions on how to modify a resource. Contrast this with [`PUT`](put); which is a complete representation of a resource. A `PATCH` is not necessarily idempotent, although it can be. Contrast this with [`PUT`](put); which is always idempotent. The word "idempotent" means that any number of repeated, identical requests will leave the resource in the same state. For example if an auto-incrementing counter field is an integral part of the resource, then a [`PUT`](put) will naturally overwrite it (since it overwrites everything), but not necessarily so for `PATCH`. `PATCH` (like [`POST`](post)) *may* have side-effects on other resources. To find out whether a server supports `PATCH`, a server can advertise its support by adding it to the list in the [`Allow`](../headers/allow) or [`Access-Control-Allow-Methods`](../headers/access-control-allow-methods) (for [CORS](../cors)) response headers. Another (implicit) indication that `PATCH` is allowed, is the presence of the [`Accept-Patch`](../headers/accept-patch) header, which specifies the patch document formats accepted by the server. | | | | --- | --- | | Request has body | Yes | | Successful response has body | Yes | | [Safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) | No | | [Idempotent](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent) | No | | [Cacheable](https://developer.mozilla.org/en-US/docs/Glossary/cacheable) | No | | Allowed in [HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) | No | Syntax ------ ``` PATCH /file.txt HTTP/1.1 ``` Example ------- ### Request ``` PATCH /file.txt HTTP/1.1 Host: www.example.com Content-Type: application/example If-Match: "e0023aa4e" Content-Length: 100 [description of changes] ``` ### Response A successful response is indicated by any [2xx](https://httpwg.org/specs/rfc9110.html#status.2xx) status code. In the example below a [`204`](../status/204) response code is used, because the response does not carry a payload body. A [`200`](../status/200) response could have contained a payload body. ``` HTTP/1.1 204 No Content Content-Location: /file.txt ETag: "e0023aa4f" ``` Specifications -------------- | Specification | | --- | | [RFC 5789](https://www.rfc-editor.org/rfc/rfc5789) | See also -------- * [`204`](../status/204) * [`Allow`](../headers/allow), [`Access-Control-Allow-Methods`](../headers/access-control-allow-methods) * [`Accept-Patch`](../headers/accept-patch) – specifies the patch document formats accepted by the server. http HEAD HEAD ==== HEAD ==== The `HEAD` requests the [headers](../headers) that would be returned if the `HEAD` request's URL was instead requested with the HTTP [`GET`](get) method. For example, if a URL might produce a large download, a `HEAD` request could read its [`Content-Length`](../headers/content-length) header to check the filesize without actually downloading the file. **Warning:** A response to a `HEAD` method *should not* have a body. If it has one anyway, that body **must be** ignored: any [representation headers](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header) that might describe the erroneous body are instead assumed to describe the response which a similar `GET` request would have received. If the response to a `HEAD` request shows that a cached URL response is now outdated, the cached copy is invalidated even if no `GET` request was made. | | | | --- | --- | | Request has body | No | | Successful response has body | No | | [Safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) | Yes | | [Idempotent](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent) | Yes | | [Cacheable](https://developer.mozilla.org/en-US/docs/Glossary/cacheable) | Yes | | Allowed in [HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) | No | Syntax ------ ``` HEAD /index.html ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # HEAD](https://httpwg.org/specs/rfc9110.html#HEAD) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `HEAD` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`GET`](get) http OPTIONS OPTIONS ======= OPTIONS ======= The `OPTIONS` requests permitted communication options for a given URL or server. A client can specify a URL with this method, or an asterisk (`*`) to refer to the entire server. | | | | --- | --- | | Request has body | No | | Successful response has body | Yes | | [Safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) | Yes | | [Idempotent](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent) | Yes | | [Cacheable](https://developer.mozilla.org/en-US/docs/Glossary/cacheable) | No | | Allowed in HTML forms | No | Syntax ------ ``` OPTIONS /index.html HTTP/1.1 OPTIONS * HTTP/1.1 ``` Examples -------- ### Identifying allowed request methods To find out which request methods a server supports, one can use the `curl` command-line program to issue an `OPTIONS` request: ``` curl -X OPTIONS https://example.org -i ``` The response then contains an [`Allow`](../headers/allow) header that holds the allowed methods: ``` HTTP/1.1 204 No Content Allow: OPTIONS, GET, HEAD, POST Cache-Control: max-age=604800 Date: Thu, 13 Oct 2016 11:45:00 GMT Server: EOS (lax004/2813) ``` ### Preflighted requests in CORS In [CORS](../cors), a [preflight request](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request) is sent with the `OPTIONS` method so that the server can respond if it is acceptable to send the request. In this example, we will request permission for these parameters: * The [`Access-Control-Request-Method`](../headers/access-control-request-method) header sent in the preflight request tells the server that when the actual request is sent, it will have a [`POST`](post) request method. * The [`Access-Control-Request-Headers`](../headers/access-control-request-headers) header tells the server that when the actual request is sent, it will have the `X-PINGOTHER` and `Content-Type` headers. ``` OPTIONS /resources/post-here/ HTTP/1.1 Host: bar.example Accept: text/html,application/xhtml+xml,application/xml;q=0.9,\*/\*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Connection: keep-alive Origin: https://foo.example Access-Control-Request-Method: POST Access-Control-Request-Headers: X-PINGOTHER, Content-Type ``` The server now can respond if it will accept a request under these circumstances. In this example, the server response says that: [`Access-Control-Allow-Origin`](../headers/access-control-allow-origin) The `https://foo.example` origin is permitted to request the `bar.example/resources/post-here/` URL via the following: [`Access-Control-Allow-Methods`](../headers/access-control-allow-methods) [`POST`](post), [`GET`](get), and `OPTIONS` are permitted methods for the URL. (This header is similar to the [`Allow`](../headers/allow) response header, but used only for [CORS](../cors).) [`Access-Control-Allow-Headers`](../headers/access-control-allow-headers) Any script inspecting the response is permitted to read the values of the `X-PINGOTHER` and `Content-Type` headers. [`Access-Control-Max-Age`](../headers/access-control-max-age) The above permissions may be cached for 86,400 seconds (1 day). ``` HTTP/1.1 204 No Content Date: Mon, 01 Dec 2008 01:15:39 GMT Server: Apache/2.0.61 (Unix) Access-Control-Allow-Origin: https://foo.example Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Allow-Headers: X-PINGOTHER, Content-Type Access-Control-Max-Age: 86400 Vary: Accept-Encoding, Origin Keep-Alive: timeout=2, max=100 Connection: Keep-Alive ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # OPTIONS](https://httpwg.org/specs/rfc9110.html#OPTIONS) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `OPTIONS` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Allow`](../headers/allow) header * [CORS](../cors) http PUT PUT === PUT === The `PUT` creates a new resource or replaces a representation of the target resource with the request payload. The difference between `PUT` and [`POST`](post) is that `PUT` is idempotent: calling it once or several times successively has the same effect (that is no *side* effect), whereas successive identical [`POST`](post) requests may have additional effects, akin to placing an order several times. | | | | --- | --- | | Request has body | Yes | | Successful response has body | May | | [Safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) | No | | [Idempotent](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent) | Yes | | [Cacheable](https://developer.mozilla.org/en-US/docs/Glossary/cacheable) | No | | Allowed in [HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) | No | Syntax ------ ``` PUT /new.html HTTP/1.1 ``` Example ------- ### Request ``` PUT /new.html HTTP/1.1 Host: example.com Content-type: text/html Content-length: 16 <p>New File</p> ``` ### Responses If the target resource does not have a current representation and the `PUT` request successfully creates one, then the origin server must inform the user agent by sending a [`201`](../status/201) (`Created`) response. ``` HTTP/1.1 201 Created Content-Location: /new.html ``` If the target resource does have a current representation and that representation is successfully modified in accordance with the state of the enclosed representation, then the origin server must send either a [`200`](../status/200) (`OK`) or a [`204`](../status/204) (`No Content`) response to indicate successful completion of the request. ``` HTTP/1.1 204 No Content Content-Location: /existing.html ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # PUT](https://httpwg.org/specs/rfc9110.html#PUT) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `PUT` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`201`](../status/201) * [`204`](../status/204)
programming_docs
http DELETE DELETE ====== DELETE ====== The `DELETE` deletes the specified resource. | | | | --- | --- | | Request has body | May | | Successful response has body | May | | [Safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) | No | | [Idempotent](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent) | Yes | | [Cacheable](https://developer.mozilla.org/en-US/docs/Glossary/cacheable) | No | | Allowed in [HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) | No | Syntax ------ ``` DELETE /file.html HTTP/1.1 ``` Example ------- ### Request ``` DELETE /file.html HTTP/1.1 Host: example.com ``` ### Responses If a `DELETE` method is successfully applied, there are several response status codes possible: * A [`202`](../status/202) (`Accepted`) status code if the action will likely succeed but has not yet been enacted. * A [`204`](../status/204) (`No Content`) status code if the action has been enacted and no further information is to be supplied. * A [`200`](../status/200) (`OK`) status code if the action has been enacted and the response message includes a representation describing the status. ``` HTTP/1.1 200 OK Date: Wed, 21 Oct 2015 07:28:00 GMT <html> <body> <h1>File deleted.</h1> </body> </html> ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # DELETE](https://httpwg.org/specs/rfc9110.html#DELETE) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `DELETE` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * HTTP status: [`200`](../status/200), [`202`](../status/202), [`204`](../status/204) http CONNECT CONNECT ======= CONNECT ======= The `CONNECT` starts two-way communications with the requested resource. It can be used to open a tunnel. For example, the `CONNECT` method can be used to access websites that use [SSL](https://developer.mozilla.org/en-US/docs/Glossary/SSL) ([HTTPS](https://developer.mozilla.org/en-US/docs/Glossary/https)). The client asks an HTTP [Proxy server](https://developer.mozilla.org/en-US/docs/Glossary/Proxy_server) to tunnel the [TCP](https://developer.mozilla.org/en-US/docs/Glossary/TCP) connection to the desired destination. The server then proceeds to make the connection on behalf of the client. Once the connection has been established by the server, the [Proxy server](https://developer.mozilla.org/en-US/docs/Glossary/Proxy_server) continues to proxy the TCP stream to and from the client. `CONNECT` is a hop-by-hop method. | | | | --- | --- | | Request has body | No | | Successful response has body | Yes | | [Safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) | No | | [Idempotent](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent) | No | | [Cacheable](https://developer.mozilla.org/en-US/docs/Glossary/cacheable) | No | | Allowed in [HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) | No | Syntax ------ ``` CONNECT www.example.com:443 HTTP/1.1 ``` Example ------- Some proxy servers might need authority to create a tunnel. See also the [`Proxy-Authorization`](../headers/proxy-authorization) header. ``` CONNECT server.example.com:80 HTTP/1.1 Host: server.example.com:80 Proxy-Authorization: basic aGVsbG86d29ybGQ= ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # CONNECT](https://httpwg.org/specs/rfc9110.html#CONNECT) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `CONNECT` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [Proxy server](https://developer.mozilla.org/en-US/docs/Glossary/Proxy_server) * [`Proxy-Authorization`](../headers/proxy-authorization) http GET GET === GET === The `GET` requests a representation of the specified resource. Requests using `GET` should only be used to request data (they shouldn't include data). **Note:** Sending body/payload in a `GET` request may cause some existing implementations to reject the request — while not prohibited by the specification, the semantics are undefined. It is better to just avoid sending payloads in `GET` requests. | | | | --- | --- | | Request has body | No | | Successful response has body | Yes | | [Safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) | Yes | | [Idempotent](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent) | Yes | | [Cacheable](https://developer.mozilla.org/en-US/docs/Glossary/cacheable) | Yes | | Allowed in HTML forms | Yes | Syntax ------ ``` GET /index.html ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # GET](https://httpwg.org/specs/rfc9110.html#GET) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `GET` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [HTTP Headers](../headers) * [`Range`](../headers/range) * [`POST`](post) http TRACE TRACE ===== TRACE ===== The `TRACE` performs a message loop-back test along the path to the target resource, providing a useful debugging mechanism. The final recipient of the request should reflect the message received, excluding some fields described below, back to the client as the message body of a [`200`](../status/200) (`OK`) response with a [`Content-Type`](../headers/content-type) of `message/http`. The final recipient is either the origin server or the first server to receive a [`Max-Forwards`](../headers/max-forwards) value of 0 in the request. | | | | --- | --- | | Request has body | No | | Successful response has body | No | | [Safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) | Yes | | [Idempotent](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent) | Yes | | [Cacheable](https://developer.mozilla.org/en-US/docs/Glossary/cacheable) | No | | Allowed in HTML forms | No | Syntax ------ ``` TRACE /index.html ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # TRACE](https://httpwg.org/specs/rfc9110.html#TRACE) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `TRACE` | No | No | No | No | No | No | No | No | No | No | No | No | See also -------- * [HTTP methods](../methods) http 205 Reset Content 205 Reset Content ================= 205 Reset Content ================= The HTTP `205 Reset Content` response status tells the client to reset the document view, so for example to clear the content of a form, reset a canvas state, or to refresh the UI. Status ------ ``` 205 Reset Content ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.205](https://httpwg.org/specs/rfc9110.html#status.205) | Compatibility notes ------------------- * Browser behavior differs if this response erroneously includes a body on persistent connections See [204 No Content](204) for more detail. See also -------- * [`204`](204) No Content http 301 Moved Permanently 301 Moved Permanently ===================== 301 Moved Permanently ===================== The HyperText Transfer Protocol (HTTP) `301 Moved Permanently` redirect status response code indicates that the requested resource has been definitively moved to the URL given by the [`Location`](../headers/location) headers. A browser redirects to the new URL and search engines update their links to the resource. **Note:** Although the [specification](#specifications) requires the method and the body to remain unchanged when the redirection is performed, not all user-agents meet this requirement. Use the `301` code only as a response for [`GET`](../methods/get) or [`HEAD`](../methods/head) methods and use the [`308 Permanent Redirect`](308) for [`POST`](../methods/post) methods instead, as the method change is explicitly prohibited with this status. Status ------ ``` 301 Moved Permanently ``` Example ------- ### Client request ``` GET /index.php HTTP/1.1 Host: www.example.org ``` ### Server response ``` HTTP/1.1 301 Moved Permanently Location: http://www.example.org/index.asp ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.301](https://httpwg.org/specs/rfc9110.html#status.301) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `301` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`308 Permanent Redirect`](308), the equivalent of this status code where the method used never changes. * [`302 Found`](302), a temporary redirect http 511 Network Authentication Required 511 Network Authentication Required =================================== 511 Network Authentication Required =================================== The HTTP `511 Network Authentication Required` response status code indicates that the client needs to authenticate to gain network access. This status is not generated by origin servers, but by intercepting proxies that control access to the network. Network operators sometimes require some authentication, acceptance of terms, or other user interaction before granting access (for example in an internet café or at an airport). They often identify clients who have not done so using their Media Access Control (MAC) addresses. Status ------ ``` 511 Network Authentication Required ``` Specifications -------------- | Specification | | --- | | [RFC 6585 # section-6](https://www.rfc-editor.org/rfc/rfc6585#section-6) | See also -------- * [Proxy server](https://developer.mozilla.org/en-US/docs/Glossary/Proxy_server) http 403 Forbidden 403 Forbidden ============= 403 Forbidden ============= The HTTP `403 Forbidden` response status code indicates that the server understands the request but refuses to authorize it. This status is similar to [`401`](401), but for the `403 Forbidden` status code, re-authenticating makes no difference. The access is tied to the application logic, such as insufficient rights to a resource. Status ------ ``` 403 Forbidden ``` Example response ---------------- ``` HTTP/1.1 403 Forbidden Date: Wed, 21 Oct 2015 07:28:00 GMT ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.403](https://httpwg.org/specs/rfc9110.html#status.403) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `403` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`401`](401) * [HTTP/1.1: Status Code Definitions](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) http 415 Unsupported Media Type 415 Unsupported Media Type ========================== 415 Unsupported Media Type ========================== The HTTP `415 Unsupported Media Type` client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format. The format problem might be due to the request's indicated [`Content-Type`](../headers/content-type) or [`Content-Encoding`](../headers/content-encoding), or as a result of inspecting the data directly. Status ------ ``` 415 Unsupported Media Type ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.415](https://httpwg.org/specs/rfc9110.html#status.415) | See also -------- * [`Content-Type`](../headers/content-type) * [`Content-Encoding`](../headers/content-encoding) * [`Accept`](../headers/accept) http 100 Continue 100 Continue ============ 100 Continue ============ The HTTP `100 Continue` informational status response code indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished. To have a server check the request's headers, a client must send [`Expect`](../headers/expect)`: 100-continue` as a header in its initial request and receive a `100 Continue` status code in response before sending the body. Status ------ ``` 100 Continue ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.100](https://httpwg.org/specs/rfc9110.html#status.100) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `100` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Expect`](../headers/expect) * [`417`](417) http 507 Insufficient Storage 507 Insufficient Storage ======================== 507 Insufficient Storage ======================== The HyperText Transfer Protocol (HTTP) `507 Insufficient Storage` response status code may be given in the context of the Web Distributed Authoring and Versioning (WebDAV) protocol (see [RFC 4918](https://datatracker.ietf.org/doc/html/rfc4918)). It indicates that a method could not be performed because the server cannot store the representation needed to successfully complete the request. Status ------ ``` 507 Insufficient Storage ``` Specifications -------------- | Specification | | --- | | [RFC 4918 # section-11.5](https://www.rfc-editor.org/rfc/rfc4918#section-11.5) | http 418 I'm a teapot 418 I'm a teapot ================ 418 I'm a teapot ================ The HTTP `418 I'm a teapot` client error response code indicates that the server refuses to brew coffee because it is, permanently, a teapot. A combined coffee/tea pot that is temporarily out of coffee should instead return 503. This error is a reference to Hyper Text Coffee Pot Control Protocol defined in April Fools' jokes in 1998 and 2014. Some websites use this response for requests they do not wish to handle, such as automated queries. Status ------ ``` 418 I'm a teapot ``` Specifications -------------- | Specification | | --- | | [RFC 2324 # section-2.3.2](https://www.rfc-editor.org/rfc/rfc2324#section-2.3.2) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `418` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [Wikipedia: Hyper Text Coffee Pot Control Protocol](https://en.wikipedia.org/wiki/Hyper_Text_Coffee_Pot_Control_Protocol) http 422 Unprocessable Entity 422 Unprocessable Entity ======================== 422 Unprocessable Entity ======================== The HyperText Transfer Protocol (HTTP) `422 Unprocessable Entity` response status code indicates that the server understands the content type of the request entity, and the syntax of the request entity is correct, but it was unable to process the contained instructions. **Warning:** The client should not repeat this request without modification. Status ------ ``` 422 Unprocessable Entity ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.422](https://httpwg.org/specs/rfc9110.html#status.422) | http 506 Variant Also Negotiates 506 Variant Also Negotiates =========================== 506 Variant Also Negotiates =========================== The HyperText Transfer Protocol (HTTP) `506 Variant Also Negotiates` response status code may be given in the context of Transparent Content Negotiation (see [RFC 2295](https://datatracker.ietf.org/doc/html/rfc2295)). This protocol enables a client to retrieve the best variant of a given resource, where the server supports multiple variants. The `Variant Also Negotiates` status code indicates an internal server configuration error in which the chosen variant is itself configured to engage in content negotiation, so is not a proper negotiation endpoint. Status ------ ``` 506 Variant Also Negotiates ``` Specifications -------------- | Specification | | --- | | [RFC 2295 # section-8.1](https://www.rfc-editor.org/rfc/rfc2295#section-8.1) | http 414 URI Too Long 414 URI Too Long ================ 414 URI Too Long ================ The HTTP `414 URI Too Long` response status code indicates that the URI requested by the client is longer than the server is willing to interpret. There are a few rare conditions when this might occur: * when a client has improperly converted a [`POST`](../methods/post) request to a [`GET`](../methods/get) request with long query information, * when the client has descended into a loop of redirection (for example, a redirected URI prefix that points to a suffix of itself), * or when the server is under attack by a client attempting to exploit potential security holes. Status ------ ``` 414 URI Too Long ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.414](https://httpwg.org/specs/rfc9110.html#status.414) | See also -------- * [URI](https://developer.mozilla.org/en-US/docs/Glossary/URI) http 101 Switching Protocols 101 Switching Protocols ======================= 101 Switching Protocols ======================= The HTTP `101 Switching Protocols` response code indicates a protocol to which the server switches. The protocol is specified in the [`Upgrade`](../headers/upgrade) request header received from a client. The server includes in this response an [`Upgrade`](../headers/upgrade) response header to indicate the protocol it switched to. The process is described in the following article: [Protocol upgrade mechanism](../protocol_upgrade_mechanism). Status ------ ``` 101 Switching Protocols ``` Examples -------- Switching protocols might be used with [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API). ``` HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.101](https://httpwg.org/specs/rfc9110.html#status.101) | See also -------- * [Protocol upgrade mechanism](../protocol_upgrade_mechanism) * [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) * [`Upgrade`](../headers/upgrade) * [`426`](426) `Upgrade Required` http 402 Payment Required 402 Payment Required ==================== 402 Payment Required ==================== **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. The HTTP `402 Payment Required` is a nonstandard response status code that is reserved for future use. This status code was created to enable digital cash or (micro) payment systems and would indicate that the requested content is not available until the client makes a payment. Sometimes, this status code indicates that the request cannot be processed until the client makes a payment. However, no standard use convention exists and different entities use it in different contexts. Status ------ ``` 402 Payment Required ``` Example response ---------------- ``` HTTP/1.1 402 Payment Required Date: Wed, 21 Oct 2015 07:28:00 GMT ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.402](https://httpwg.org/specs/rfc9110.html#status.402) | Browser compatibility --------------------- See also -------- * [HTTP authentication](../authentication)
programming_docs
http 510 Not Extended 510 Not Extended ================ 510 Not Extended ================ The HyperText Transfer Protocol (HTTP) `510 Not Extended` response status code is sent in the context of the HTTP Extension Framework, defined in [RFC 2774](https://datatracker.ietf.org/doc/html/rfc2774). In that specification a client may send a request that contains an extension declaration, that describes the extension to be used. If the server receives such a request, but any described extensions are not supported for the request, then the server responds with the 510 status code. Status ------ ``` 510 Not Extended ``` Specifications -------------- | Specification | | --- | | [RFC 2774 # section-7](https://www.rfc-editor.org/rfc/rfc2774#section-7) | http 300 Multiple Choices 300 Multiple Choices ==================== 300 Multiple Choices ==================== The HTTP `300 Multiple Choices` redirect status response code indicates that the request has more than one possible responses. The user-agent or the user should choose one of them. As there is no standardized way of choosing one of the responses, this response code is very rarely used. If the server has a preferred choice, it should generate a [`Location`](../headers/location) header. Status ------ ``` 300 Multiple Choices ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.300](https://httpwg.org/specs/rfc9110.html#status.300) | See also -------- * [`301`](301) `Moved Permanently` * [`302`](302) `Found`, the temporary redirect * [`308`](308) `Permanent Redirect` http 204 No Content 204 No Content ============== 204 No Content ============== The HTTP `204 No Content` success status response code indicates that a request has succeeded, but that the client doesn't need to navigate away from its current page. This might be used, for example, when implementing "save and continue editing" functionality for a wiki site. In this case a [`PUT`](../methods/put) request would be used to save the page, and the `204 No Content` response would be sent to indicate that the editor should not be replaced by some other page. A 204 response is cacheable by default (an [`ETag`](../headers/etag) header is included in such a response). Status ------ ``` 204 No Content ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.204](https://httpwg.org/specs/rfc9110.html#status.204) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `204` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | ### Compatibility notes * Although this status code is intended to describe a response with no body, servers may erroneously include data following the headers. The protocol allows user agents to vary in how they process such responses ([discussion regarding this specification text can be found here](https://github.com/httpwg/http-core/issues/26)). This is observable in persistent connections, where the invalid body may include a distinct response to a subsequent request. Apple Safari rejects any such data. Google Chrome and Microsoft Edge discard up to four invalid bytes preceding a valid response. Firefox tolerates in excess of a kilobyte of invalid data preceding a valid response. See also -------- * [HTTP request methods](../methods) http 425 Too Early 425 Too Early ============= 425 Too Early ============= The HyperText Transfer Protocol (HTTP) `425 Too Early` response status code indicates that the server is unwilling to risk processing a request that might be replayed, which creates the potential for a replay attack. Status ------ ``` 425 Too Early ``` Specifications -------------- | Specification | | --- | | [Using Early Data in HTTP # status](https://httpwg.org/specs/rfc8470.html#status) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `425` | No | No | 58 | No | No | No | No | No | 58 | No | No | No | http 409 Conflict 409 Conflict ============ 409 Conflict ============ The HTTP `409 Conflict` response status code indicates a request conflict with the current state of the target resource. Conflicts are most likely to occur in response to a [`PUT`](../methods/put) request. For example, you may get a 409 response when uploading a file that is older than the existing one on the server, resulting in a version control conflict. Status ------ ``` 409 Conflict ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.409](https://httpwg.org/specs/rfc9110.html#status.409) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `409` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`PUT`](../methods/put) http 203 Non-Authoritative Information 203 Non-Authoritative Information ================================= 203 Non-Authoritative Information ================================= The HTTP `203 Non-Authoritative Information` response status indicates that the request was successful but the enclosed payload has been modified by a transforming [proxy](https://developer.mozilla.org/en-US/docs/Glossary/Proxy_server) from that of the origin server's [`200`](200) (`OK`) response . The `203` response is similar to the value [`214`](../headers/warning#warning_codes), meaning `Transformation Applied`, of the [`Warning`](../headers/warning) header code, which has the additional advantage of being applicable to responses with any status code. Status ------ ``` 203 Non-Authoritative Information ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.203](https://httpwg.org/specs/rfc9110.html#status.203) | See also -------- * [`200`](200) * [Proxy server](https://developer.mozilla.org/en-US/docs/Glossary/Proxy_server) * [`Warning`](../headers/warning) http 307 Temporary Redirect 307 Temporary Redirect ====================== 307 Temporary Redirect ====================== [HTTP](https://developer.mozilla.org/en-US/docs/Glossary/HTTP) `307 Temporary Redirect` redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the [`Location`](../headers/location) headers. The method and the body of the original request are reused to perform the redirected request. In the cases where you want the method used to be changed to [`GET`](../methods/get), use [`303 See Other`](303) instead. This is useful when you want to give an answer to a [`PUT`](../methods/put) method that is not the uploaded resources, but a confirmation message (like "You successfully uploaded XYZ"). The only difference between `307` and [`302`](302) is that `307` guarantees that the method and the body will not be changed when the redirected request is made. With `302`, some old clients were incorrectly changing the method to [`GET`](../methods/get): the behavior with non-`GET` methods and `302` is then unpredictable on the Web, whereas the behavior with `307` is predictable. For `GET` requests, their behavior is identical. Status ------ ``` 307 Temporary Redirect ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.307](https://httpwg.org/specs/rfc9110.html#status.307) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `307` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`302 Found`](302), the equivalent of this status code, but that may change the method used when it is not a [`GET`](../methods/get). * [`303 See Other`](303), a temporary redirect that changes the method used to [`GET`](../methods/get). * [`301 Moved Permanently`](301), a permanent redirect http 429 Too Many Requests 429 Too Many Requests ===================== 429 Too Many Requests ===================== The HTTP `429 Too Many Requests` response status code indicates the user has sent too many requests in a given amount of time ("rate limiting"). A [`Retry-After`](../headers/retry-after) header might be included to this response indicating how long to wait before making a new request. Status ------ ``` 429 Too Many Requests ``` Example ------- ``` HTTP/1.1 429 Too Many Requests Content-Type: text/html Retry-After: 3600 ``` Specifications -------------- | Specification | | --- | | [RFC 6585 # section-4](https://www.rfc-editor.org/rfc/rfc6585#section-4) | See also -------- * [`Retry-After`](../headers/retry-after) * [HTTP/1.1: Status Code Definitions](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) * Python solution: [How to avoid HTTP error 429 python](https://stackoverflow.com/questions/22786068/how-to-avoid-http-error-429-too-many-requests-python) http 405 Method Not Allowed 405 Method Not Allowed ====================== 405 Method Not Allowed ====================== The HyperText Transfer Protocol (HTTP) `405 Method Not Allowed` response status code indicates that the server knows the request method, but the target resource doesn't support this method. The server **must** generate an `Allow` header field in a 405 status code response. The field must contain a list of methods that the target resource currently supports. Status ------ ``` 405 Method Not Allowed ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.405](https://httpwg.org/specs/rfc9110.html#status.405) | See also -------- * [`Allow`](../headers/allow) * [HTTP/1.1: Status Code Definitions](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) * [How to Fix 405 Method Not Allowed](https://kinsta.com/blog/405-method-not-allowed-error/) * [Troubleshooting HTTP 405](https://docs.microsoft.com/aspnet/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications) http 413 Payload Too Large 413 Payload Too Large ===================== 413 Payload Too Large ===================== The HTTP `413 Payload Too Large` response status code indicates that the request entity is larger than limits defined by server; the server might close the connection or return a [`Retry-After`](../headers/retry-after) header field. Status ------ ``` 413 Payload Too Large ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.413](https://httpwg.org/specs/rfc9110.html#status.413) | See also -------- * [`Connection`](../headers/connection) * [`Retry-After`](../headers/retry-after) http 501 Not Implemented 501 Not Implemented =================== 501 Not Implemented =================== The HyperText Transfer Protocol (HTTP) `501 Not Implemented` server error response code means that **the server does not support the functionality required to fulfill the request**. This status can also send a [`Retry-After`](../headers/retry-after) header, telling the requester when to check back to see if the functionality is supported by then. `501` is the appropriate response when the server does not recognize the request method and is incapable of supporting it for any resource. The only methods that servers are required to support (and therefore that must not return `501`) are [`GET`](../methods/get) and [`HEAD`](../methods/head). If the server *does* recognize the method, but intentionally does not support it, the appropriate response is [`405 Method Not Allowed`](405). **Note:** * A 501 error is not something you can fix, but requires a fix by the web server you are trying to access. * A 501 response is cacheable by default; that is, unless caching headers instruct otherwise. Status ------ ``` 501 Not Implemented ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.501](https://httpwg.org/specs/rfc9110.html#status.501) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `501` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | http 500 Internal Server Error 500 Internal Server Error ========================= 500 Internal Server Error ========================= The HyperText Transfer Protocol (HTTP) `500 Internal Server Error` server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. This error response is a generic "catch-all" response. Usually, this indicates the server cannot find a better 5xx error code to response. Sometimes, server administrators log error responses like the 500 status code with more details about the request to prevent the error from happening again in the future. Status ------ ``` 500 Internal Server Error ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.500](https://httpwg.org/specs/rfc9110.html#status.500) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `500` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [HTTP/1.1: Status Code Definitions](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) http 412 Precondition Failed 412 Precondition Failed ======================= 412 Precondition Failed ======================= The HyperText Transfer Protocol (HTTP) `412 Precondition Failed` client error response code indicates that access to the target resource has been denied. This happens with conditional requests on methods other than [`GET`](../methods/get) or [`HEAD`](../methods/head) when the condition defined by the [`If-Unmodified-Since`](../headers/if-unmodified-since) or [`If-None-Match`](../headers/if-none-match) headers is not fulfilled. In that case, the request, usually an upload or a modification of a resource, cannot be made and this error response is sent back. Status ------ ``` 412 Precondition Failed ``` Examples -------- ``` ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4" ETag: W/"0815" ``` ### Avoiding mid-air collisions With the help of the `ETag` and the [`If-Match`](../headers/if-match) headers, you can detect mid-air edit collisions. For example, when editing MDN, the current wiki content is hashed and put into an `Etag` in the response: ``` ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4" ``` When saving changes to a wiki page (posting data), the [`POST`](../methods/post) request will contain the [`If-Match`](../headers/if-match) header containing the `ETag` values to check freshness against. ``` If-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4" ``` If the hashes don't match, it means that the document has been edited in-between and a [`412`](412) `Precondition Failed` error is thrown. Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.412](https://httpwg.org/specs/rfc9110.html#status.412) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `412` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | The information below has been pulled from MDN's GitHub (<https://github.com/mdn/browser-compat-data>). See also -------- * [`304`](304) * [`If-Unmodified-Since`](../headers/if-unmodified-since) * [`If-None-Match`](../headers/if-none-match) * [`428`](428) http 404 Not Found 404 Not Found ============= 404 Not Found ============= The HTTP `404 Not Found` response status code indicates that the server cannot find the requested resource. Links that lead to a 404 page are often called broken or dead links and can be subject to [link rot](https://en.wikipedia.org/wiki/Link_rot). A 404 status code only indicates that the resource is missing: not whether the absence is temporary or permanent. If a resource is permanently removed, use the [`410`](410) (Gone) status instead. Status ------ ``` 404 Not Found ``` Custom error pages ------------------ You can display a custom 404 page to be more helpful to a user and provide guidance on what to do next. For example, for the Apache server, you can specify a path to a custom 404 page in an `.htaccess` file: ``` ErrorDocument 404 /notfound.html ``` For an example of a custom 404 page, see this [404 page](https://konmari.com/404). **Note:** Custom design is a good thing, in moderation. Feel free to make your 404 page humorous and human, but don't confuse your users. Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.404](https://httpwg.org/specs/rfc9110.html#status.404) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `404` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`410`](410) * [Wikipedia: HTTP 404](https://en.wikipedia.org/wiki/HTTP_404) http 428 Precondition Required 428 Precondition Required ========================= 428 Precondition Required ========================= The HTTP `428 Precondition Required` response status code indicates that the server requires the request to be [conditional](../conditional_requests). Typically, this means that a required precondition header, such as [`If-Match`](../headers/if-match), **is missing**. When a precondition header is **not matching** the server side state, the response should be [`412`](412) `Precondition Failed`. Status ------ ``` 428 Precondition Required ``` Specifications -------------- | Specification | | --- | | [RFC 6585 # section-3](https://www.rfc-editor.org/rfc/rfc6585#section-3) | See also -------- * [HTTP conditional requests](../conditional_requests) * [`If-Match`](../headers/if-match) * [`412`](412) http 202 Accepted 202 Accepted ============ 202 Accepted ============ The HyperText Transfer Protocol (HTTP) `202 Accepted` response status code indicates that the request has been accepted for processing, but the processing has not been completed; in fact, processing may not have started yet. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. 202 is non-committal, meaning that there is no way for the HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing. Status ------ ``` 202 Accepted ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.202](https://httpwg.org/specs/rfc9110.html#status.202) | See also -------- * [`Accept`](../headers/accept)
programming_docs
http 408 Request Timeout 408 Request Timeout =================== 408 Request Timeout =================== The HyperText Transfer Protocol (HTTP) `408 Request Timeout` response status code means that the server would like to shut down this unused connection. It is sent on an idle connection by some servers, *even without any previous request by the client*. A server should send the "close" [`Connection`](../headers/connection) header field in the response, since `408` implies that the server has decided to close the connection rather than continue waiting. This response is used much more since some browsers, like Chrome, Firefox 27+, and IE9, use HTTP pre-connection mechanisms to speed up surfing. **Note:** some servers merely shut down the connection without sending this message. Status ------ ``` 408 Request Timeout ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.408](https://httpwg.org/specs/rfc9110.html#status.408) | See also -------- * [`Connection`](../headers/connection) * [`X-DNS-Prefetch-Control`](../headers/x-dns-prefetch-control) http 431 Request Header Fields Too Large 431 Request Header Fields Too Large =================================== 431 Request Header Fields Too Large =================================== The HTTP `431 Request Header Fields Too Large` response status code indicates that the server refuses to process the request because the request's [HTTP headers](../headers) are too long. The request *may* be resubmitted after reducing the size of the request headers. 431 can be used when the **total size** of request headers is too large, or when a **single** header field is too large. To help those running into this error, indicate which of the two is the problem in the response body — ideally, also include which headers are too large. This lets users attempt to fix the problem, such as by clearing their cookies. Servers will often produce this status if: * The [`Referer`](../headers/referer) URL is too long * There are too many [Cookies](../cookies) sent in the request Status ------ ``` 431 Request Header Fields Too Large ``` Specifications -------------- | Specification | | --- | | [RFC 6585 # section-5](https://www.rfc-editor.org/rfc/rfc6585#section-5) | See also -------- * [`414 URI Too Long`](414) * [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) http 503 Service Unavailable 503 Service Unavailable ======================= 503 Service Unavailable ======================= The HyperText Transfer Protocol (HTTP) `503 Service Unavailable` server error response code indicates that the server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. This response should be used for temporary conditions and the [`Retry-After`](../headers/retry-after) HTTP header should, if possible, contain the estimated time for the recovery of the service. **Note:** together with this response, a user-friendly page explaining the problem should be sent. Caching-related headers that are sent along with this response should be taken care of, as a 503 status is often a temporary condition and responses shouldn't usually be cached. Status ------ ``` 503 Service Unavailable ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.503](https://httpwg.org/specs/rfc9110.html#status.503) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `503` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Retry-After`](../headers/retry-after) * [HTTP/1.1: Status Code Definitions](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) http 411 Length Required 411 Length Required =================== 411 Length Required =================== The HyperText Transfer Protocol (HTTP) `411 Length Required` client error response code indicates that the server refuses to accept the request without a defined [`Content-Length`](../headers/content-length) header. **Note:** by specification, when sending data in a series of chunks, the `Content-Length` header is omitted and at the beginning of each chunk you need to add the length of the current chunk in hexadecimal format. See [`Transfer-Encoding`](../headers/transfer-encoding) for more details. Status ------ ``` 411 Length Required ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.411](https://httpwg.org/specs/rfc9110.html#status.411) | See also -------- * [`Content-Length`](../headers/content-length) * [`Transfer-Encoding`](../headers/transfer-encoding) http 407 Proxy Authentication Required 407 Proxy Authentication Required ================================= 407 Proxy Authentication Required ================================= The HTTP `407 Proxy Authentication Required` client error status response code indicates that the request has not been applied because it lacks valid authentication credentials for a [proxy server](https://developer.mozilla.org/en-US/docs/Glossary/Proxy_server) that is between the browser and the server that can access the requested resource. This status is sent with a [`Proxy-Authenticate`](../headers/proxy-authenticate) header that contains information on how to authorize correctly. Status ------ ``` 407 Proxy Authentication Required ``` Example response ---------------- ``` HTTP/1.1 407 Proxy Authentication Required Date: Wed, 21 Oct 2015 07:28:00 GMT Proxy-Authenticate: Basic realm="Access to internal site" ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.407](https://httpwg.org/specs/rfc9110.html#status.407) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `407` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [HTTP authentication](../authentication) * [`WWW-Authenticate`](../headers/www-authenticate) * [`Authorization`](../headers/authorization) * [`Proxy-Authorization`](../headers/proxy-authorization) * [`Proxy-Authenticate`](../headers/proxy-authenticate) * [`401`](401), [`403`](403) http 201 Created 201 Created =========== 201 Created =========== The HTTP `201 Created` success status response code indicates that the request has succeeded and has led to the creation of a resource. The new resource, or a description and link to the new resource, is effectively created before the response is sent back and the newly created items are returned in the body of the message, located at either the URL of the request, or at the URL in the value of the [`Location`](../headers/location) header. The common use case of this status code is as the result of a [`POST`](../methods/post) request. Status ------ ``` 201 Created ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.201](https://httpwg.org/specs/rfc9110.html#status.201) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `201` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [HTTP request methods](../methods) http 200 OK 200 OK ====== 200 OK ====== The HTTP `200 OK` success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: * [`GET`](../methods/get): The resource has been fetched and is transmitted in the message body. * [`HEAD`](../methods/head): The representation headers are included in the response without any message body * [`POST`](../methods/post): The resource describing the result of the action is transmitted in the message body * [`TRACE`](../methods/trace): The message body contains the request message as received by the server. The successful result of a [`PUT`](../methods/put) or a [`DELETE`](../methods/delete) is often not a `200` `OK` but a [`204`](204) `No Content` (or a [`201`](201) `Created` when the resource is uploaded for the first time). Status ------ ``` 200 OK ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.200](https://httpwg.org/specs/rfc9110.html#status.200) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `200` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [HTTP request methods](../methods) http 304 Not Modified 304 Not Modified ================ 304 Not Modified ================ The HTTP `304 Not Modified` client redirection response code indicates that there is no need to retransmit the requested resources. It is an implicit redirection to a cached resource. This happens when the request method is a [safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) method, such as [`GET`](../methods/get) or [`HEAD`](../methods/head), or when the request is conditional and uses an [`If-None-Match`](../headers/if-none-match) or an [`If-Modified-Since`](../headers/if-modified-since) header. The equivalent [`200`](200) `OK` response would have included the headers [`Cache-Control`](../headers/cache-control), [`Content-Location`](../headers/content-location), [`Date`](../headers/date), [`ETag`](../headers/etag), [`Expires`](../headers/expires), and [`Vary`](../headers/vary). **Note:** Many [developer tools' network panels](https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/index.html) of browsers create extraneous requests leading to `304` responses, so that access to the local cache is visible to developers. Status ------ ``` 304 Not Modified ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.304](https://httpwg.org/specs/rfc9110.html#status.304) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `304` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | ### Compatibility notes * Browser behavior differs if this response erroneously includes a body on persistent connections See [204 No Content](204) for more detail. See also -------- * [`If-Modified-Since`](../headers/if-modified-since) * [`If-None-Match`](../headers/if-none-match) http 451 Unavailable For Legal Reasons 451 Unavailable For Legal Reasons ================================= 451 Unavailable For Legal Reasons ================================= The HyperText Transfer Protocol (HTTP) `451 Unavailable For Legal Reasons` client error response code indicates that the user requested a resource that is not available due to legal reasons, such as a web page for which a legal action has been issued. Status ------ ``` 451 Unavailable For Legal Reasons ``` Example ------- This example response is taken from the IETF RFC (see below) and contains a reference to [Monty Python's Life of Brian](https://en.wikipedia.org/wiki/Monty_Python's_Life_of_Brian). **Note:** the [`Link`](../headers/link) header might also contain a `rel="blocked-by"` relation identifying the entity and implementing blockage, not any other entity mandating it. Any attempt to identify the entity ultimately responsible for the resource being unavailable belongs in the response body, not in the `rel="blocked-by"` link. This includes the name of the person or organization that made a legal demand resulting in the content's removal. ``` HTTP/1.1 451 Unavailable For Legal Reasons Link: <https://spqr.example.org/legislatione>; rel="blocked-by" Content-Type: text/html <html> <head><title>Unavailable For Legal Reasons</title></head> <body> <h1>Unavailable For Legal Reasons</h1> <p>This request may not be serviced in the Roman Province of Judea due to the Lex Julia Majestatis, which disallows access to resources hosted on servers deemed to be operated by the People's Front of Judea.</p> </body> </html> ``` Specifications -------------- | Specification | | --- | | [An HTTP Status Code to Report Legal Obstacles # n-451-unavailable-for-legal-reasons](https://httpwg.org/specs/rfc7725.html#n-451-unavailable-for-legal-reasons) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `451` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [Wikipedia: HTTP 451](https://en.wikipedia.org/wiki/HTTP_451) * [Wikipedia: Fahrenheit 451](https://en.wikipedia.org/wiki/Fahrenheit_451) (which gave this status code its number) http 406 Not Acceptable 406 Not Acceptable ================== 406 Not Acceptable ================== The HyperText Transfer Protocol (HTTP) `406 Not Acceptable` client error response code indicates that the server cannot produce a response matching the list of acceptable values defined in the request's proactive [content negotiation](../content_negotiation) headers, and that the server is unwilling to supply a default representation. Proactive content negotiation headers include: * [`Accept`](../headers/accept) * [`Accept-Encoding`](../headers/accept-encoding) * [`Accept-Language`](../headers/accept-language) In practice, this error is very rarely used. Instead of responding using this error code, which would be cryptic for the end user and difficult to fix, servers ignore the relevant header and serve an actual page to the user. It is assumed that even if the user won't be completely happy, they will prefer this to an error code. If a server returns such an error status, the body of the message should contain the list of the available representations of the resources, allowing the user to choose among them. Status ------ ``` 406 Not Acceptable ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.406](https://httpwg.org/specs/rfc9110.html#status.406) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `406` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Accept`](../headers/accept) * [`Accept-Encoding`](../headers/accept-encoding) * [`Accept-Language`](../headers/accept-language) * HTTP [content negotiation](../content_negotiation) http 410 Gone 410 Gone ======== 410 Gone ======== The HyperText Transfer Protocol (HTTP) `410 Gone` client error response code indicates that access to the target resource is no longer available at the origin server and that this condition is likely to be permanent. If you don't know whether this condition is temporary or permanent, a [`404`](404) status code should be used instead. **Note:** A 410 response is cacheable by default. Status ------ ``` 410 Gone ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.410](https://httpwg.org/specs/rfc9110.html#status.410) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `410` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`404`](404) * [410 gone](https://www.exai.com/blog/410-gone-client-error) http 502 Bad Gateway 502 Bad Gateway =============== 502 Bad Gateway =============== The HyperText Transfer Protocol (HTTP) `502 Bad Gateway` server error response code indicates that the server, while acting as a gateway or proxy, received an invalid response from the upstream server. **Note:** A [Gateway](https://en.wikipedia.org/wiki/Gateway_(telecommunications)) might refer to different things in networking and a 502 error is usually not something you can fix, but requires a fix by the web server or the proxies you are trying to get access through. Status ------ ``` 502 Bad Gateway ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.502](https://httpwg.org/specs/rfc9110.html#status.502) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `502` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`504`](504) * [HTTP/1.1: Status Code Definitions](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) http 308 Permanent Redirect 308 Permanent Redirect ====================== 308 Permanent Redirect ====================== The HyperText Transfer Protocol (HTTP) `308 Permanent Redirect` redirect status response code indicates that the resource requested has been definitively moved to the URL given by the [`Location`](../headers/location) headers. A browser redirects to this page and search engines update their links to the resource (in 'SEO-speak', it is said that the 'link-juice' is sent to the new URL). The request method and the body will not be altered, whereas [`301`](301) may incorrectly sometimes be changed to a [`GET`](../methods/get) method. **Note:** Some Web applications may use the `308 Permanent Redirect` in a non-standard way and for other purposes. For example, Google Drive uses a `308 Resume Incomplete` response to indicate to the client when an incomplete upload stalled. (See [Perform a resumable download](https://developers.google.com/drive/api/guides/manage-uploads) on Google Drive documentation.) Status ------ ``` 308 Permanent Redirect ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.308](https://httpwg.org/specs/rfc9110.html#status.308) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `308` | 36 | 12 | 14 | 11 Does not work below Windows 10. | 24 | 7 | 37 | 36 | 14 | 24 | 7 | 3.0 | See also -------- * [`301 Moved Permanently`](301), the equivalent of this status code, but that may change the method used when it is not a [`GET`](../methods/get). * [`302 Found`](302), a temporary redirect http 426 Upgrade Required 426 Upgrade Required ==================== 426 Upgrade Required ==================== The HTTP `426 Upgrade Required` client error response code indicates that the server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server sends an [`Upgrade`](../headers/upgrade) header with this response to indicate the required protocol(s). Status ------ ``` 426 Upgrade Required ``` Examples -------- ``` HTTP/1.1 426 Upgrade Required Upgrade: HTTP/2.0 Connection: Upgrade Content-Length: 53 Content-Type: text/plain This service requires use of the HTTP/2.0 protocol ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.426](https://httpwg.org/specs/rfc9110.html#status.426) | See also -------- * [`Upgrade`](../headers/upgrade) * [`101`](101) `Switching Protocols`
programming_docs
http 505 HTTP Version Not Supported 505 HTTP Version Not Supported ============================== 505 HTTP Version Not Supported ============================== The HyperText Transfer Protocol (HTTP) `505 HTTP Version Not Supported` response status code indicates that the HTTP version used in the request is not supported by the server. Status ------ ``` 505 HTTP Version Not Supported ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.505](https://httpwg.org/specs/rfc9110.html#status.505) | See also -------- * [`Upgrade`](../headers/upgrade) http 417 Expectation Failed 417 Expectation Failed ====================== 417 Expectation Failed ====================== The HTTP `417 Expectation Failed` client error response code indicates that the expectation given in the request's [`Expect`](../headers/expect) header could not be met. See the [`Expect`](../headers/expect) header for more details. Status ------ ``` 417 Expectation Failed ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.417](https://httpwg.org/specs/rfc9110.html#status.417) | See also -------- * [`Expect`](../headers/expect) http 401 Unauthorized 401 Unauthorized ================ 401 Unauthorized ================ The HyperText Transfer Protocol (HTTP) `401 Unauthorized` response status code indicates that the client request has not been completed because it lacks valid authentication credentials for the requested resource. This status code is sent with an HTTP [`WWW-Authenticate`](../headers/www-authenticate) response header that contains information on how the client can request for the resource again after prompting the user for authentication credentials. This status code is similar to the [`403 Forbidden`](403) status code, except that in situations resulting in this status code, user authentication can allow access to the resource. Status ------ ``` 401 Unauthorized ``` Example response ---------------- ``` HTTP/1.1 401 Unauthorized Date: Wed, 21 Oct 2015 07:28:00 GMT WWW-Authenticate: Basic realm="Access to staging site" ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.401](https://httpwg.org/specs/rfc9110.html#status.401) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `401` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [HTTP authentication](../authentication) * [`WWW-Authenticate`](../headers/www-authenticate) * [`Authorization`](../headers/authorization) * [`Proxy-Authorization`](../headers/proxy-authorization) * [`Proxy-Authenticate`](../headers/proxy-authenticate) * [`403`](403), [`407`](407) http 303 See Other 303 See Other ============= 303 See Other ============= The HyperText Transfer Protocol (HTTP) `303 See Other` redirect status response code indicates that the redirects don't link to the requested resource itself, but to another page (such as a confirmation page, a representation of a real-world object — see [HTTP range-14](https://en.wikipedia.org/wiki/HTTPRange-14) — or an upload-progress page). This response code is often sent back as a result of [`PUT`](../methods/put) or [`POST`](../methods/post). The method used to display this redirected page is always [`GET`](../methods/get). Status ------ ``` 303 See Other ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.303](https://httpwg.org/specs/rfc9110.html#status.303) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `303` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`302 Found`](302), a temporary redirect * [`307 Temporary Redirect`](307), a temporary redirect where the method used never changes. http 508 Loop Detected 508 Loop Detected ================= 508 Loop Detected ================= The HyperText Transfer Protocol (HTTP) `508 Loop Detected` response status code may be given in the context of the Web Distributed Authoring and Versioning (WebDAV) protocol. It indicates that the server terminated an operation because it encountered an infinite loop while processing a request with "Depth: infinity". This status indicates that the entire operation failed. Status ------ ``` 508 Loop Detected ``` Specifications -------------- | Specification | | --- | | [RFC 5842 # section-7.2](https://www.rfc-editor.org/rfc/rfc5842#section-7.2) | http 206 Partial Content 206 Partial Content =================== 206 Partial Content =================== The HTTP `206 Partial Content` success status response code indicates that the request has succeeded and the body contains the requested ranges of data, as described in the [`Range`](../headers/range) header of the request. If there is only one range, the [`Content-Type`](../headers/content-type) of the whole response is set to the type of the document, and a [`Content-Range`](../headers/content-range) is provided. If several ranges are sent back, the [`Content-Type`](../headers/content-type) is set to `multipart/byteranges` and each fragment covers one range, with [`Content-Range`](../headers/content-range) and [`Content-Type`](../headers/content-type) describing it. Status ------ ``` 206 Partial Content ``` Examples -------- A response containing one single range: ``` HTTP/1.1 206 Partial Content Date: Wed, 15 Nov 2015 06:25:24 GMT Last-Modified: Wed, 15 Nov 2015 04:58:08 GMT Content-Range: bytes 21010-47021/47022 Content-Length: 26012 Content-Type: image/gif # 26012 bytes of partial image data… ``` A response containing several ranges: ``` HTTP/1.1 206 Partial Content Date: Wed, 15 Nov 2015 06:25:24 GMT Last-Modified: Wed, 15 Nov 2015 04:58:08 GMT Content-Length: 1741 Content-Type: multipart/byteranges; boundary=String\_separator --String_separator Content-Type: application/pdf Content-Range: bytes 234-639/8000 # the first range --String_separator Content-Type: application/pdf Content-Range: bytes 4590-7999/8000 # the second range --String_separator-- ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.206](https://httpwg.org/specs/rfc9110.html#status.206) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `206` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`If-Range`](../headers/if-range) * [`Range`](../headers/range) * [`Content-Range`](../headers/content-range) * [`Content-Type`](../headers/content-type) http 302 Found 302 Found ========= 302 Found ========= The HyperText Transfer Protocol (HTTP) `302 Found` redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the [`Location`](../headers/location) header. A browser redirects to this page but search engines don't update their links to the resource (in 'SEO-speak', it is said that the 'link-juice' is not sent to the new URL). Even if the specification requires the method (and the body) not to be altered when the redirection is performed, not all user-agents conform here - you can still find this type of bugged software out there. It is therefore recommended to set the `302` code only as a response for [`GET`](../methods/get) or [`HEAD`](../methods/head) methods and to use [`307 Temporary Redirect`](307) instead, as the method change is explicitly prohibited in that case. In the cases where you want the method used to be changed to [`GET`](../methods/get), use [`303 See Other`](303) instead. This is useful when you want to give a response to a [`PUT`](../methods/put) method that is not the uploaded resource but a confirmation message such as: 'you successfully uploaded XYZ'. Status ------ ``` 302 Found ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.302](https://httpwg.org/specs/rfc9110.html#status.302) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `302` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`307 Temporary Redirect`](307), the equivalent of this status code where the method used never changes. * [`303 See Other`](303), a temporary redirect that changes the method used to [`GET`](../methods/get). * [`301 Moved Permanently`](301), a permanent redirect. http 400 Bad Request 400 Bad Request =============== 400 Bad Request =============== The HyperText Transfer Protocol (HTTP) `400 Bad Request` response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (for example, malformed request syntax, invalid request message framing, or deceptive request routing). **Warning:** The client should not repeat this request without modification. Status ------ ``` 400 Bad Request ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.400](https://httpwg.org/specs/rfc9110.html#status.400) | See also -------- * [HTTP/1.1: Status Code Definitions](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) http 103 Early Hints 103 Early Hints =============== 103 Early Hints =============== **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. The HTTP `103 Early Hints` information response status code is primarily intended to be used with the [`Link`](../headers/link) header to allow the user agent to start preloading resources while the server is still preparing a response. Syntax ------ ``` 103 Early Hints ``` Specifications -------------- | Specification | | --- | | [HTML Standard # early-hints](https://html.spec.whatwg.org/multipage/semantics.html#early-hints) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `103` | 103 | No | No | No | No | No | ? | 103 | ? | ? | ? | ? | See also -------- * [`Link`](../headers/link) http 416 Range Not Satisfiable 416 Range Not Satisfiable ========================= 416 Range Not Satisfiable ========================= The HyperText Transfer Protocol (HTTP) `416 Range Not Satisfiable` error response code indicates that a server cannot serve the requested ranges. The most likely reason is that the document doesn't contain such ranges, or that the [`Range`](../headers/range) header value, though syntactically correct, doesn't make sense. The `416` response message contains a [`Content-Range`](../headers/content-range) indicating an unsatisfied range (that is a `'*'`) followed by a `'/'` and the current length of the resource. E.g. `Content-Range: bytes */12777` Faced with this error, browsers usually either abort the operation (for example, a download will be considered as non-resumable) or ask for the whole document again. Status ------ ``` 416 Range Not Satisfiable ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.416](https://httpwg.org/specs/rfc9110.html#status.416) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `416` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`206`](206) `Partial Content` * [`Content-Range`](../headers/content-range) * [`Range`](../headers/range) http 504 Gateway Timeout 504 Gateway Timeout =================== 504 Gateway Timeout =================== The HyperText Transfer Protocol (HTTP) `504 Gateway Timeout` server error response code indicates that the server, while acting as a gateway or proxy, did not get a response in time from the upstream server that it needed in order to complete the request. **Note:** A [Gateway](https://en.wikipedia.org/wiki/Gateway_(telecommunications)) might refer to different things in networking and a 504 error is usually not something you can fix, but requires a fix by the web server or the proxies you are trying to get access through. Status ------ ``` 504 Gateway Timeout ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.504](https://httpwg.org/specs/rfc9110.html#status.504) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `504` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [HTTP/1.1: Status Code Definitions](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) * [`502`](502) http Evolution of HTTP Evolution of HTTP ================= Evolution of HTTP ================= **HTTP** (HyperText Transfer Protocol) is the underlying protocol of the World Wide Web. Developed by Tim Berners-Lee and his team between 1989-1991, HTTP has gone through many changes that have helped maintain its simplicity while shaping its flexibility. Keep reading to learn how HTTP evolved from a protocol designed to exchange files in a semitrusted laboratory environment into a modern internet maze that carries images and videos in high resolution and 3D. Invention of the World Wide Web ------------------------------- In 1989, while working at CERN, Tim Berners-Lee wrote a proposal to build a hypertext system over the internet. Initially called the *Mesh*, it was later renamed the *World Wide Web* during its implementation in 1990. Built over the existing TCP and IP protocols, it consisted of 4 building blocks: * A textual format to represent hypertext documents, the *[HyperText Markup Language](https://developer.mozilla.org/en-US/docs/Web/HTML)* (HTML). * A simple protocol to exchange these documents, the *HyperText Transfer Protocol* (HTTP). * A client to display (and edit) these documents, the first web browser called the *WorldWideWeb*. * A server to give access to the document, an early version of *httpd*. These four building blocks were completed by the end of 1990, and the first servers were running outside of CERN by early 1991. On August 6, 1991, Tim Berners-Lee [posted](https://www.w3.org/People/Berners-Lee/1991/08/art-6484.txt) on the public *alt.hypertext* newsgroup. This is now considered to be the official start of the World Wide Web as a public project. The HTTP protocol used in those early phases was very simple. It was later dubbed HTTP/0.9 and is sometimes called the one-line protocol. HTTP/0.9 – The one-line protocol -------------------------------- The initial version of HTTP had no version number; it was later called 0.9 to differentiate it from later versions. HTTP/0.9 was extremely simple: requests consisted of a single line and started with the only possible method [`GET`](../methods/get) followed by the path to the resource. The full URL wasn't included as the protocol, server, and port weren't necessary once connected to the server. ``` GET /mypage.html ``` The response was extremely simple, too: it only consisted of the file itself. ``` <html> A very simple HTML page </html> ``` Unlike subsequent evolutions, there were no HTTP headers. This meant that only HTML files could be transmitted. There were no status or error codes. If there was a problem, a specific HTML file was generated and included a description of the problem for human consumption. HTTP/1.0 – Building extensibility --------------------------------- HTTP/0.9 was very limited, but browsers and servers quickly made it more versatile: * Versioning information was sent within each request (`HTTP/1.0` was appended to the `GET` line). * A status code line was also sent at the beginning of a response. This allowed the browser itself to recognize the success or failure of a request and adapt its behavior accordingly. For example, updating or using its local cache in a specific way. * The concept of HTTP headers was introduced for both requests and responses. Metadata could be transmitted and the protocol became extremely flexible and extensible. * Documents other than plain HTML files could be transmitted thanks to the [`Content-Type`](../headers/content-type) header. At this point in time, a typical request and response looked like this: ``` GET /mypage.html HTTP/1.0 User-Agent: NCSA\_Mosaic/2.0 (Windows 3.1) 200 OK Date: Tue, 15 Nov 1994 08:12:31 GMT Server: CERN/3.0 libwww/2.17 Content-Type: text/html <HTML> A page with an image <IMG SRC="/myimage.gif"> </HTML> ``` It was followed by a second connection and a request to fetch the image (with the corresponding response): ``` GET /myimage.gif HTTP/1.0 User-Agent: NCSA\_Mosaic/2.0 (Windows 3.1) 200 OK Date: Tue, 15 Nov 1994 08:12:32 GMT Server: CERN/3.0 libwww/2.17 Content-Type: text/gif (image content) ``` Between 1991-1995, these were introduced with a try-and-see approach. A server and a browser would add a feature and see if it got traction. Interoperability problems were common. In an effort to solve these issues, an informational document that described the common practices was published in November 1996. This was known as [RFC 1945](https://datatracker.ietf.org/doc/html/rfc1945) and defined HTTP/1.0. HTTP/1.1 – The standardized protocol ------------------------------------ In the meantime, proper standardization was in progress. This happened in parallel to the diverse implementations of HTTP/1.0. The first standardized version of HTTP, HTTP/1.1, was published in early 1997, only a few months after HTTP/1.0. HTTP/1.1 clarified ambiguities and introduced numerous improvements: * A connection could be reused, which saved time. It no longer needed to be opened multiple times to display the resources embedded in the single original document. * Pipelining was added. This allowed a second request to be sent before the answer to the first one was fully transmitted. This lowered the latency of the communication. * Chunked responses were also supported. * Additional cache control mechanisms were introduced. * Content negotiation, including language, encoding, and type, was introduced. A client and a server could now agree on which content to exchange. * Thanks to the [`Host`](../headers/host) header, the ability to host different domains from the same IP address allowed server collocation. A typical flow of requests, all through one single connection, looked like this: ``` GET /en-US/docs/Glossary/Simple\_header HTTP/1.1 Host: developer.mozilla.org User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,\*/\*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Referer: https://developer.mozilla.org/en-US/docs/Glossary/Simple\_header 200 OK Connection: Keep-Alive Content-Encoding: gzip Content-Type: text/html; charset=utf-8 Date: Wed, 20 Jul 2016 10:55:30 GMT Etag: "547fa7e369ef56031dd3bff2ace9fc0832eb251a" Keep-Alive: timeout=5, max=1000 Last-Modified: Tue, 19 Jul 2016 00:59:33 GMT Server: Apache Transfer-Encoding: chunked Vary: Cookie, Accept-Encoding (content) GET /static/img/header-background.png HTTP/1.1 Host: developer.mozilla.org User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0 Accept: \*/\* Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Referer: https://developer.mozilla.org/en-US/docs/Glossary/Simple\_header 200 OK Age: 9578461 Cache-Control: public, max-age=315360000 Connection: keep-alive Content-Length: 3077 Content-Type: image/png Date: Thu, 31 Mar 2016 13:34:46 GMT Last-Modified: Wed, 21 Oct 2015 18:27:50 GMT Server: Apache (image content of 3077 bytes) ``` HTTP/1.1 was first published as [RFC 2068](https://datatracker.ietf.org/doc/html/rfc2068) in January 1997. More than 15 years of extensions -------------------------------- The extensibility of HTTP made it easy to create new headers and methods. Even though the HTTP/1.1 protocol was refined over two revisions, [RFC 2616](https://datatracker.ietf.org/doc/html/rfc2616) published in June 1999 and [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230)-[RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235) published in June 2014 before the release of HTTP/2, it was extremely stable for more than 15 years. ### Using HTTP for secure transmissions The largest change to HTTP was made at the end of 1994. Instead of sending HTTP over a basic TCP/IP stack, the computer-services company Netscape Communications created an additional encrypted transmission layer on top of it: SSL. SSL 1.0 was never released to the public, but SSL 2.0 and its successor SSL 3.0 allowed for the creation of ecommerce websites. To do this, they encrypted and guaranteed the authenticity of the messages exchanged between the server and client. SSL was eventually standardized and became TLS. During the same time period, it became clear that an encrypted transport layer was needed. The web was no longer a mostly academic network, and instead became a jungle where advertisers, random individuals, and criminals competed for as much private data as possible. As the applications built over HTTP became more powerful and required access to private information like address books, email, and user location, TLS became necessary outside of the ecommerce use case. ### Using HTTP for complex applications Tim Berners-Lee didn't originally envision HTTP as a read-only medium. He wanted to create a web where people could add and move documents remotely—a kind of distributed file system. Around 1996, HTTP was extended to allow authoring, and a standard called WebDAV was created. It grew to include specific applications like CardDAV for handling address book entries and CalDAV for dealing with calendars. But all these \*DAV extensions had a flaw: they were only usable when implemented by the servers. In 2000, a new pattern for using HTTP was designed: [representational state transfer](https://developer.mozilla.org/en-US/docs/Glossary/REST) (or REST). The API wasn't based on the new HTTP methods, but instead relied on access to specific URIs with basic HTTP/1.1 methods. This allowed any web application to let an API retrieve and modify its data without having to update the browsers or the servers. All necessary information was embedded in the files that the websites served through standard HTTP/1.1. The drawback of the REST model was that each website defined its own nonstandard RESTful API and had total control of it. This differed from the \*DAV extensions where clients and servers were interoperable. RESTful APIs became very common in the 2010s. Since 2005, more APIs have become available to web pages. Several of these APIs create extensions to the HTTP protocol for specific purposes: * [Server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events), where the server can push occasional messages to the browser. * [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API), a new protocol that can be set up by upgrading an existing HTTP connection. ### Relaxing the security-model of the web HTTP is independent of the web security model, known as the [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). In fact, the current web security model was developed after the creation of HTTP! Over the years, it proved useful to lift some of the restrictions of this policy under certain constraints. The server transmitted how much and when to lift such restrictions to the client using a new set of HTTP headers. These were defined in specifications like [Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Glossary/CORS) (CORS) and the [Content Security Policy](../csp) (CSP). In addition to these large extensions, many other headers were added, sometimes only experimentally. Notable headers are the Do Not Track ([`DNT`](../headers/dnt)) header to control privacy, [`X-Frame-Options`](../headers/x-frame-options), and [`Upgrade-Insecure-Requests`](../headers/upgrade-insecure-requests) but many more exist. HTTP/2 – A protocol for greater performance ------------------------------------------- Over the years, web pages became more complex. Some of them were even applications in their own right. More visual media was displayed and the volume and size of scripts adding interactivity also increased. Much more data was transmitted over significantly more HTTP requests and this created more complexity and overhead for HTTP/1.1 connections. To account for this, Google implemented an experimental protocol SPDY in the early 2010s. This alternative way of exchanging data between client and server amassed interest from developers working on both browsers and servers. SPDY defined an increase in responsiveness and solved the problem of duplicate data transmission, serving as the foundation for the HTTP/2 protocol. The HTTP/2 protocol differs from HTTP/1.1 in a few ways: * It's a binary protocol rather than a text protocol. It can't be read and created manually. Despite this hurdle, it allows for the implementation of improved optimization techniques. * It's a multiplexed protocol. Parallel requests can be made over the same connection, removing the constraints of the HTTP/1.x protocol. * It compresses headers. As these are often similar among a set of requests, this removes the duplication and overhead of data transmitted. * It allows a server to populate data in a client cache through a mechanism called the server push. Officially standardized in May 2015, HTTP/2 use peaked in January 2022 at 46.9% of all websites (see [these stats](https://w3techs.com/technologies/details/ce-http2)). High-traffic websites showed the most rapid adoption in an effort to save on data transfer overhead and subsequent budgets. This rapid adoption was likely because HTTP/2 didn't require changes to websites and applications. To use it, only an up-to-date server that communicated with a recent browser was necessary. Only a limited set of groups was needed to trigger adoption, and as legacy browser and server versions were renewed, usage was naturally increased, without significant work for web developers. Post-HTTP/2 evolution --------------------- HTTP's extensibility is still being used to add new features. Notably, we can cite new extensions of the HTTP protocol that appeared in 2016: * Support for [`Alt-Svc`](../headers/alt-svc) allowed the dissociation of the identification and the location of a given resource. This meant a smarter [CDN](https://developer.mozilla.org/en-US/docs/Glossary/CDN) caching mechanism. * The introduction of [client hints](../client_hints) allowed the browser or client to proactively communicate information about its requirements and hardware constraints to the server. * The introduction of security-related prefixes in the [`Cookie`](../headers/cookie) header helped guarantee that secure cookies couldn't be altered. HTTP/3 - HTTP over QUIC ----------------------- The next major version of HTTP, HTTP/3 has the same semantics as earlier versions of HTTP but uses [QUIC](https://developer.mozilla.org/en-US/docs/Glossary/QUIC) instead of [TCP](https://developer.mozilla.org/en-US/docs/Glossary/TCP) for the transport layer portion. By October 2022, [26% of all websites were using HTTP/3](https://w3techs.com/technologies/details/ce-http3)). QUIC is designed to provide much lower latency for HTTP connections. Like HTTP/2, it is a multiplexed protocol, but HTTP/2 runs over a single TCP connection, so packet loss detection and retransmission handled at the TCP layer can block all streams. QUIC runs multiple streams over [UDP](https://developer.mozilla.org/en-US/docs/Glossary/UDP) and implements packet loss detection and retransmission independently for each stream, so that if an error occurs, only the stream with data in that packet is blocked. Defined in [RFC 9114](https://datatracker.ietf.org/doc/html/rfc9114), [HTTP/3 is supported by most major browsers](https://caniuse.com/http3) including Chromium (and its variants such as Chrome and Edge) and Firefox.
programming_docs
http MIME types MIME types ========== MIME types (IANA media types) ============================= A **media type** (also known as a **Multipurpose Internet Mail Extensions or MIME type**) indicates the nature and format of a document, file, or assortment of bytes. MIME types are defined and standardized in IETF's [RFC 6838](https://datatracker.ietf.org/doc/html/rfc6838). The [Internet Assigned Numbers Authority (IANA)](https://www.iana.org/) is responsible for all official MIME types, and you can find the most up-to-date and complete list at their [Media Types](https://www.iana.org/assignments/media-types/media-types.xhtml) page. **Warning:** Browsers use the MIME type, *not the file extension*, to determine how to process a URL, so it's important that web servers send the correct MIME type in the response's [`Content-Type`](../headers/content-type) header. If this is not correctly configured, browsers are likely to misinterpret the contents of files, sites will not work correctly, and downloaded files may be mishandled. Structure of a MIME type ------------------------ A MIME type most-commonly consists of just two parts: a *type* and a *subtype*, separated by a slash (`/`) — with no whitespace between: ``` type/subtype ``` The ***type*** represents the general category into which the data type falls, such as `video` or `text`. The ***subtype*** identifies the exact kind of data of the specified type the MIME type represents. For example, for the MIME type `text`, the subtype might be `plain` (plain text), `html` ([HTML](https://developer.mozilla.org/en-US/docs/Glossary/HTML) source code), or `calendar` (for iCalendar/`.ics`) files. Each type has its own set of possible subtypes. A MIME type always has both a type and a subtype, never just one or the other. An optional **parameter** can be added to provide additional details: ``` type/subtype;parameter=value ``` For example, for any MIME type whose main type is `text`, you can add the optional `charset` parameter to specify the character set used for the characters in the data. If no `charset` is specified, the default is [ASCII](https://developer.mozilla.org/en-US/docs/Glossary/ASCII) (`US-ASCII`) unless overridden by the [user agent's](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) settings. To specify a UTF-8 text file, the MIME type `text/plain;charset=UTF-8` is used. MIME types are case-insensitive but are traditionally written in lowercase. The parameter values can be case-sensitive. ### Types There are two classes of type: **discrete** and **multipart**. Discrete types are types which represent a single file or medium, such as a single text or music file, or a single video. A multipart type is one which represents a document that's comprised of multiple component parts, each of which may have its own individual MIME type; or, a multipart type may encapsulate multiple files being sent together in one transaction. For example, multipart MIME types are used when attaching multiple files to an email. #### Discrete types The discrete types currently registered with the IANA are: `application` Any kind of binary data that doesn't fall explicitly into one of the other types; either data that will be executed or interpreted in some way or binary data that requires a specific application or category of application to use. Generic binary data (or binary data whose true type is unknown) is `application/octet-stream`. Other common examples include `application/pdf`, `application/pkcs8`, and `application/zip`. [(Registration at IANA)](https://www.iana.org/assignments/media-types/media-types.xhtml#application) `audio` Audio or music data. Examples include `audio/mpeg`, `audio/vorbis`. [(Registration at IANA)](https://www.iana.org/assignments/media-types/media-types.xhtml#audio) `example` Reserved for use as a placeholder in examples showing how to use MIME types. These should never be used outside of sample code listings and documentation. `example` can also be used as a subtype; for instance, in an example related to working with audio on the web, the MIME type `audio/example` can be used to indicate that the type is a placeholder and should be replaced with an appropriate one when using the code in the real world. `font` Font/typeface data. Common examples include `font/woff`, `font/ttf`, and `font/otf`. [(Registration at IANA)](https://www.iana.org/assignments/media-types/media-types.xhtml#font) `image` Image or graphical data including both bitmap and vector still images as well as animated versions of still image formats such as animated [GIF](https://developer.mozilla.org/en-US/docs/Glossary/gif) or APNG. Common examples are `image/jpeg`, `image/png`, and `image/svg+xml`. [(Registration at IANA)](https://www.iana.org/assignments/media-types/media-types.xhtml#image) `model` Model data for a 3D object or scene. Examples include `model/3mf` and `model/vrml`. [(Registration at IANA)](https://www.iana.org/assignments/media-types/media-types.xhtml#model) `text` Text-only data including any human-readable content, source code, or textual data such as comma-separated value (CSV) formatted data. Examples include: `text/plain`, `text/csv`, and `text/html`. [(Registration at IANA)](https://www.iana.org/assignments/media-types/media-types.xhtml#text) `video` Video data or files, such as MP4 movies (`video/mp4`). [(Registration at IANA)](https://www.iana.org/assignments/media-types/media-types.xhtml#video) For text documents without a specific subtype, `text/plain` should be used. Similarly, for binary documents without a specific or known subtype, `application/octet-stream` should be used. #### Multipart types **Multipart** types indicate a category of document broken into pieces, often with different MIME types; they can also be used — especially in email scenarios — to represent multiple, separate files which are all part of the same transaction. They represent a **composite document**. Except for `multipart/form-data`, used in the [`POST`](../methods/post) method of [HTML Forms](https://developer.mozilla.org/en-US/docs/Learn/Forms), and `multipart/byteranges`, used with [`206`](../status/206) `Partial Content` to send part of a document, HTTP doesn't handle multipart documents in a special way: the message is transmitted to the browser (which will likely show a "Save As" window if it doesn't know how to display the document). There are two multipart types: `message` A message that encapsulates other messages. This can be used, for instance, to represent an email that includes a forwarded message as part of its data, or to allow sending very large messages in chunks as if it were multiple messages. Examples include `message/rfc822` (for forwarded or replied-to message quoting) and `message/partial` to allow breaking a large message into smaller ones automatically to be reassembled by the recipient. [(Registration at IANA)](https://www.iana.org/assignments/media-types/media-types.xhtml#message) `multipart` Data that consists of multiple components which may individually have different MIME types. Examples include `multipart/form-data` (for data produced using the [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) API) and `multipart/byteranges` (defined in [RFC 7233, section 5.4.1](https://datatracker.ietf.org/doc/html/rfc7233#section-5.4.1) and used with [HTTP](https://developer.mozilla.org/en-US/docs/Glossary/HTTP)'s [`206`](../status/206) "Partial Content" response returned when the fetched data is only part of the content, such as is delivered using the [`Range`](../headers/range) header). [(Registration at IANA)](https://www.iana.org/assignments/media-types/media-types.xhtml#multipart) Important MIME types for Web developers --------------------------------------- ### application/octet-stream This is the default for binary files. As it means *unknown binary* file, browsers usually don't execute it, or even ask if it should be executed. They treat it as if the [`Content-Disposition`](../headers/content-disposition) header was set to `attachment`, and propose a "Save As" dialog. ### text/plain This is the default for textual files. Even if it really means "unknown textual file," browsers assume they can display it. **Note:** `text/plain` does not mean "any kind of textual data." If they expect a specific kind of textual data, they will likely not consider it a match. Specifically if they download a `text/plain` file from a [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) element declaring a CSS file, they will not recognize it as a valid CSS file if presented with `text/plain`. The CSS mime type `text/css` must be used. ### text/css CSS files used to style a Web page **must** be sent with `text/css`. If a server doesn't recognize the `.css` suffix for CSS files, it may send them with `text/plain` or `application/octet-stream` MIME types. If so, they won't be recognized as CSS by most browsers and will be ignored. ### text/html All HTML content should be served with this type. Alternative MIME types for XHTML (like `application/xhtml+xml`) are mostly useless nowadays. **Note:** Use `application/xml` or `application/xhtml+xml` if you want XML's strict parsing rules, [`<![CDATA[…]]>`](https://developer.mozilla.org/en-US/docs/Web/API/CDATASection) sections, or elements that aren't from HTML/SVG/MathML namespaces. ### text/javascript Per the [IANA Media Types registry](https://www.iana.org/assignments/media-types/media-types.xhtml#text), [RFC 9239](https://www.rfc-editor.org/rfc/rfc9239.html), and the [HTML specification](https://html.spec.whatwg.org/multipage/scripting.html#scriptingLanguages:text/javascript), JavaScript content should always be served using the MIME type `text/javascript`. No other MIME types are considered valid for JavaScript, and using any MIME type other than `text/javascript` may result in scripts that do not load or run. You may find some JavaScript content incorrectly served with a `charset` parameter as part of the MIME type — as an attempt to specify the character set for the script content. That `charset` parameter isn't valid for JavaScript content, and in most cases will result in a script failing to load. #### Legacy JavaScript MIME types In addition to the `text/javascript` MIME type, for historical reasons, the [MIME Sniffing Standard](https://mimesniff.spec.whatwg.org/) (the definition of how browsers should interpret MIME types and figure out what to do with content that doesn't have a valid one) also allows JavaScript to be served using any of the following legacy JavaScript MIME types: * `application/javascript` Deprecated * `application/ecmascript` Deprecated * `application/x-ecmascript` Non-standard * `application/x-javascript` Non-standard * `text/ecmascript` Deprecated * `text/javascript1.0` Non-standard * `text/javascript1.1` Non-standard * `text/javascript1.2` Non-standard * `text/javascript1.3` Non-standard * `text/javascript1.4` Non-standard * `text/javascript1.5` Non-standard * `text/jscript` Non-standard * `text/livescript` Non-standard * `text/x-ecmascript` Non-standard * `text/x-javascript` Non-standard **Note:** Even though any given [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) may support any or all of these, you should only use `text/javascript`. It's the only MIME type guaranteed to work now and into the future. ### Image types Files whose MIME type is `image` contain image data. The subtype specifies which specific image file format the data represents. The following image types are used commonly enough to be considered *safe* for use on web pages: * [`image/apng`](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#apng_animated_portable_network_graphics): Animated Portable Network Graphics (APNG) * [`image/avif`](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#avif_image) : AV1 Image File Format (AVIF) * [`image/gif`](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#gif_graphics_interchange_format): Graphics Interchange Format (GIF) * [`image/jpeg`](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#jpeg_joint_photographic_experts_group_image): Joint Photographic Expert Group image (JPEG) * [`image/png`](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#png_portable_network_graphics): Portable Network Graphics (PNG) * [`image/svg+xml`](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#svg_scalable_vector_graphics): Scalable Vector Graphics (SVG) * [`image/webp`](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#webp_image): Web Picture format (WEBP) The [Image file type and format guide](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) provides information and recommendations about when to use the different image formats. ### Audio and video types As is the case for images, HTML doesn't mandate that web browsers support any specific file and codec types for the [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) and [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) elements, so it's important to consider your target audience and the range of browsers (and versions of those browsers) they may be using when choosing the file type and codecs to use for media. Our [media container formats guide](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers) provides a list of the file types that are commonly supported by web browsers, including information about what their special use cases may be, any drawbacks they have, and compatibility information, along with other details. The [audio codec](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Audio_codecs) and [video codec](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs) guides list the various codecs that web browsers often support, providing compatibility details along with technical information such as how many audio channels they support, what sort of compression is used, and what bit rates and so forth they're useful at. The [codecs used by WebRTC](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/WebRTC_codecs) guide expands upon this by specifically covering the codecs supported by the major web browsers, so you can choose the codecs that best cover the range of browsers you wish to support. As for MIME types of audio or video files, they typically specify the container format (file type). The optional [codecs parameter](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/codecs_parameter) can be added to the MIME type to further specify which codecs to use and what options were used to encode the media, such as codec profile, level, or other such information. The most commonly used MIME types used for web content are listed below. This isn't a complete list of all the types that may be available, however. See the [media container formats guide](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers) for that. | MIME type | Audio or video type | | --- | --- | | `audio/wave` `audio/wav` `audio/x-wav` `audio/x-pn-wav` | An audio file in the WAVE container format. The PCM audio codec (WAVE codec "1") is often supported, but other codecs have limited support (if any). | | `audio/webm` | An audio file in the WebM container format. Vorbis and Opus are the codecs officially supported by the WebM specification. | | `video/webm` | A video file, possibly with audio, in the WebM container format. VP8 and VP9 are the most common video codecs; Vorbis and Opus the most common audio codecs. | | `audio/ogg` | An audio file in the Ogg container format. Vorbis is the most common audio codec used in such a container; however, Opus is now supported by Ogg as well. | | `video/ogg` | A video file, possibly with audio, in the Ogg container format. Theora is the usual video codec used within it; Vorbis is the usual audio codec, although Opus is becoming more common. | | `application/ogg` | An audio or video file using the Ogg container format. Theora is the usual video codec used within it; Vorbis is the usual audio codec. | ### multipart/form-data The `multipart/form-data` type can be used when sending the values of a completed [HTML Form](https://developer.mozilla.org/en-US/docs/Learn/Forms) from browser to server. As a multipart document format, it consists of different parts, delimited by a boundary (a string starting with a double dash `--`). Each part is its own entity with its own HTTP headers, [`Content-Disposition`](../headers/content-disposition), and [`Content-Type`](../headers/content-type) for file uploading fields. ``` Content-Type: multipart/form-data; boundary=aBoundaryString (other headers associated with the multipart document as a whole) --aBoundaryString Content-Disposition: form-data; name="myFile"; filename="img.jpg" Content-Type: image/jpeg (data) --aBoundaryString Content-Disposition: form-data; name="myField" (data) --aBoundaryString (more subparts) --aBoundaryString-- ``` The following `<form>`: ``` <form action="http://localhost:8000/" method="post" enctype="multipart/form-data"> <label>Name: <input name="myTextField" value="Test" /></label> <label><input type="checkbox" name="myCheckBox" /> Check</label> <label> Upload file: <input type="file" name="myFile" value="test.txt"/> </label> <button>Send the file</button> </form> ``` will send this message: ``` POST / HTTP/1.1 Host: localhost:8000 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Upgrade-Insecure-Requests: 1 Content-Type: multipart/form-data; boundary=---------------------------8721656041911415653955004498 Content-Length: 465 -----------------------------8721656041911415653955004498 Content-Disposition: form-data; name="myTextField" Test -----------------------------8721656041911415653955004498 Content-Disposition: form-data; name="myCheckBox" on -----------------------------8721656041911415653955004498 Content-Disposition: form-data; name="myFile"; filename="test.txt" Content-Type: text/plain Simple file. -----------------------------8721656041911415653955004498-- ``` ### multipart/byteranges The `multipart/byteranges` MIME type is used to send partial responses to the browser. When the [`206 Partial Content`](../status/206) status code is sent, this MIME type indicates that the document is composed of several parts, one for each of the requested ranges. Like other multipart types, the [`Content-Type`](../headers/content-type) uses a `boundary` to separate the pieces. Each piece has a [`Content-Type`](../headers/content-type) header with its actual type and a [`Content-Range`](../headers/content-range) of the range it represents. ``` HTTP/1.1 206 Partial Content Accept-Ranges: bytes Content-Type: multipart/byteranges; boundary=3d6b6a416f9b5 Content-Length: 385 --3d6b6a416f9b5 Content-Type: text/html Content-Range: bytes 100-200/1270 eta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta name="viewport" content --3d6b6a416f9b5 Content-Type: text/html Content-Range: bytes 300-400/1270 -color: #f0f0f2; margin: 0; padding: 0; font-family: "Open Sans", "Helvetica --3d6b6a416f9b5-- ``` Importance of setting the correct MIME type ------------------------------------------- Most web servers send unrecognized resources as the `application/octet-stream` MIME type. For security reasons, most browsers do not allow setting a custom default action for such resources, forcing the user to save it to disk to use it. Some common incorrect server configurations: * RAR-compressed files. In this case, the ideal would be the true type of the original files; this is often impossible as .RAR files can hold several resources of different types. In this case, configure the server to send `application/x-rar-compressed`. * Audio and video. Only resources with the correct MIME Type will be played in [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) or [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) elements. Be sure to specify the correct [media type for audio and video](https://developer.mozilla.org/en-US/docs/Web/Media/Formats). * Proprietary file types. Avoid using `application/octet-stream` as most browsers do not allow defining a default behavior (like "Open in Word") for this generic MIME type. A specific type like `application/vnd.mspowerpoint` lets users open such files automatically in the presentation software of their choice. MIME sniffing ------------- In the absence of a MIME type, or in certain cases where browsers believe they are incorrect, browsers may perform *MIME sniffing* — guessing the correct MIME type by looking at the bytes of the resource. Each browser performs MIME sniffing differently and under different circumstances. (For example, Safari will look at the file extension in the URL if the sent MIME type is unsuitable.) There are security concerns as some MIME types represent executable content. Servers can prevent MIME sniffing by sending the [`X-Content-Type-Options`](../headers/x-content-type-options) header. Other methods of conveying document type ---------------------------------------- MIME types are not the only way to convey document type information: * Filename suffixes are sometimes used, especially on Microsoft Windows. Not all operating systems consider these suffixes meaningful (such as Linux and macOS), and there is no guarantee they are correct. * Magic numbers. The syntax of different formats allows file-type inference by looking at their byte structure. For example, GIF files start with the `47 49 46 38 39` hexadecimal value (`GIF89`), and PNG files with `89 50 4E 47` (`.PNG`). Not all file types have magic numbers, so this is not 100% reliable either. See also -------- * [Web media technologies](https://developer.mozilla.org/en-US/docs/Web/Media) * [Guide to media types used on the web](https://developer.mozilla.org/en-US/docs/Web/Media/Formats) * [Properly configuring server MIME types](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Configuring_server_MIME_types)
programming_docs
http Data URLs Data URLs ========= Data URLs ========= **Data URLs**, URLs prefixed with the `data:` scheme, allow content creators to embed small files inline in documents. They were formerly known as "data URIs" until that name was retired by the WHATWG. **Note:** Data URLs are treated as unique opaque origins by modern browsers, rather than inheriting the origin of the settings object responsible for the navigation. Syntax ------ Data URLs are composed of four parts: a prefix (`data:`), a [MIME type](mime_types) indicating the type of data, an optional `base64` token if non-textual, and the data itself: ``` data:[<mediatype>][;base64],<data> ``` The `mediatype` is a [MIME type](mime_types) string, such as `'image/jpeg'` for a JPEG image file. If omitted, defaults to `text/plain;charset=US-ASCII` If the data contains [characters defined in RFC 3986 as reserved characters](https://datatracker.ietf.org/doc/html/rfc3986#section-2.2), or contains space characters, newline characters, or other non-printing characters, those characters must be [percent-encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding) (*aka* "URL-encoded"). If the data is textual, you can embed the text (using the appropriate entities or escapes based on the enclosing document's type). Otherwise, you can specify `base64` to embed base64-encoded binary data. You can find more info on MIME types [here](mime_types) and [here](mime_types/common_types). A few examples: `data:,Hello%2C%20World%21` The text/plain data `Hello, World!`. Note how the comma is [percent-encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding) as `%2C`, and the space character as `%20`. `data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==` base64-encoded version of the above `data:text/html,%3Ch1%3EHello%2C%20World%21%3C%2Fh1%3E` An HTML document with `<h1>Hello, World!</h1>` `data:text/html,%3Cscript%3Ealert%28%27hi%27%29%3B%3C%2Fscript%3E` An HTML document with `<script>alert('hi');</script>` that executes a JavaScript alert. Note that the closing script tag is required. Encoding data into base64 format -------------------------------- Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. By consisting only of ASCII characters, base64 strings are generally url-safe, and that's why they can be used to encode data in Data URLs. ### Encoding in JavaScript The Web APIs have native methods to encode or decode to base64: [Base64 encoding and decoding](https://developer.mozilla.org/en-US/docs/Glossary/Base64). ### Encoding on a Unix system Base64 encoding of a file or string on Linux and macOS systems can be achieved using the command-line `base64` (or, as an alternative, the `uuencode` utility with `-m` argument). ``` echo -n hello|base64 # outputs to console: aGVsbG8= echo -n hello>a.txt base64 a.txt # outputs to console: aGVsbG8= base64 a.txt>b.txt # outputs to file b.txt: aGVsbG8= ``` ### Encoding on Microsoft Windows On Windows, [Convert.ToBase64String](https://docs.microsoft.com/dotnet/api/system.convert.tobase64string?view=net-5.0) from PowerShell can be used to perform the Base64 encoding: ``` [convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("hello")) # outputs to console: aGVsbG8= ``` Alternatively, a GNU/Linux shell (such as [WSL](https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux)) provides the utility `base64`: ``` bash$ echo -n hello | base64 # outputs to console: aGVsbG8= ``` Common problems --------------- This section describes problems that commonly occur when creating and using `data` URLs. ``` data:text/html,lots of text…<p><a name%3D"bottom">bottom</a>?arg=val</p> ``` This represents an HTML resource whose contents are: ``` lots of text… <p><a name="bottom">bottom</a>?arg=val</p> ``` Syntax The format for `data` URLs is very simple, but it's easy to forget to put a comma before the "data" segment, or to incorrectly encode the data into base64 format. Formatting in HTML A `data` URL provides a file within a file, which can potentially be very wide relative to the width of the enclosing document. As a URL, the `data` should be formattable with whitespace (linefeed, tab, or spaces), but there are practical issues that arise [when using base64 encoding](https://bugzilla.mozilla.org/show_bug.cgi?id=73026#c12). Length limitations Browsers are not required to support any particular maximum length of data. For example, the Opera 11 browser limited URLs to 65535 characters long which limits `data` URLs to 65529 characters (65529 characters being the length of the encoded data, not the source, if you use the plain `data:`, without specifying a MIME type). Firefox version 97 and newer supports `data` URLs of up to 32MB (before 97 the limit was close to 256MB). Chromium objects to URLs over 512MB, and Webkit (Safari) to URLs over 2048MB. Lack of error handling Invalid parameters in media, or typos when specifying `'base64'`, are ignored, but no error is provided. No support for query strings, etc. The data portion of a data URL is opaque, so an attempt to use a query string (page-specific parameters, with the syntax `<url>?parameter-data`) with a data URL will just include the query string in the data the URL represents. Security issues A number of security issues (for example, phishing) have been associated with data URLs, and navigating to them in the browser's top level. To mitigate such issues, top-level navigation to `data:` URLs is blocked in all modern browsers. See [this blog post from the Mozilla Security Team](https://blog.mozilla.org/security/2017/11/27/blocking-top-level-navigations-data-urls-firefox-59/) for more details. Specifications -------------- | Specification | | --- | | [The "data" URL scheme # section-2](https://www.rfc-editor.org/rfc/rfc2397#section-2) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Data_URLs` | Yes | 12 Before Edge 79, the maximum size supported is 4GB. | Yes | 8 ["Since Internet Explorer 9, the maximum size supported is 4GB.", "In Internet Explorer 8, the maximum size supported is 32kB."] | 7.2 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `css_files` | Yes | 12 | Yes | 8 | 7.2 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `html_files` | Yes | 79 | Yes | No | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `js_files` | Yes | 12 | Yes | 9 | 7.2 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `top_level_navigation_blocked` | 60 | ≤79 | 59 | No | 47 | 14 | No | 60 | 59 | 44 | 14 | 8.0 | See also -------- * [Base64 encoding and decoding](https://developer.mozilla.org/en-US/docs/Glossary/Base64) * [Percent encoding](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding) * [`atob()`](https://developer.mozilla.org/en-US/docs/Web/API/atob) * [`btoa()`](https://developer.mozilla.org/en-US/docs/Web/API/btoa) * [CSS `url()`](https://developer.mozilla.org/en-US/docs/Web/CSS/url) * [URI](https://developer.mozilla.org/en-US/docs/Glossary/URI) http Identifying resources on the Web Identifying resources on the Web ================================ Identifying resources on the Web ================================ The target of an HTTP request is called a "resource", whose nature isn't defined further; it can be a document, a photo, or anything else. Each resource is identified by a Uniform Resource Identifier ([URI](https://developer.mozilla.org/en-US/docs/Glossary/URI)) used throughout HTTP for identifying resources. URLs and URNs ------------- ### URLs The most common form of URI is the Uniform Resource Locator ([URL](https://developer.mozilla.org/en-US/docs/Glossary/URL)), which is known as the *web address*. ``` https://developer.mozilla.org https://developer.mozilla.org/en-US/docs/Learn/ https://developer.mozilla.org/en-US/search?q=URL ``` Any of those URLs can be typed into your browser's address bar to tell it to load the associated page (resource). A URL is composed of different parts, some mandatory and others are optional. A more complex example might look like this: ``` http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument ``` ### URNs A Uniform Resource Name (URN) is a URI that identifies a resource by name in a particular namespace. ``` urn:isbn:9780141036144 urn:ietf:rfc:7230 ``` The two URNs correspond to * the book Nineteen Eighty-Four by George Orwell, * the IETF specification 7230, Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing. Syntax of Uniform Resource Identifiers (URIs) --------------------------------------------- ### Scheme or protocol `http://` is the protocol. It indicates which protocol the browser must use. Usually it is the HTTP protocol or its secured version, HTTPS. The Web requires one of these two, but browsers also know how to handle other protocols such as `mailto:` (to open a mail client) or `ftp:` to handle a file transfer, so don't be surprised if you see such protocols. Common schemes are: | Scheme | Description | | --- | --- | | data | [Data URLs](data_urls) | | file | Host-specific file names | | ftp | [File Transfer Protocol](https://developer.mozilla.org/en-US/docs/Glossary/FTP) | | http/https | [Hyper text transfer protocol (Secure)](https://developer.mozilla.org/en-US/docs/Glossary/HTTP) | | javascript | URL-embedded JavaScript code | | mailto | Electronic mail address | | ssh | Secure shell | | tel | telephone | | urn | Uniform Resource Names | | view-source | Source code of the resource | | ws/wss | [WebSocket connections (Secure)](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) | ### Authority `www.example.com` is the domain name or authority that governs the namespace. It indicates which Web server is being requested. Alternatively, it is possible to directly use an [IP address](https://developer.mozilla.org/en-US/docs/Glossary/IP_Address), but because it is less convenient, it is not often used on the Web. ### Port `:80` is the port in this instance. It indicates the technical "gate" used to access the resources on the web server. It is usually omitted if the web server uses the standard ports of the HTTP protocol (80 for HTTP and 443 for HTTPS) to grant access to its resources. Otherwise, it is mandatory. ### Path `/path/to/myfile.html` is the path to the resource on the Web server. In the early days of the Web, a path like this represented a physical file location on the Web server. Nowadays, it is mostly an abstraction handled by Web servers without any physical reality. ### Query `?key1=value1&key2=value2` are extra parameters provided to the Web server. Those parameters are a list of key/value pairs separated with the `&` symbol. The Web server can use those parameters to do extra stuff before returning the resource to the user. Each Web server has its own rules regarding parameters, and the only reliable way to know how a specific Web server is handling parameters is by asking the Web server owner. ### Fragment `#SomewhereInTheDocument` is an anchor to another part of the resource itself. An anchor represents a sort of "bookmark" inside the resource, giving the browser the directions to show the content located at that "bookmarked" spot. On an HTML document, for example, the browser will scroll to the point where the anchor is defined; on a video or audio document, the browser will try to go to the time the anchor represents. It is worth noting that the part after the #, also known as the fragment identifier, is never sent to the server with the request. Usage notes ----------- When using URLs in [HTML](https://developer.mozilla.org/en-US/docs/Glossary/HTML) content, you should generally only use a few of these URL schemes. When referring to subresources — that is, files that are being loaded as part of a larger document — you should only use the HTTP and HTTPS schemes. Increasingly, browsers are removing support for using FTP to load subresources, for security reasons. FTP is still acceptable at the top level (such as typed directly into the browser's URL bar, or the target of a link), although some browsers may delegate loading FTP content to another application. Examples -------- ``` https://developer.mozilla.org/en-US/docs/Learn tel:+1-816-555-1212 [email protected]:mdn/browser-compat-data.git ftp://example.org/resource.txt urn:isbn:9780141036144 mailto:[email protected] ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # uri](https://httpwg.org/specs/rfc9110.html#uri) | See also -------- * [What is a URL?](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL) * [IANA list of URI schemes](https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml) http MIME types: Common types MIME types: Common types ======================== Common MIME types ================= This topic lists most common MIME types, with corresponding document types, ordered by their common extensions. Two primary MIME types are important for the role of default types: * `text/plain` is the default value for textual files. A textual file should be human-readable and must not contain binary data. * `application/octet-stream` is the default value for all other cases. An unknown file type should use this type. Browsers pay a particular care when manipulating these files, to protect users from software vulnerabilities and possible dangerous behavior. IANA is the official registry of MIME media types and maintains a [list of all the official MIME types](https://www.iana.org/assignments/media-types/media-types.xhtml). This table lists important MIME types for the Web: | Extension | Kind of document | MIME Type | | --- | --- | --- | | `.aac` | AAC audio | `audio/aac` | | `.abw` | [AbiWord](https://en.wikipedia.org/wiki/AbiWord) document | `application/x-abiword` | | `.arc` | Archive document (multiple files embedded) | `application/x-freearc` | | `.avif` | AVIF image | `image/avif` | | `.avi` | AVI: Audio Video Interleave | `video/x-msvideo` | | `.azw` | Amazon Kindle eBook format | `application/vnd.amazon.ebook` | | `.bin` | Any kind of binary data | `application/octet-stream` | | `.bmp` | Windows OS/2 Bitmap Graphics | `image/bmp` | | `.bz` | BZip archive | `application/x-bzip` | | `.bz2` | BZip2 archive | `application/x-bzip2` | | `.cda` | CD audio | `application/x-cdf` | | `.csh` | C-Shell script | `application/x-csh` | | `.css` | Cascading Style Sheets (CSS) | `text/css` | | `.csv` | Comma-separated values (CSV) | `text/csv` | | `.doc` | Microsoft Word | `application/msword` | | `.docx` | Microsoft Word (OpenXML) | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` | | `.eot` | MS Embedded OpenType fonts | `application/vnd.ms-fontobject` | | `.epub` | Electronic publication (EPUB) | `application/epub+zip` | | `.gz` | GZip Compressed Archive | `application/gzip` | | `.gif` | Graphics Interchange Format (GIF) | `image/gif` | | `.htm .html` | HyperText Markup Language (HTML) | `text/html` | | `.ico` | Icon format | `image/vnd.microsoft.icon` | | `.ics` | iCalendar format | `text/calendar` | | `.jar` | Java Archive (JAR) | `application/java-archive` | | `.jpeg` `.jpg` | JPEG images | `image/jpeg` | | `.js` | JavaScript | `text/javascript` (Specifications: [HTML](https://html.spec.whatwg.org/multipage/#scriptingLanguages) and [RFC 9239](https://www.rfc-editor.org/rfc/rfc9239)) | | `.json` | JSON format | `application/json` | | `.jsonld` | JSON-LD format | `application/ld+json` | | `.mid` `.midi` | Musical Instrument Digital Interface (MIDI) | `audio/midi` `audio/x-midi` | | `.mjs` | JavaScript module | `text/javascript` | | `.mp3` | MP3 audio | `audio/mpeg` | | `.mp4` | MP4 video | `video/mp4` | | `.mpeg` | MPEG Video | `video/mpeg` | | `.mpkg` | Apple Installer Package | `application/vnd.apple.installer+xml` | | `.odp` | OpenDocument presentation document | `application/vnd.oasis.opendocument.presentation` | | `.ods` | OpenDocument spreadsheet document | `application/vnd.oasis.opendocument.spreadsheet` | | `.odt` | OpenDocument text document | `application/vnd.oasis.opendocument.text` | | `.oga` | OGG audio | `audio/ogg` | | `.ogv` | OGG video | `video/ogg` | | `.ogx` | OGG | `application/ogg` | | `.opus` | Opus audio | `audio/opus` | | `.otf` | OpenType font | `font/otf` | | `.png` | Portable Network Graphics | `image/png` | | `.pdf` | Adobe [Portable Document Format](https://www.adobe.com/acrobat/about-adobe-pdf.html) (PDF) | `application/pdf` | | `.php` | Hypertext Preprocessor (**Personal Home Page**) | `application/x-httpd-php` | | `.ppt` | Microsoft PowerPoint | `application/vnd.ms-powerpoint` | | `.pptx` | Microsoft PowerPoint (OpenXML) | `application/vnd.openxmlformats-officedocument.presentationml.presentation` | | `.rar` | RAR archive | `application/vnd.rar` | | `.rtf` | Rich Text Format (RTF) | `application/rtf` | | `.sh` | Bourne shell script | `application/x-sh` | | `.svg` | Scalable Vector Graphics (SVG) | `image/svg+xml` | | `.tar` | Tape Archive (TAR) | `application/x-tar` | | `.tif .tiff` | Tagged Image File Format (TIFF) | `image/tiff` | | `.ts` | MPEG transport stream | `video/mp2t` | | `.ttf` | TrueType Font | `font/ttf` | | `.txt` | Text, (generally ASCII or ISO 8859-*n*) | `text/plain` | | `.vsd` | Microsoft Visio | `application/vnd.visio` | | `.wav` | Waveform Audio Format | `audio/wav` | | `.weba` | WEBM audio | `audio/webm` | | `.webm` | WEBM video | `video/webm` | | `.webp` | WEBP image | `image/webp` | | `.woff` | Web Open Font Format (WOFF) | `font/woff` | | `.woff2` | Web Open Font Format (WOFF) | `font/woff2` | | `.xhtml` | XHTML | `application/xhtml+xml` | | `.xls` | Microsoft Excel | `application/vnd.ms-excel` | | `.xlsx` | Microsoft Excel (OpenXML) | `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` | | `.xml` | XML | `application/xml` is recommended as of [RFC 7303](https://datatracker.ietf.org/doc/html/rfc7303#section-4.1) (section 4.1), but `text/xml` is still used sometimes. You can assign a specific MIME type to a file with `.xml` extension depending on how its contents are meant to be interpreted. For instance, an Atom feed is `application/atom+xml`, but `application/xml` serves as a valid default. | | `.xul` | XUL | `application/vnd.mozilla.xul+xml` | | `.zip` | ZIP archive | `application/zip` | | `.3gp` | [3GPP](https://en.wikipedia.org/wiki/3GP_and_3G2) audio/video container | `video/3gpp`; `audio/3gpp` if it doesn't contain video | | `.3g2` | [3GPP2](https://en.wikipedia.org/wiki/3GP_and_3G2) audio/video container | `video/3gpp2`; `audio/3gpp2` if it doesn't contain video | | `.7z` | [7-zip](https://en.wikipedia.org/wiki/7-Zip) archive | `application/x-7z-compressed` | http Access-Control-Max-Age Access-Control-Max-Age ====================== Access-Control-Max-Age ====================== The `Access-Control-Max-Age` response header indicates how long the results of a [preflight request](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request) (that is the information contained in the [`Access-Control-Allow-Methods`](access-control-allow-methods) and [`Access-Control-Allow-Headers`](access-control-allow-headers) headers) can be cached. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Access-Control-Max-Age: <delta-seconds> ``` Directives ---------- <delta-seconds> Maximum number of seconds the results can be cached, as an unsigned non-negative integer. Firefox [caps this at 24 hours](https://searchfox.org/mozilla-central/source/netwerk/protocol/http/nsCORSListenerProxy.cpp#1118) (86400 seconds). Chromium (prior to v76) [caps at 10 minutes](https://source.chromium.org/chromium/chromium/src/+/main:services/network/public/cpp/cors/preflight_result.cc;drc=52002151773d8cd9ffc5f557cd7cc880fddcae3e;l=36) (600 seconds). Chromium (starting in v76) [caps at 2 hours](https://source.chromium.org/chromium/chromium/src/+/main:services/network/public/cpp/cors/preflight_result.cc;drc=49e7c0b4886cac1f3d09dc046bd528c9c811a0fa;l=31) (7200 seconds). The default value is 5 seconds. Examples -------- Cache results of a preflight request for 10 minutes: ``` Access-Control-Max-Age: 600 ``` Specifications -------------- | Specification | | --- | | [Fetch Standard # http-access-control-max-age](https://fetch.spec.whatwg.org/#http-access-control-max-age) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Access-Control-Max-Age` | 4 | 12 | 3.5 | 10 | 12 | 4 | 2 | Yes | 4 | 12 | 3.2 | Yes | See also -------- * [`Access-Control-Allow-Headers`](access-control-allow-headers) * [`Access-Control-Allow-Methods`](access-control-allow-methods)
programming_docs
http Cross-Origin-Resource-Policy Cross-Origin-Resource-Policy ============================ Cross-Origin-Resource-Policy ============================ The HTTP `Cross-Origin-Resource-Policy` response header conveys a desire that the browser blocks no-cors cross-origin/cross-site requests to the given resource. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Cross-Origin-Resource-Policy: same-site | same-origin | cross-origin ``` Examples -------- The response header below will cause compatible user agents to disallow cross-origin no-cors requests: ``` Cross-Origin-Resource-Policy: same-origin ``` For more examples, see <https://resourcepolicy.fyi/>. Specifications -------------- | Specification | | --- | | [Fetch Standard # cross-origin-resource-policy-header](https://fetch.spec.whatwg.org/#cross-origin-resource-policy-header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Cross-Origin-Resource-Policy` | 73 ["Until version 75, downloads for files with this header would fail in Chrome. See [bug 952834](https://crbug.com/952834).", "From version 80 to 85, linearized PDFs served inline with this header fail to render properly. See [bug 1074261](https://crbug.com/1074261). From version 86, partial PDF loading is disabled."] | 79 | 74 | No | No | 12 | 73 ["Until version 75, downloads for files with this header would fail in Chrome. See [bug 952834](https://crbug.com/952834).", "From version 80 to 85, linearized PDFs served inline with this header fail to render properly. See [bug 1074261](https://crbug.com/1074261). From version 86, partial PDF loading is disabled."] | 73 ["Until version 75, downloads for files with this header would fail in Chrome. See [bug 952834](https://crbug.com/952834).", "From version 80 to 85, linearized PDFs served inline with this header fail to render properly. See [bug 1074261](https://crbug.com/1074261). From version 86, partial PDF loading is disabled."] | No | No | 12 | 11.0 | See also -------- * [Cross-Origin Resource Policy (CORP) explainer](../cross-origin_resource_policy_(corp)) * [Consider deploying Cross-Origin Resource Policy](https://resourcepolicy.fyi/) * [`Access-Control-Allow-Origin`](access-control-allow-origin) http If-Unmodified-Since If-Unmodified-Since =================== If-Unmodified-Since =================== The HyperText Transfer Protocol (HTTP) `If-Unmodified-Since` request header makes the request for the resource conditional: the server will send the requested resource or accept it in the case of a [`POST`](../methods/post) or another non-[safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) method only if the resource has not been modified after the date specified by this HTTP header. If the resource has been modified after the specified date, the response will be a [`412 Precondition Failed`](../status/412) error. The `If-Unmodified-Since` HTTP header is commonly used in the following situations: * In conjunction with non-[safe](https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP) methods, like [`POST`](../methods/post), this header can be used to implement an [optimistic concurrency control](https://en.wikipedia.org/wiki/Optimistic_concurrency_control), as is done by some wikis: editions are rejected if the stored document has been modified since the original was retrieved. * In conjunction with a range request using the [`Range`](range) header, this header can be used to ensure that the new fragment requested comes from an unmodified document. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` If-Unmodified-Since: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT ``` Directives ---------- <day-name> A 3-letter description of the day of the week. One of "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", or "Sun" (case-sensitive). <day> A 2-digit day number of the month. Examples: "04", "23". <month> A 3-letter description of the month. One of "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" (case-sensitive). <year> A 4-digit year number. Examples: "1990", "2016". <hour> A 2-digit hour number based on a 24-hour system. Examples: "09", "23". <minute> A 2-digit minute number. Examples: "04", "59". <second> A 2-digit second number. Examples: "04", "59". `GMT` Greenwich Mean Time. HTTP dates are always expressed in GMT, never in local time. Examples -------- ``` If-Unmodified-Since: Wed, 21 Oct 2015 07:28:00 GMT ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.if-unmodified-since](https://httpwg.org/specs/rfc9110.html#field.if-unmodified-since) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `If-Unmodified-Since` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Last-Modified`](last-modified) * [`If-Modified-Since`](if-modified-since) * [`If-Match`](if-match) * [`If-None-Match`](if-none-match) * [`Range`](range) * [`412 Precondition Failed`](../status/412) http Proxy-Authenticate Proxy-Authenticate ================== Proxy-Authenticate ================== The HTTP `Proxy-Authenticate` response header defines the authentication method that should be used to gain access to a resource behind a [proxy server](https://developer.mozilla.org/en-US/docs/Glossary/Proxy_server). It authenticates the request to the proxy server, allowing it to transmit the request further. The `Proxy-Authenticate` header is sent along with a [`407`](../status/407) `Proxy Authentication Required`. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Proxy-Authenticate: <type> realm=<realm> ``` Directives ---------- <type> [Authentication type](../authentication#authentication_schemes). A common type is ["Basic"](../authentication#basic_authentication_scheme). IANA maintains a [list of authentication schemes](https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml). realm=<realm> A description of the protected area, the realm. If no realm is specified, clients often display a formatted host name instead. Examples -------- ``` Proxy-Authenticate: Basic Proxy-Authenticate: Basic realm="Access to the internal site" ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.proxy-authenticate](https://httpwg.org/specs/rfc9110.html#field.proxy-authenticate) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Proxy-Authenticate` | 1 | ≤79 | 1 | No | Yes | No | 37 | Yes | Yes | Yes | No | Yes | See also -------- * [HTTP authentication](../authentication) * [`Authorization`](authorization) * [`Proxy-Authorization`](proxy-authorization) * [`WWW-Authenticate`](www-authenticate) * [`401`](../status/401), [`403`](../status/403), [`407`](../status/407) http Max-Forwards Max-Forwards ============ Max-Forwards ============ The `Max-Forwards` request HTTP header is used with the [`TRACE`](../methods/trace) method to limit the number of nodes (usually proxies) that request goes through. Its value is an integer value indicating the *maximum amount* of nodes it must visit. At each node, the value is decremented and the `TRACE` request is forwarded to the next node, until the destination is reached, or the received value of `Max-Forwards` is zero. The request is then sent back, except for some headers, as the body of a `200 OK` response. If the `Max-Forwards` header is not present in a `TRACE` request, a node will assume that there is no maximum number of forwards. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Max-Forwards: <integer> ``` Examples -------- ``` Max-Forwards: 0 Max-Forwards: 10 ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.max-forwards](https://httpwg.org/specs/rfc9110.html#field.max-forwards) | Browser compatibility --------------------- See also -------- * The HTTP [`TRACE`](../methods/trace) method http X-Forwarded-For X-Forwarded-For =============== X-Forwarded-For =============== The `X-Forwarded-For` (XFF) request header is a de-facto standard header for identifying the originating IP address of a client connecting to a web server through a proxy server. **Warning:** Improper use of this header can be a security risk. For details, see the [Security and privacy concerns](#security_and_privacy_concerns) section. When a client connects directly to a server, the client's IP address is sent to the server (and is often written to server access logs). But if a client connection passes through any [forward or reverse](https://en.wikipedia.org/wiki/Proxy_server) proxies, the server only sees the final proxy's IP address, which is often of little use. That's especially true if the final proxy is a load balancer which is part of the same installation as the server. So, to provide a more-useful client IP address to the server, the `X-Forwarded-For` request header is used. For detailed guidance on using this header, see the [Parsing](#parsing) and [Selecting an IP address](#selecting_an_ip_address) sections. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | A standardized version of this header is the HTTP [`Forwarded`](forwarded) header. Security and privacy concerns ----------------------------- This header, by design, exposes privacy-sensitive information, such as the IP address of the client. Therefore the user's privacy must be kept in mind when deploying this header. The `X-Forwarded-For` header is untrustworthy when no trusted reverse proxy (e.g., a load balancer) is between the client and server. If the client and all proxies are benign and well-behaved, then the list of IP addresses in the header has the meaning described in the [Directives](#directives) section. But if there's a risk the client or any proxy is malicious or misconfigured, then it's possible any part (or the entirety) of the header may have been spoofed (and may not be a list or contain IP addresses at all). If any trusted reverse proxies are between the client and server, the final `X-Forwarded-For` IP addresses (one for each trusted proxy) are trustworthy, as they were added by trusted proxies. (That's true as long as the server is *only* accessible through those proxies and not also directly). Any security-related use of `X-Forwarded-For` (such as for rate limiting or IP-based access control) *must only* use IP addresses added by a trusted proxy. Using untrustworthy values can result in rate-limiter avoidance, access-control bypass, memory exhaustion, or other negative security or availability consequences. Conversely, leftmost (untrusted) values must only be used where there will be no negative impact from the possibility of using spoofed values. Syntax ------ ``` X-Forwarded-For: <client>, <proxy1>, <proxy2> ``` Elements are comma-separated, with optional whitespace surrounding the commas. Directives ---------- <client> The client IP address <proxy1>, <proxy2> If a request goes through multiple proxies, the IP addresses of each successive proxy is listed. This means that, given well-behaved client and proxies, the rightmost IP address is the IP address of the most recent proxy and the leftmost IP address is the IP address of the originating client. Examples -------- ``` X-Forwarded-For: 2001:db8:85a3:8d3:1319:8a2e:370:7348 X-Forwarded-For: 203.0.113.195 X-Forwarded-For: 203.0.113.195, 2001:db8:85a3:8d3:1319:8a2e:370:7348 X-Forwarded-For: 203.0.113.195,2001:db8:85a3:8d3:1319:8a2e:370:7348,150.172.238.178 ``` Parsing ------- Improper parsing of the `X-Forwarded-For` header can result in spoofed values being used for security-related purposes, resulting in the negative consequences mentioned above. There may be multiple `X-Forwarded-For` headers present in a request (per [RFC 2616](https://datatracker.ietf.org/doc/html/rfc2616#section-4.2)). The IP addresses in these headers must be treated as a single list, starting with the first IP address of the first header and continuing to the last IP address of the last header. There are two ways of making this single list: * join the `X-Forwarded-For` full header values with commas and then split by comma into a list, or * split each `X-Forwarded-For` header by comma into lists and then join the lists It is insufficient to use only one of multiple `X-Forwarded-For` headers. (Some reverse proxies will automatically join multiple `X-Forwarded-For` headers into one, but it is safest to not assume that this is the case.) Selecting an IP address ----------------------- When selecting an address, the full list of IPs — from all `X-Forwarded-For` headers — must be used. When choosing the `X-Forwarded-For` client IP address closest to the client (untrustworthy and *not* for security-related purposes), the first IP from the leftmost that is *a valid address* and *not private/internal* should be selected. ("Valid" because spoofed values may not be IP addresses at all; "not internal/private" because clients may have used proxies on their internal network, which may have added addresses from the [private IP space](https://en.wikipedia.org/wiki/Private_network).) When choosing the first *trustworthy* `X-Forwarded-For` client IP address, additional configuration is required. There are two common methods: * **Trusted proxy count**: The count of reverse proxies between the internet and the server is configured. The `X-Forwarded-For` IP list is searched from the rightmost by that count minus one. (For example, if there is only one reverse proxy, that proxy will add the client's IP address, so the rightmost address should be used. If there are three reverse proxies, the last two IP addresses will be internal.) * **Trusted proxy list**: The IPs or IP ranges of the trusted reverse proxies are configured. The `X-Forwarded-For` IP list is searched from the rightmost, skipping all addresses that are on the trusted proxy list. The first non-matching address is the target address. The first trustworthy `X-Forwarded-For` IP address may belong to an untrusted intermediate proxy rather than the actual client computer, but it is the only IP suitable for security uses. Note that if the server is directly connectable from the internet — even if it is also behind a trusted reverse proxy — *no part* of the `X-Forwarded-For` IP list can be considered trustworthy or safe for security-related uses. Specifications -------------- Not part of any current specification. The standardized version of this header is [`Forwarded`](forwarded). See also -------- * [`Forwarded`](forwarded) * [`X-Forwarded-Host`](x-forwarded-host) * [`X-Forwarded-Proto`](x-forwarded-proto) * [`Via`](via) http Viewport-Width Viewport-Width ============== Viewport-Width ============== **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). **Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The `Viewport-Width` [device client hint](../client_hints) request header provides the client's layout viewport width in [CSS pixels](https://developer.mozilla.org/en-US/docs/Glossary/CSS_pixel). The value is rounded up to the smallest following integer (i.e. ceiling value). | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | The hint can be used with other screen-specific hints to deliver images optimized for a specific screen size, or to omit resources that are not needed for a particular screen width. If the `Viewport-Width` header appears more than once in a message the last occurrence is used. **Note:** * Client Hints are accessible only on secure origins (via TLS). * A server has to opt in to receive the `Viewport-Width` header from the client, by sending the [`Accept-CH`](accept-ch) response header. * Servers that opt in to the `Viewport-Width` client hint will typically also specify it in the [`Vary`](vary) header. This informs caches that the server may send different responses based on the header value in a request. * `Viewport-Width` was removed from the original client hints specification in [draft-ietf-httpbis-client-hints-07](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-client-hints-07). The proposed replacement is [`Sec-CH-Viewport-Width`](https://wicg.github.io/responsive-image-client-hints/#sec-ch-viewport-width) (Responsive Image Client Hints). Syntax ------ ``` Viewport-Width: <number> ``` Directives ---------- <number> The width of the user's viewport in [CSS pixels](https://developer.mozilla.org/en-US/docs/Glossary/CSS_pixel), rounded up to the nearest integer. Examples -------- A server must first opt in to receive the `Viewport-Width` header by sending the response header [`Accept-CH`](accept-ch) containing the directive `Viewport-Width`. ``` Accept-CH: Viewport-Width ``` Then on subsequent requests the client might send `Viewport-Width` header back: ``` Viewport-Width: 320 ``` Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Viewport-Width` | 46 | ≤79 | No | No | 33 | No | 46 | 46 | No | 33 | No | 5.0 | See also -------- * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * Device client hints + [`Content-DPR`](content-dpr) + [`Device-Memory`](device-memory) + [`DPR`](dpr) + [`Width`](width) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary)
programming_docs
http Accept-Post Accept-Post =========== Accept-Post =========== The `Accept-Post` response HTTP header advertises which [media types](../basics_of_http/mime_types) are accepted by the server for HTTP post requests. `Accept-Post` in response to any method means that `POST` is allowed on the requested resource (any document/media format in the header further indicates that the document format is allowed). For example, a server receiving a `POST` request with an unsupported media type could reply with [`415`](../status/415) `Unsupported Media Type` and an `Accept-Post` header referencing one or more supported media types. **Note:** An IANA registry maintains [a complete list of official content encodings](https://www.iana.org/assignments/http-parameters/http-parameters.xml#http-parameters-1). | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Accept-Post: <MIME\_type>/<MIME\_subtype> Accept-Post: <MIME\_type>/\* Accept-Post: \*/\* ``` **Note:** The `Accept-Post` header specifies a media range in the same way as [`Accept`](accept), except that it has no notion of preference (i.e., no `q` arguments). This is because `Accept-Post` is a response header while `Accept` is a request header. Directives ---------- None. Examples -------- ``` Accept-Post: application/example, text/example Accept-Post: image/webp Accept-Post: \*/\* ``` Specifications -------------- | Specification | | --- | | [Linked Data Platform # header-accept-post](https://www.w3.org/TR/ldp/#header-accept-post) | Browser compatibility --------------------- See also -------- * Http method [`POST`](../methods/post) * HTTP Semantic and context [RFC 7231, section 4.3.3: POST](https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.3) http Content-Type Content-Type ============ Content-Type ============ The `Content-Type` representation header is used to indicate the original [media type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) of the resource (prior to any content encoding applied for sending). In responses, a `Content-Type` header provides the client with the actual content type of the returned content. This header's value may be ignored, for example when browsers perform MIME sniffing; set the [`X-Content-Type-Options`](x-content-type-options) header value to `nosniff` to prevent this behavior. In requests, (such as [`POST`](../methods/post) or [`PUT`](../methods/put)), the client tells the server what type of data is actually sent. | | | | --- | --- | | Header type | [Representation header](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [CORS-safelisted response header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header) | yes | | [CORS-safelisted request header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header) | yes, with the additional restriction that values can't contain a *CORS-unsafe request header byte*: 0x00-0x1F (except 0x09 (HT)), `"():<>?@[\]{}`, and 0x7F (DEL).It also needs to have a MIME type of its parsed value (ignoring parameters) of either `application/x-www-form-urlencoded`, `multipart/form-data`, or `text/plain`. | Syntax ------ ``` Content-Type: text/html; charset=utf-8 Content-Type: multipart/form-data; boundary=something ``` Directives ---------- `media-type` The [MIME type](../basics_of_http/mime_types) of the resource or the data. charset The character encoding standard. Case insensitive, lowercase is preferred. boundary For multipart entities the `boundary` directive is required. The directive consists of 1 to 70 characters from a set of characters (and not ending with white space) known to be very robust through email gateways. It is used to encapsulate the boundaries of the multiple parts of the message. Often, the header boundary is prepended with two dashes and the final boundary has two dashes appended at the end. Examples -------- ### `Content-Type` in HTML forms In a [`POST`](../methods/post) request, resulting from an HTML form submission, the `Content-Type` of the request is specified by the `enctype` attribute on the [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) element. ``` <form action="/" method="post" enctype="multipart/form-data"> <input type="text" name="description" value="some text" /> <input type="file" name="myFile" /> <button type="submit">Submit</button> </form> ``` The request looks something like this (less interesting headers are omitted here): ``` POST /foo HTTP/1.1 Content-Length: 68137 Content-Type: multipart/form-data; boundary=---------------------------974767299852498929531610575 -----------------------------974767299852498929531610575 Content-Disposition: form-data; name="description" some text -----------------------------974767299852498929531610575 Content-Disposition: form-data; name="myFile"; filename="foo.txt" Content-Type: text/plain (content of the uploaded file foo.txt) -----------------------------974767299852498929531610575-- ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # status.206](https://httpwg.org/specs/rfc9110.html#status.206) | | [HTTP Semantics # field.content-type](https://httpwg.org/specs/rfc9110.html#field.content-type) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Content-Type` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Accept`](accept) * [`Content-Disposition`](content-disposition) * [`206`](../status/206) Partial Content * [`X-Content-Type-Options`](x-content-type-options) http Link Link ==== Link ==== The HTTP `Link` entity-header field provides a means for serializing one or more links in HTTP headers. It is semantically equivalent to the HTML [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) element. Syntax ------ ``` Link: <uri-reference>; param1=value1; param2="value2" ``` `<uri-reference>` The URI reference, must be enclosed between `<` and `>` and [percent encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). ### Parameters The link header contains parameters, which are separated with `;` and are equivalent to attributes of the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) element. Examples -------- The URI (absolute or relative) must be enclosed between `<` and `>`: ``` Link: <https://example.com>; rel="preconnect" ``` ``` Link: https://bad.example; rel="preconnect" ``` ### Encoding URLs The URI (absolute or relative) must encode char codes greater than 255: ``` Link: <https://example.com/%E8%8B%97%E6%9D%A1>; rel="preconnect" ``` ``` Link: <https://example.com/苗条>; rel="preconnect" ``` ### Specifying multiple links You can specify multiple links separated by commas, for example: ``` Link: <https://one.example.com>; rel="preconnect", <https://two.example.com>; rel="preconnect", <https://three.example.com>; rel="preconnect" ``` Specifications -------------- **No specification found**No specification data found for `http.headers.Link`. [Check for problems with this page](#on-github) or contribute a missing `spec_url` to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). Also make sure the specification is included in [w3c/browser-specs](https://github.com/w3c/browser-specs). Browser compatibility --------------------- No compatibility data found for `http.headers.Link`. [Check for problems with this page](#on-github) or contribute missing data to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). See also -------- * [`103 Early Hints`](../status/103) * [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) http Sec-CH-UA-Arch Sec-CH-UA-Arch ============== Sec-CH-UA-Arch ============== **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). The `Sec-CH-UA-Arch` [user agent client hint](../client_hints#user-agent_client_hints) request header provides the user-agent's underlying CPU architecture, such as ARM or x86. This might be used by a server, for example, to select and offer the correct binary format of an executable for a user to download. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Sec-CH-UA-Arch: <arch> ``` ### Directives `<arch>` A string indicating the underlying platform architecture, such as: `"x86"`, `"ARM"`, `"[arm64-v8a, armeabi-v7a, armeabi]"`. Examples -------- A server requests the `Sec-CH-UA-Arch` header by including the [`Accept-CH`](accept-ch) in a response to some request from the client, using the name of the desired header as a token: ``` HTTP/1.1 200 OK Accept-CH: Sec-CH-UA-Arch ``` The client may choose to provide the hint, and add the `Sec-CH-UA-Arch` header to subsequent requests. For example, on a Windows X86 based computer, the client might add the header as shown: ``` GET /GET /my/page HTTP/1.1 Host: example.site Sec-CH-UA: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96" Sec-CH-UA-Mobile: ?0 Sec-CH-UA-Platform: "Windows" Sec-CH-UA-Arch: "x86" ``` Note above that the [low entropy headers](../client_hints#low_entropy_hints) are added to the request even though not specified in the server response. Specifications -------------- | Specification | | --- | | [User-Agent Client Hints # sec-ch-ua-arch](https://wicg.github.io/ua-client-hints/#sec-ch-ua-arch) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Sec-CH-UA-Arch` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | See also -------- * [Client hints](../client_hints) * [User-Agent Client Hints API](https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API) * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) http Accept-CH-Lifetime Accept-CH-Lifetime ================== Accept-CH-Lifetime ================== **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. **Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. **Warning:** The header was removed from the specification in [draft 8](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-client-hints-08). The `Accept-CH-Lifetime` header is set by the server to specify the persistence of the [client hint headers](../client_hints) it specified using [`Accept-CH`](accept-ch), that the client should include in subsequent requests. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [CORS-safelisted response header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header) | no | **Note:** Client Hints are accessible only on secure origins (via TLS). [`Accept-CH`](accept-ch) and [`Accept-CH-Lifetime`](accept-ch-lifetime) headers should be persisted for all secure requests to ensure Client Hints are sent reliably. Syntax ------ ``` Accept-CH-Lifetime: <age> ``` Examples -------- ``` Accept-CH: Viewport-Width Accept-CH-Lifetime: 86400 ``` Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Accept-CH-Lifetime` | 67 | ≤79 | No | No | 54 | No | 67 | 67 | No | No | No | 9.0 | See also -------- * [`Accept-CH`](accept-ch) * [`Vary`](vary) http Content-Language Content-Language ================ Content-Language ================ The `Content-Language` [representation header](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header) is used to **describe the language(s) intended for the audience**, so users can differentiate it according to their own preferred language. For example, if "`Content-Language: de-DE`" is set, it says that the document is intended for German language speakers (however, it doesn't indicate the document is written in German. For example, it might be written in English as part of a language course for German speakers. If you want to indicate which language the document is written in, use the [`lang` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang) instead). If no `Content-Language` is specified, the default is that the content is intended for all language audiences. Multiple language tags are also possible, as well as applying the `Content-Language` header to various media types and not only to textual documents. | | | | --- | --- | | Header type | [Representation header](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [CORS-safelisted response header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header) | yes | | [CORS-safelisted request header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header) | yes, with the additional restriction that values can only be `0-9`, `A-Z`, `a-z`, space or `*,-.;=`. | Syntax ------ ``` Content-Language: de-DE Content-Language: en-US Content-Language: de-DE, en-CA ``` Directives ---------- `language-tag` Multiple language tags are separated by a comma. Each language tag is a sequence of one or more case-insensitive subtags, each separated by a hyphen character ("`-`", `%x2D`). In most cases, a language tag consists of a primary language subtag that identifies a broad family of related languages (e.g., "`en`" = English) and is optionally followed by a series of subtags that refine or narrow that language's range (e.g., "`en-CA`" = the variety of English as communicated in Canada). **Note:** Language tags are formally defined in [RFC 5646](https://datatracker.ietf.org/doc/html/rfc5646), which rely on the [ISO 639](https://en.wikipedia.org/wiki/ISO_639) standard (quite often the [ISO 639-1 code list](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)) for [language codes](https://en.wikipedia.org/wiki/Language_code) to be used. Examples -------- ### Indicating the language a document is written in The global [`lang`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang) attribute is used on HTML elements to indicate the language of an entire [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML) document or parts of it. ``` <html lang="de">…</html> ``` Do **not** use this meta element like this for stating a document language: ``` <!-- /!\ This is bad practice --> <meta http-equiv="content-language" content="de" /> ``` ### Indicating a target audience for a resource The `Content-Language` header is used to specify the **page's intended audience** and can indicate that this is more than one language. ``` Content-Language: de, en ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.content-language](https://httpwg.org/specs/rfc9110.html#field.content-language) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Content-Language` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Accept-Language`](accept-language) * [HTTP headers, meta elements and language information](https://www.w3.org/International/questions/qa-http-and-lang.en) * [HTML `lang` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang) http Content-Encoding Content-Encoding ================ Content-Encoding ================ The `Content-Encoding` [representation header](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header) lists any encodings that have been applied to the representation (message payload), and in what order. This lets the recipient know how to decode the representation in order to obtain the original payload format. Content encoding is mainly used to compress the message data without losing information about the origin media type. Note that the original media/content type is specified in the [`Content-Type`](content-type) header, and that the `Content-Encoding` applies to the representation, or "coded form", of the data. If the original media is encoded in some way (e.g. a zip file) then this information would not be included in the `Content-Encoding` header. Servers are encouraged to compress data as much as possible, and should use content encoding where appropriate. Compressing a compressed media type such as a zip or jpeg may not be appropriate, as this can make the payload larger. | | | | --- | --- | | Header type | [Representation header](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Content-Encoding: gzip Content-Encoding: compress Content-Encoding: deflate Content-Encoding: br // Multiple, in the order in which they were applied Content-Encoding: deflate, gzip ``` Directives ---------- `gzip` A format using the [Lempel-Ziv coding](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ77) (LZ77), with a 32-bit CRC. This is the original format of the UNIX *gzip* program. The HTTP/1.1 standard also recommends that the servers supporting this content-encoding should recognize `x-gzip` as an alias, for compatibility purposes. `compress` A format using the [Lempel-Ziv-Welch](https://en.wikipedia.org/wiki/LZW) (LZW) algorithm. The value name was taken from the UNIX *compress* program, which implemented this algorithm. Like the compress program, which has disappeared from most UNIX distributions, this content-encoding is not used by many browsers today, partly because of a patent issue (it expired in 2003). `deflate` Using the [zlib](https://en.wikipedia.org/wiki/Zlib) structure (defined in [RFC 1950](https://datatracker.ietf.org/doc/html/rfc1950)) with the [deflate](https://en.wikipedia.org/wiki/Deflate) compression algorithm (defined in [RFC 1951](https://datatracker.ietf.org/doc/html/rfc1951)). `br` Non-standard A format using the [Brotli](https://en.wikipedia.org/wiki/Brotli) algorithm. Examples -------- ### Compressing with gzip On the client side, you can advertise a list of compression schemes that will be sent along in an HTTP request. The [`Accept-Encoding`](accept-encoding) header is used for negotiating content encoding. ``` Accept-Encoding: gzip, deflate ``` The server responds with the scheme used, indicated by the `Content-Encoding` response header. ``` Content-Encoding: gzip ``` Note that the server is not obligated to use any compression method. Compression highly depends on server settings and used server modules. Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.content-encoding](https://httpwg.org/specs/rfc9110.html#field.content-encoding) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Content-Encoding` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `br` | 50 | 15 | 44 | No | 36 | 11 Unsupported before macOS 10.13 High Sierra. | 51 | 51 | 44 | No | No | 5.0 | See also -------- * [`Accept-Encoding`](accept-encoding) * [`Transfer-Encoding`](transfer-encoding)
programming_docs
http Warning Warning ======= Warning ======= **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. The `Warning` HTTP header contains information about possible problems with the status of the message. More than one `Warning` header may appear in a response. `Warning` header fields can, in general, be applied to any message. However, some warn-codes are specific to caches and can only be applied to response messages. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Warning: <warn-code> <warn-agent> <warn-text> [<warn-date>] ``` Directives ---------- <warn-code> A three-digit warning number. The first digit indicates whether the `Warning` is required to be deleted from a stored response after validation. * `1xx` warn-codes describe the freshness or validation status of the response and will be deleted by a cache after deletion. * `2xx` warn-codes describe some aspect of the representation that is not rectified by a validation and will not be deleted by a cache after validation unless a full response is sent. <warn-agent> The name or pseudonym of the server or software adding the `Warning` header (might be "-" when the agent is unknown). <warn-text> An advisory text describing the error. <warn-date> A date. This is optional. If more than one `Warning` header is sent, include a date that matches the [`Date`](date) header. Warning codes ------------- The [HTTP Warn Codes registry at iana.org](https://www.iana.org/assignments/http-warn-codes/http-warn-codes.xhtml) defines the namespace for warning codes. | Code | Text | Description | | --- | --- | --- | | 110 | Response is Stale | The response provided by a cache is stale (the expiration time set for the response has passed). | | 111 | Revalidation Failed | An attempt to validate the stale response failed due to an inability to reach the server. | | 112 | Disconnected Operation | The cache is intentionally disconnected from the rest of the network. | | 113 | Heuristic Expiration | A cache heuristically chose a [freshness lifetime](../caching#freshness_lifetime) greater than 24 hours and the age of the response is greater than 24 hours. | | 199 | Miscellaneous Warning | Arbitrary information that should be presented to a user or logged. | | 214 | Transformation Applied | Added by a proxy if it applies any transformation to the representation, such as changing the content-coding, media-type or the like. | | 299 | Miscellaneous Persistent Warning | Arbitrary information that should be presented to a user or logged. This warn-code is similar to the warn-code 199 and additionally indicates a persistent warning. | Examples -------- ``` Warning: 110 anderson/1.3.37 "Response is stale" Date: Wed, 21 Oct 2015 07:28:00 GMT Warning: 112 - "cache down" "Wed, 21 Oct 2015 07:28:00 GMT" ``` Specifications -------------- | Specification | | --- | | [HTTP Caching # field.warning](https://httpwg.org/specs/rfc9111.html#field.warning) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Warning` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Date`](date) * [HTTP response status codes](../status) http Clear-Site-Data Clear-Site-Data =============== Clear-Site-Data =============== **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). The `Clear-Site-Data` header clears browsing data (cookies, storage, cache) associated with the requesting website. It allows web developers to have more control over the data stored by a client browser for their origins. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ The `Clear-Site-Data` header accepts one or more directives. If all types of data should be cleared, the wildcard directive (`"*"`) can be used. ``` // Single directive Clear-Site-Data: "cache" // Multiple directives (comma separated) Clear-Site-Data: "cache", "cookies" // Wild card Clear-Site-Data: "\*" ``` Directives ---------- **Note:** All directives must comply with the [quoted-string grammar](https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6). A directive that does not include the double quotes is invalid. `"cache"` Experimental Indicates that the server wishes to remove locally cached data (the browser cache, see [HTTP caching](../caching)) for the origin of the response URL. Depending on the browser, this might also clear out things like pre-rendered pages, script caches, WebGL shader caches, or address bar suggestions. `"cookies"` Indicates that the server wishes to remove all cookies for the origin of the response URL. HTTP authentication credentials are also cleared out. This affects the entire registered domain, including subdomains. So `https://example.com` as well as `https://stage.example.com`, will have cookies cleared. `"storage"` Indicates that the server wishes to remove all DOM storage for the origin of the response URL. This includes storage mechanisms such as: * localStorage (executes `localStorage.clear`), * sessionStorage (executes `sessionStorage.clear`), * IndexedDB (for each database execute [`IDBFactory.deleteDatabase`](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/deleteDatabase)), * Service worker registrations (for each service worker registration, execute [`ServiceWorkerRegistration.unregister`](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/unregister)), * Web SQL databases (deprecated), * [FileSystem API data](https://developer.mozilla.org/en-US/docs/Web/API/File_and_Directory_Entries_API), * Plugin data (Flash via [`NPP_ClearSiteData`](https://wiki.mozilla.org/NPAPI:ClearSiteData)). `"executionContexts"` Experimental Indicates that the server wishes to reload all browsing contexts for the origin of the response ([`Location.reload`](https://developer.mozilla.org/en-US/docs/Web/API/Location/reload)). `"*"` (wildcard) Indicates that the server wishes to clear all types of data for the origin of the response. If more data types are added in future versions of this header, they will also be covered by it. Examples -------- ### Sign out of a web site If a user signs out of your website or service, you might want to remove locally stored data. To do this, add the `Clear-Site-Data` header to the page that confirms the logging out from the site has been accomplished successfully (`https://example.com/logout`, for example): ``` Clear-Site-Data: "cache", "cookies", "storage", "executionContexts" ``` ### Clearing cookies If this header is delivered with the response at `https://example.com/clear-cookies`, all cookies on the same domain `https://example.com` and any subdomains (like `https://stage.example.com`, etc.), will be cleared out. ``` Clear-Site-Data: "cookies" ``` Specifications -------------- | Specification | | --- | | [Clear Site Data # header](https://w3c.github.io/webappsec-clear-site-data/#header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Clear-Site-Data` | 61 | ≤79 | 63 | No | 48 | No | 61 | 61 | 63 | 45 | No | 8.0 | | `cache` | 61 | ≤79 | 94 63-94 | No | 48 | No | 61 | 61 | 63-94 | 45 | No | 8.0 | | `cookies` | 61 | ≤79 | 63 | No | 48 | No | 61 | 61 | 63 | 45 | No | 8.0 | | `executionContexts` | No See [bug 898503](https://crbug.com/898503). | No See [bug 898503](https://crbug.com/898503). | 63-68 | No | No See [bug 898503](https://crbug.com/898503). | No | No See [bug 898503](https://crbug.com/898503). | No See [bug 898503](https://crbug.com/898503). | 63-68 | No See [bug 898503](https://crbug.com/898503). | No | 8.0 | | `secure_context_required` | 61 | ≤79 | 63 | No | 48 | No | 61 | 61 | 63 | 45 | No | 8.0 | | `storage` | 61 | ≤79 | 63 | No | 48 | No | 61 | 61 | 63 | 45 | No | 8.0 | See also -------- * [`Cache-Control`](cache-control) http Sec-CH-UA-Bitness Sec-CH-UA-Bitness ================= Sec-CH-UA-Bitness ================= **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). The `Sec-CH-UA-Bitness` [user agent client hint](../client_hints#user-agent_client_hints) request header provides the "bitness" of the user-agent's underlying CPU architecture. This is the size in bits of an integer or memory address—typically 64 or 32 bits. This might be used by a server, for example, to select and offer the correct binary format of an executable for a user to download. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Sec-CH-UA-Bitness: <bitness> ``` Directives ---------- `<bitness>` A string indicating the underlying platform architecture bitness, such as: `"64"`, `"32"`. Examples -------- A server requests the `Sec-CH-UA-Bitness` header by including the [`Accept-CH`](accept-ch) in a *response* to any request from the client, using the name of the desired header as a token: ``` HTTP/1.1 200 OK Accept-CH: Sec-CH-UA-Bitness ``` The client may choose to provide the hint, and add the `Sec-CH-UA-Bitness` header to subsequent requests. For example, on a Windows based 64-bit computer, the client might add the header as shown: ``` GET /GET /my/page HTTP/1.1 Host: example.site Sec-CH-UA: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96" Sec-CH-UA-Mobile: ?0 Sec-CH-UA-Platform: "Windows" Sec-CH-UA-Bitness: "64" ``` Specifications -------------- | Specification | | --- | | [User-Agent Client Hints # sec-ch-ua-bitness](https://wicg.github.io/ua-client-hints/#sec-ch-ua-bitness) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Sec-CH-UA-Bitness` | 93 | 93 | No | No | 79 | No | 93 | 93 | No | 66 | No | 17.0 | See also -------- * [Client hints](../client_hints) * [User-Agent Client Hints API](https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API) * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) http Retry-After Retry-After =========== Retry-After =========== The `Retry-After` response HTTP header indicates how long the user agent should wait before making a follow-up request. There are three main cases this header is used: * When sent with a [`503`](../status/503) (Service Unavailable) response, this indicates how long the service is expected to be unavailable. * When sent with a [`429`](../status/429) (Too Many Requests) response, this indicates how long to wait before making a new request. * When sent with a redirect response, such as [`301`](../status/301) (Moved Permanently), this indicates the minimum time that the user agent is asked to wait before issuing the redirected request. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Retry-After: <http-date> Retry-After: <delay-seconds> ``` Directives ---------- <http-date> A date after which to retry. See the [`Date`](date) header for more details on the HTTP date format. <delay-seconds> A non-negative decimal integer indicating the seconds to delay after the response is received. Examples -------- ### Dealing with scheduled downtime Support for the `Retry-After` header on both clients and servers is still inconsistent. However, some crawlers and spiders, like the Googlebot, honor the `Retry-After` header. It is useful to send it along with a [`503`](../status/503) (Service Unavailable) response, so that search engines will keep indexing your site when the downtime is over. ``` Retry-After: Wed, 21 Oct 2015 07:28:00 GMT Retry-After: 120 ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.retry-after](https://httpwg.org/specs/rfc9110.html#field.retry-after) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Retry-After` | No | ≤18 | No See [bug 230260](https://bugzil.la/230260). | No | No | No | No | No | No See [bug 230260](https://bugzil.la/230260). | No | No | No | See also -------- * [Google Webmaster blog: How to deal with planned site downtime](https://webmasters.googleblog.com/2011/01/how-to-deal-with-planned-site-downtime.html) * [`503`](../status/503) (Service Unavailable) * [`301`](../status/301) (Moved Permanently) http User-Agent User-Agent ========== User-Agent ========== The **User-Agent** [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) is a characteristic string that lets servers and network peers identify the application, operating system, vendor, and/or version of the requesting [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent). **Warning:** Please read [Browser detection using the user agent](../browser_detection_using_the_user_agent) for why serving different Web pages or services to different browsers is usually a bad idea. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` User-Agent: <product> / <product-version> <comment> ``` Common format for web browsers: ``` User-Agent: Mozilla/5.0 (<system-information>) <platform> (<platform-details>) <extensions> ``` ### Directives <product> A product identifier — its name or development codename. <product-version> Version number of the product. <comment> Zero or more comments containing more details. For example, sub-product information. Firefox UA string ----------------- For more on Firefox- and Gecko-based user agent strings, see the [Firefox user agent string reference](user-agent/firefox). The UA string of Firefox is broken down into 4 components: ``` Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail Firefox/firefoxversion ``` 1. `Mozilla/5.0` is the general token that says that the browser is Mozilla-compatible. For historical reasons, almost every browser today sends it. 2. ***platform*** describes the native platform that the browser is running on (Windows, Mac, Linux, Android, etc.) and if it is a mobile phone. [Firefox OS](https://developer.mozilla.org/en-US/docs/Glossary/Firefox_OS) phones say `Mobile` — the web is the platform. Note that ***platform*** can consist of multiple "`;`"-separated tokens. See below for further details and examples. 3. **rv:*geckoversion*** indicates the release version of Gecko (such as "*17.0*"). In recent browsers, ***geckoversion*** is the same as ***firefoxversion***. 4. ***Gecko/geckotrail*** indicates that the browser is based on Gecko. (On the desktop, ***geckotrail*** is always the fixed string `20100101`.) 5. ***Firefox/firefoxversion*** indicates that the browser is Firefox and provides the version (such as "*17.0"*). ### Examples ``` Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0 Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0 ``` Chrome UA string ---------------- The Chrome (or Chromium/Blink-based engines) user agent string is similar to Firefox's. For compatibility, it adds strings like `KHTML, like Gecko` and `Safari`. ### Examples ``` Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36 ``` Opera UA string --------------- The Opera browser is also based on the Blink engine, which is why it almost looks the same as the Chrome UA string, but adds `"OPR/<version>"`. ### Examples ``` Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41 ``` Older, Presto-based Opera releases used: ``` Opera/9.80 (Macintosh; Intel Mac OS X; U; en) Presto/2.2.15 Version/10.00 Opera/9.60 (Windows NT 6.0; U; en) Presto/2.1.1 ``` Microsoft Edge UA string ------------------------ The Edge browser is also based on the Blink engine. It adds `"Edg/<version>"`. ### Examples ``` Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.59 ``` Safari UA string ---------------- In this example, the user agent string is mobile Safari's version. It contains the word `"Mobile"`. ### Examples ``` Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Mobile/15E148 Safari/604.1 ``` Internet Explorer UA string --------------------------- ### Examples ``` Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0) ``` Crawler and bot UA strings -------------------------- ### Examples ``` Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) ``` ``` Mozilla/5.0 (compatible; YandexAccessibilityBot/3.0; +http://yandex.com/bots) ``` Library and net tool UA strings ------------------------------- ### Examples ``` curl/7.64.1 ``` ``` PostmanRuntime/7.26.5 ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.user-agent](https://httpwg.org/specs/rfc9110.html#field.user-agent) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `User-Agent` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [User-Agent detection, history and checklist](https://hacks.mozilla.org/2013/09/user-agent-detection-history-and-checklist/) * [Firefox user agent string reference](user-agent/firefox) * [Browser detection using the user agent](../browser_detection_using_the_user_agent) * [Client hints](../client_hints)
programming_docs
http Accept-Ranges Accept-Ranges ============= Accept-Ranges ============= The `Accept-Ranges` HTTP response header is a marker used by the server to advertise its support for partial requests from the client for file downloads. The value of this field indicates the unit that can be used to define a range. In the presence of an `Accept-Ranges` header, the browser may try to *resume* an interrupted download instead of trying to restart the download. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Accept-Ranges: <range-unit> Accept-Ranges: none ``` Directives ---------- `<range-unit>` Defines the range unit that the server supports. Though `bytes` is the only range unit formally defined by [RFC 7233](https://datatracker.ietf.org/doc/html/rfc7233), additional range units may be registered in the[HTTP Range Unit Registry](https://www.iana.org/assignments/http-parameters/http-parameters.xhtml#range-units). `none` Indicates that no range unit is supported. This makes the header equivalent of its own absence and is therefore, rarely used. Although in some browsers, like IE9, this setting is used to disable or remove the pause buttons in the download manager. Examples -------- ``` Accept-Ranges: bytes ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.accept-ranges](https://httpwg.org/specs/rfc9110.html#field.accept-ranges) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Accept-Ranges` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`If-Range`](if-range) * [`Range`](range) * [IANA HTTP Range Unit Registry](https://www.iana.org/assignments/http-parameters/http-parameters.xhtml#range-units) http Sec-CH-UA-Platform-Version Sec-CH-UA-Platform-Version ========================== Sec-CH-UA-Platform-Version ========================== **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). The `Sec-CH-UA-Platform-Version` [user agent client hint](../client_hints#user-agent_client_hints) request header provides the version of the operating system on which the user agent is running. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Sec-CH-UA-Platform-Version: <version> ``` ### Directives `<version>` The version string typically contains the operating system version in a string, consisting of dot-separated major, minor and patch version numbers. For example, `"11.0.0"` The version string on Linux is always empty. Examples -------- A server requests the `Sec-CH-UA-Platform-Version` header by including the [`Accept-CH`](accept-ch) in a *response* to any request from the client, using the name of the desired header as a token: ``` HTTP/1.1 200 OK Accept-CH: Sec-CH-UA-Platform-Version ``` The client may choose to provide the hint, and add the `Sec-CH-UA-Platform-Version` header to subsequent requests. For example, the following request headers might be sent from a browser running on Windows 10. ``` GET /GET /my/page HTTP/1.1 Host: example.site Sec-CH-UA: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96" Sec-CH-UA-Mobile: ?0 Sec-CH-UA-Platform: "Windows" Sec-CH-UA-Platform-Version: "10.0.0" ``` Specifications -------------- | Specification | | --- | | [User-Agent Client Hints # sec-ch-ua-platform-version](https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform-version) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Sec-CH-UA-Platform-Version` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | See also -------- * [Client hints](../client_hints) * [User-Agent Client Hints API](https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API) * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) http Large-Allocation Large-Allocation ================ Large-Allocation ================ **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. **Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The non-standard `Large-Allocation` response header tells the browser that the page being loaded is going to want to perform a large allocation. It's not implemented in current versions of any browser, but is harmless to send to any browser. [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly) or asm.js applications can use large contiguous blocks of allocated memory. For complex games, for example, these allocations can be quite large, sometimes as large as 1GB. The `Large-Allocation` tells the browser that the web content in the to-be-loaded page is going to want to perform a large contiguous memory allocation and the browser can react to this header by starting a dedicated process for the to-be-loaded document, for example. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Large-Allocation: 0 Large-Allocation: <megabytes> ``` Directives ---------- `0` 0 is a special value which represents uncertainty as to what the size of the allocation is. `<megabytes>` The expected size of the allocation to be performed, in megabytes. Examples -------- ``` Large-Allocation: 0 Large-Allocation: 500 ``` Troubleshooting errors ---------------------- The `Large-Allocation` header throws warnings or error messages when used incorrectly. You'll encounter them in the [web console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html). This page was loaded in a new process due to a `Large-Allocation` header. This message means that the browser saw the `Large-Allocation` header, and was able to reload the page into a new process which should have more available contiguous memory. A `Large-Allocation` header was ignored due to the load being triggered by a non-GET request. When a [`POST`](../methods/post) request is used to load a document, that load cannot currently be redirected into a new process. This error is displayed when loading a document with a `Large-Allocation` header with a non-GET HTTP method. This could be caused due to the document being loaded by a form submission, for example. A `Large-Allocation` header was ignored due to the presence of windows which have a reference to this browsing context through the frame hierarchy or [`window.opener`](https://developer.mozilla.org/en-US/docs/Web/API/Window/opener). This error means that the document was not loaded at the top level of an user-opened or noopener-opened tab or window. It can occur in these situations: * The document with the `Large-Allocation` header was loaded in an [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe). Firefox cannot move an iframe into a new process currently, so the document must load in the current process. * The document with the `Large-Allocation` header was loaded in a window which was opened by [`window.open()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/open), `<a target="_blank">` or other similar methods without `rel="noopener"` or the `"noopener"` feature being set. These windows must remain in the same process as their opener, as they can communicate, meaning that we cannot allow them to switch processes. * The document with the `Large-Allocation header` has opened another window with [`window.open()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/open), `<a target="_blank">` or other similar methods without `rel="noopener"` or the `"noopener"` feature being set. This is for the same reason as above, namely that they can communicate and thus we cannot allow them to switch processes. This page would be loaded in a new process due to a `Large-Allocation` header, however `Large-Allocation` process creation is disabled on non-Win32 platforms. Firefox currently only supports the `Large-Allocation` header in our 32-bit Windows builds, as memory fragmentation is not an issue in 64-bit builds. If you are running a non-win32 version of Firefox, this error will appear. This check can be disabled with the `dom.largeAllocation.forceEnable` boolean preference in about:config. Specifications -------------- Not part of any current specifications. An explainer of the ideas behind this header can be found in [this document](https://gist.github.com/mystor/5739e222e398efc6c29108be55eb6fe3). Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Large-Allocation` | No | No | 53-100 | No | No | No | No | No | No | No | No | No | See also -------- * [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly) http TE TE == TE == The `TE` request header specifies the transfer encodings the user agent is willing to accept. (you could informally call it `Accept-Transfer-Encoding`, which would be more intuitive). **Note:** In [HTTP/2](https://httpwg.org/specs/rfc9113.html#ConnectionSpecific) and [HTTP/3](https://httpwg.org/specs/rfc9114.html#header-formatting), the `TE` header field is only accepted if the `trailers` value is set. See also the [`Transfer-Encoding`](transfer-encoding) response header for more details on transfer encodings. Note that `chunked` is always acceptable for HTTP/1.1 recipients and you don't have to specify `"chunked"` using the `TE` header. However, it is useful for setting if the client is accepting trailer fields in a chunked transfer coding using the "trailers" value. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` TE: compress TE: deflate TE: gzip TE: trailers // Multiple directives, weighted with the quality value syntax: TE: trailers, deflate;q=0.5 ``` Directives ---------- `compress` A format using the [Lempel-Ziv-Welch](https://en.wikipedia.org/wiki/LZW) (LZW) algorithm is accepted as a transfer coding name. `deflate` Using the [zlib](https://en.wikipedia.org/wiki/Zlib) structure is accepted as a transfer coding name. `gzip` A format using the [Lempel-Ziv coding](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ77) (LZ77), with a 32-bit CRC is accepted as a transfer coding name. `trailers` Indicates that the client is willing to accept trailer fields in a chunked transfer coding. `q` When multiple transfer codings are acceptable, the `q` parameter of the [quality value](https://developer.mozilla.org/en-US/docs/Glossary/Quality_values) syntax can rank codings by preference. Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.te](https://httpwg.org/specs/rfc9110.html#field.te) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `TE` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Transfer-Encoding`](transfer-encoding) * [`Trailer`](trailer) * [Chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding) http Forwarded Forwarded ========= Forwarded ========= The `Forwarded` request header contains information that may be added by [reverse proxy servers](../proxy_servers_and_tunneling) (load balancers, CDNs, and so on) that would otherwise be altered or lost when proxy servers are involved in the path of the request. For example, if a client is connecting to a web server through an HTTP proxy (or load balancer), server logs will only contain the IP address, host address, and protocol of the proxy; this header can be used to identify the IP address, host, and protocol, of the original request. The header is optional and may be added to, modified, or removed, by any of the proxy servers on the path to the server. This header is used for debugging, statistics, and generating location-dependent content. By design, it exposes privacy sensitive information, such as the IP address of the client. Therefore, the user's privacy must be kept in mind when deploying this header. The alternative and de-facto standard versions of this header are the [`X-Forwarded-For`](x-forwarded-for), [`X-Forwarded-Host`](x-forwarded-host) and [`X-Forwarded-Proto`](x-forwarded-proto) headers. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ The syntax for the forwarding header from a single proxy is shown below. Directives are `key=value` pairs, separated by a semicolon. ``` Forwarded: by=<identifier>;for=<identifier>;host=<host>;proto=<http|https> ``` If there are multiple proxy servers between the client and server, they may each specify their own forwarding information. This can be done by adding a new `Forwarded` header to the end of the header block, or by appending the information to the end of the last `Forwarded` header in a comma-separated list. Directives ---------- `by` Optional The interface where the request came in to the proxy server. The identifier can be: * an obfuscated identifier (such as "hidden" or "secret"). This should be treated as the default. * an IP address (v4 or v6, optionally with a port, and ipv6 quoted and enclosed in square brackets) * "unknown" when the preceding entity is not known (and you still want to indicate that forwarding of the request was made) `for` Optional The client that initiated the request and subsequent proxies in a chain of proxies. The identifier has the same possible values as the `by` directive. `host` Optional The [`Host`](host) request header field as received by the proxy. `proto` Optional Indicates which protocol was used to make the request (typically "http" or "https"). Examples -------- ### Using the `Forwarded` header ``` Forwarded: for="\_mdn" # case insensitive Forwarded: For="[2001:db8:cafe::17]:4711" # separated by semicolon Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43 # Values from multiple proxy servers can be appended using a comma Forwarded: for=192.0.2.43, for=198.51.100.17 ``` ### Transitioning from `X-Forwarded-For` to `Forwarded` If your application, server, or proxy supports the standardized `Forwarded` header, the [`X-Forwarded-For`](x-forwarded-for) header can be replaced. Note that IPv6 address is quoted and enclosed in square brackets in `Forwarded`. ``` X-Forwarded-For: 123.34.567.89 Forwarded: for=123.34.567.89 X-Forwarded-For: 192.0.2.43, "[2001:db8:cafe::17]" Forwarded: for=192.0.2.43, for="[2001:db8:cafe::17]" ``` Specifications -------------- | Specification | | --- | | [Forwarded HTTP Extension # section-4](https://www.rfc-editor.org/rfc/rfc7239#section-4) | See also -------- * [`X-Forwarded-For`](x-forwarded-for) * [`X-Forwarded-Host`](x-forwarded-host) * [`X-Forwarded-Proto`](x-forwarded-proto) * [`Via`](via) – provides information about the proxy itself, not about the client connecting to it. http NEL NEL === NEL === **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. The HTTP `NEL` response header is used to configure network request logging. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ | Specification | | --- | | [Network Error Logging # nel-response-header](https://w3c.github.io/network-error-logging/#nel-response-header) | ``` NEL: { "report\_to": "name\_of\_reporting\_group", "max\_age": 12345, "include\_subdomains": false, "success\_fraction": 0.0, "failure\_fraction": 1.0 } ``` Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `NEL` | 71 | 79 | No | No | 58 | No | 71 | 71 | No | 50 | No | 10.2 | See also -------- * [Network Error Logging (NEL) explainer](../network_error_logging) http Access-Control-Allow-Methods Access-Control-Allow-Methods ============================ Access-Control-Allow-Methods ============================ The `Access-Control-Allow-Methods` response header specifies one or more methods allowed when accessing a resource in response to a [preflight request](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request). | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Access-Control-Allow-Methods: <method>, <method>, … Access-Control-Allow-Methods: \* ``` Directives ---------- <method> A comma-delimited list of the allowed [HTTP request methods](../methods). `*` (wildcard) The value "`*`" only counts as a special wildcard value for requests without credentials (requests without [HTTP cookies](../cookies) or HTTP authentication information). In requests with credentials, it is treated as the literal method name "`*`" without special semantics. Examples -------- ``` Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Allow-Methods: \* ``` Specifications -------------- | Specification | | --- | | [Fetch Standard # http-access-control-allow-methods](https://fetch.spec.whatwg.org/#http-access-control-allow-methods) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Access-Control-Allow-Methods` | 4 | 12 | 3.5 | 10 | 12 | 4 | 2 | Yes | 4 | 12 | 3.2 | Yes | | `wildcard` | 63 | 79 | 69 | No | 50 | No | 63 | 63 | No | 46 | No | 8.2 | See also -------- * [`Access-Control-Allow-Origin`](access-control-allow-origin) * [`Access-Control-Expose-Headers`](access-control-expose-headers) * [`Access-Control-Allow-Headers`](access-control-allow-headers) * [`Access-Control-Request-Method`](access-control-request-method)
programming_docs
http Sec-CH-UA-Model Sec-CH-UA-Model =============== Sec-CH-UA-Model =============== **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). The `Sec-CH-UA-Model` [user agent client hint](../client_hints#user-agent_client_hints) request header indicates the device model on which the browser is running. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Sec-CH-UA-Model: <device-version> ``` ### Directives `<device-version>` A string containing the device version. For example "Pixel 3". Examples -------- A server requests the `Sec-CH-UA-Model` header by including the [`Accept-CH`](accept-ch) in a *response* to any request from the client, using the name of the desired header as a token: ``` HTTP/1.1 200 OK Accept-CH: Sec-CH-UA-Model ``` The client may choose to provide the hint, and add the `Sec-CH-UA-Model` header to subsequent requests. For example, on mobile phone the client might add the header as shown: ``` GET /GET /my/page HTTP/1.1 Host: example.site Sec-CH-UA: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96" Sec-CH-UA-Mobile: ?1 Sec-CH-UA-Platform: "Android" Sec-CH-UA-Bitness: "64" Sec-CH-UA-Model: "Pixel 3 XL" ``` Specifications -------------- | Specification | | --- | | [User-Agent Client Hints # sec-ch-ua-model](https://wicg.github.io/ua-client-hints/#sec-ch-ua-model) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Sec-CH-UA-Model` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | See also -------- * [Client hints](../client_hints) * [User-Agent Client Hints API](https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API) * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) http X-XSS-Protection X-XSS-Protection ================ X-XSS-Protection ================ **Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The HTTP `X-XSS-Protection` response header is a feature of Internet Explorer, Chrome and Safari that stops pages from loading when they detect reflected cross-site scripting ([XSS](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting)) attacks. These protections are largely unnecessary in modern browsers when sites implement a strong [`Content-Security-Policy`](content-security-policy) that disables the use of inline JavaScript (`'unsafe-inline'`). **Warning:** Even though this feature can protect users of older web browsers that don't yet support [CSP](https://developer.mozilla.org/en-US/docs/Glossary/CSP), in some cases, **XSS protection can create XSS vulnerabilities** in otherwise safe websites. See the section below for more information. **Note:** * Chrome has [removed their XSS Auditor](https://chromestatus.com/feature/5021976655560704) * Firefox has not, and [will not implement `X-XSS-Protection`](https://bugzilla.mozilla.org/show_bug.cgi?id=528661) * Edge has [retired their XSS filter](https://blogs.windows.com/windows-insider/2018/07/25/announcing-windows-10-insider-preview-build-17723-and-build-18204/) This means that if you do not need to support legacy browsers, it is recommended that you use [`Content-Security-Policy`](content-security-policy) without allowing `unsafe-inline` scripts instead. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` X-XSS-Protection: 0 X-XSS-Protection: 1 X-XSS-Protection: 1; mode=block X-XSS-Protection: 1; report=<reporting-uri> ``` 0 Disables XSS filtering. 1 Enables XSS filtering (usually default in browsers). If a cross-site scripting attack is detected, the browser will sanitize the page (remove the unsafe parts). 1; mode=block Enables XSS filtering. Rather than sanitizing the page, the browser will prevent rendering of the page if an attack is detected. 1; report=<reporting-URI> (Chromium only) Enables XSS filtering. If a cross-site scripting attack is detected, the browser will sanitize the page and report the violation. This uses the functionality of the CSP [`report-uri`](content-security-policy/report-uri) directive to send a report. Vulnerabilities caused by XSS filtering --------------------------------------- Consider the following excerpt of HTML code for a webpage: ``` <script> var productionMode = true; </script> <!-- [...] --> <script> if (!window.productionMode) { // Some vulnerable debug code } </script> ``` This code is completely safe if the browser doesn't perform XSS filtering. However, if it does and the search query is `?something=%3Cscript%3Evar%20productionMode%20%3D%20true%3B%3C%2Fscript%3E`, the browser might execute the scripts in the page ignoring `<script>var productionMode = true;</script>` (thinking the server included it in the response because it was in the URI), causing `window.productionMode` to be evaluated to `undefined` and executing the unsafe debug code. Setting the `X-XSS-Protection` header to either `0` or `1; mode=block` prevents vulnerabilities like the one described above. The former would make the browser run all scripts and the latter would prevent the page from being processed at all (though this approach might be vulnerable to [side-channel attacks](https://portswigger.net/research/abusing-chromes-xss-auditor-to-steal-tokens) if the website is embeddable in an `<iframe>`). Example ------- Block pages from loading when they detect reflected XSS attacks: ``` X-XSS-Protection: 1; mode=block ``` PHP ``` header("X-XSS-Protection: 1; mode=block"); ``` Apache (.htaccess) ``` <IfModule mod_headers.c> Header set X-XSS-Protection "1; mode=block" </IfModule> ``` Nginx ``` add_header "X-XSS-Protection" "1; mode=block"; ``` Specifications -------------- Not part of any specifications or drafts. Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `X-XSS-Protection` | 4-78 | 12-17 | No | 8 | Yes-65 | Yes | No | Yes-78 | No | Yes-56 | Yes | Yes-12.0 | See also -------- * [`Content-Security-Policy`](content-security-policy) * [Controlling the XSS Filter – Microsoft](https://docs.microsoft.com/archive/blogs/ieinternals/controlling-the-xss-filter) * [Understanding XSS Auditor – Virtue Security](https://www.virtuesecurity.com/understanding-xss-auditor/) * [The misunderstood X-XSS-Protection – blog.innerht.ml](https://blog.innerht.ml/the-misunderstood-x-xss-protection/) http Access-Control-Allow-Headers Access-Control-Allow-Headers ============================ Access-Control-Allow-Headers ============================ The `Access-Control-Allow-Headers` response header is used in response to a [preflight request](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request) which includes the [`Access-Control-Request-Headers`](access-control-request-headers) to indicate which HTTP headers can be used during the actual request. This header is required if the request has an [`Access-Control-Request-Headers`](access-control-request-headers) header. **Note:** [CORS-safelisted request headers](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header) are always allowed and usually aren't listed in `Access-Control-Allow-Headers` (unless there is a need to circumvent the safelist [additional restrictions](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header#additional_restrictions)). | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Access-Control-Allow-Headers: [<header-name>[, <header-name>]\*] Access-Control-Allow-Headers: \* ``` Directives ---------- `<header-name>` The name of a supported request header. The header may list any number of headers, separated by commas. `*` (wildcard) The value "`*`" only counts as a special wildcard value for requests without credentials (requests without [HTTP cookies](../cookies) or HTTP authentication information). In requests with credentials, it is treated as the literal header name "`*`" without special semantics. Note that the [`Authorization`](authorization) header can't be wildcarded and always needs to be listed explicitly. Examples -------- ### A custom header Here's an example of what an `Access-Control-Allow-Headers` header might look like. It indicates that a custom header named `X-Custom-Header` is supported by CORS requests to the server (in addition to the [CORS-safelisted request headers](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header)). ``` Access-Control-Allow-Headers: X-Custom-Header ``` ### Multiple headers This example shows `Access-Control-Allow-Headers` when it specifies support for multiple headers. ``` Access-Control-Allow-Headers: X-Custom-Header, Upgrade-Insecure-Requests ``` ### Bypassing additional restrictions Although [CORS-safelisted request headers](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header) are always allowed and don't usually need to be listed in `Access-Control-Allow-Headers`, listing them anyway will circumvent the [additional restrictions](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header#additional_restrictions) that apply. ``` Access-Control-Allow-Headers: Accept ``` ### Example preflight request Let's look at an example of a [preflight request](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request) involving `Access-Control-Allow-Headers`. #### Request First, the request. The preflight request is an [`OPTIONS`](../methods/options) request that includes some combination of the three preflight request headers: [`Access-Control-Request-Method`](access-control-request-method), [`Access-Control-Request-Headers`](access-control-request-headers), and [`Origin`](origin). The preflight request below tells the server that we want to send a CORS `GET` request with the headers listed in [`Access-Control-Request-Headers`](access-control-request-headers) ([`Content-Type`](content-type) and `x-requested-with`). ``` OPTIONS /resource/foo Access-Control-Request-Method: GET Access-Control-Request-Headers: Content-Type, x-requested-with Origin: https://foo.bar.org ``` #### Response If the CORS request indicated by the preflight request is authorized, the server will respond to the preflight request with a message that indicates the allowed origin, methods, and headers. Below we see that [`Access-Control-Allow-Headers`](access-control-allow-headers) includes the headers that were requested. ``` HTTP/1.1 200 OK Content-Length: 0 Connection: keep-alive Access-Control-Allow-Origin: https://foo.bar.org Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE Access-Control-Allow-Headers: Content-Type, x-requested-with Access-Control-Max-Age: 86400 ``` If the requested method isn't supported, the server will respond with an error. Specifications -------------- | Specification | | --- | | [Fetch Standard # http-access-control-allow-headers](https://fetch.spec.whatwg.org/#http-access-control-allow-headers) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Access-Control-Allow-Headers` | 4 | 12 | 3.5 | 10 | 12 | 4 | 2 | Yes | 4 | 12 | 3.2 | Yes | | `wildcard` | 63 | 79 | 69 | No | 50 | No | 63 | 63 | No | 46 | No | 8.2 | See also -------- * [`Access-Control-Allow-Origin`](access-control-allow-origin) * [`Access-Control-Expose-Headers`](access-control-expose-headers) * [`Access-Control-Allow-Methods`](access-control-allow-methods) * [`Access-Control-Request-Headers`](access-control-request-headers) http Age Age === Age === The `Age` header contains the time in seconds the object was in a proxy cache. The `Age` header is usually close to zero. If it is `Age: 0`, it was probably fetched from the origin server; otherwise, it was usually calculated as a difference between the proxy's current date and the [`Date`](date) general header included in the HTTP response. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Age: <delta-seconds> ``` Directives ---------- <delta-seconds> A non-negative integer that is time in seconds the object was in a proxy cache. Examples -------- ``` Age: 24 ``` Specifications -------------- | Specification | | --- | | [HTTP Caching # field.age](https://httpwg.org/specs/rfc9111.html#field.age) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Age` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Cache-Control`](cache-control) * [`Expires`](expires) http Alt-Svc Alt-Svc ======= Alt-Svc ======= The [`Alt-Svc`](alt-svc) HTTP header allows a server to indicate that another network location (the "alternative service") can be treated as authoritative for that origin when making future requests. Doing so allows new protocol versions to be advertised without affecting in-flight requests, and can also help servers manage traffic. Using an alternative service is not visible to the end user; it does not change the URL or the origin of the request, and does not introduce extra round trips. Syntax ------ ``` Alt-Svc: clear Alt-Svc: <protocol-id>=<alt-authority>; ma=<max-age> Alt-Svc: <protocol-id>=<alt-authority>; ma=<max-age>; persist=1 ``` `clear` The special value `clear` indicates that the origin requests all alternative services for that origin to be invalidated. `<protocol-id>` The [ALPN](https://developer.mozilla.org/en-US/docs/Glossary/ALPN) protocol identifier. Examples include `h2` for HTTP/2 and `h3-25` for draft 25 of the HTTP/3 protocol. `<alt-authority>` The quoted string specifying the alternative authority which consists of an optional host override, a colon, and a mandatory port number. `ma=<max-age>` Optional The number of seconds for which the alternative service is considered fresh. If omitted, it defaults to 24 hours. Alternative service entries can be cached for up to *<max-age>* seconds, minus the age of the response (from the [`Age`](age) header). Once the cached entry expires, the client can no longer use this alternative service for new connections. `persist=1` Optional Usually cached alternative service entries are cleared on network configuration changes. Use of the `persist=1` parameter requests that the entry not be deleted by such changes. Multiple entries can be specified in a single `Alt-Svc` header using comma as separator. In that case, early entries are considered more preferable. Example ------- ``` Alt-Svc: h2=":443"; ma=2592000; Alt-Svc: h2=":443"; ma=2592000; persist=1 Alt-Svc: h2="alt.example.com:443", h2=":443" Alt-Svc: h3-25=":443"; ma=3600, h2=":443"; ma=3600 ``` Specifications -------------- | Specification | | --- | | [HTTP Alternative Services # alt-svc](https://httpwg.org/specs/rfc7838.html#alt-svc) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Alt-Svc` | Yes | ≤79 | 38 37-38 Only supports draft-04 | No | Yes | No | Yes | Yes | 38 37-38 Only supports draft-04 | Yes | No | Yes | See also -------- * [Alternative Services](https://www.mnot.net/blog/2016/03/09/alt-svc) (article about `Alt-Svc` by HTTP Working Group chair Mark Nottingham) http If-Match If-Match ======== If-Match ======== The `If-Match` HTTP request header makes a request conditional. A server will only return requested resources for [`GET`](../methods/get) and [`HEAD`](../methods/head) methods, or upload resource for [`PUT`](../methods/put) and other non-safe methods, if the resource matches one of the listed [`ETag`](etag) values. If the conditional does not match then the [`412`](../status/412) (Precondition Failed) response is returned. The comparison with the stored [`ETag`](etag) uses the *strong comparison algorithm*, meaning two files are considered identical byte by byte only. If a listed `ETag` has the `W/` prefix indicating a weak entity tag, this comparison algorithm will never match it. There are two common use cases: * For [`GET`](../methods/get) and [`HEAD`](../methods/head) methods, used in combination with a [`Range`](range) header, it can guarantee that the new ranges requested come from the same resource as the previous one. * For other methods, and in particular for [`PUT`](../methods/put), `If-Match` can be used to prevent the [lost update problem](https://www.w3.org/1999/04/Editing/#3.1). It can check if the modification of a resource that the user wants to upload will not override another change that has been done since the original resource was fetched. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` If-Match: <etag\_value> If-Match: <etag\_value>, <etag\_value>, … ``` Directives ---------- `<etag_value>` Entity tags uniquely representing the requested resources. They are a string of ASCII characters placed between double quotes (like `"675af34563dc-tr34"`). They may be prefixed by `W/` to indicate that they are "weak", i.e. that they represent the resource semantically but not byte-by-byte. However, in an `If-Match` header, weak entity tags will never match. `*` The asterisk is a special value representing any resource. Note that this must match as `false` if the origin server does not have a current representation for the target resource. Examples -------- ``` If-Match: "bfc13a64729c4290ef5b2c2730249c88ca92d82d" If-Match: "67ab43", "54ed21", "7892dd" If-Match: \* ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.if-match](https://httpwg.org/specs/rfc9110.html#field.if-match) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `If-Match` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`ETag`](etag) * [`If-Unmodified-Since`](if-unmodified-since) * [`If-Modified-Since`](if-modified-since) * [`If-None-Match`](if-none-match) * [`412 Precondition Failed`](../status/412) * [`416 Range Not Satisfiable`](../status/416)
programming_docs
http Trailer Trailer ======= Trailer ======= The **Trailer** response header allows the sender to include additional fields at the end of chunked messages in order to supply metadata that might be dynamically generated while the message body is sent, such as a message integrity check, digital signature, or post-processing status. **Note:** The [`TE`](te) request header needs to be set to "trailers" to allow trailer fields. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header), [Payload header](https://developer.mozilla.org/en-US/docs/Glossary/Payload_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Trailer: header-names ``` Directives ---------- `header-names` HTTP header fields which will be present in the trailer part of chunked messages. These header fields are **disallowed**: * message framing headers (e.g., [`Transfer-Encoding`](transfer-encoding) and [`Content-Length`](content-length)), * routing headers (e.g., [`Host`](host)), * request modifiers (e.g., controls and conditionals, like [`Cache-Control`](cache-control), [`Max-Forwards`](max-forwards), or [`TE`](te)), * authentication headers (e.g., [`Authorization`](authorization) or [`Set-Cookie`](set-cookie)), * or [`Content-Encoding`](content-encoding), [`Content-Type`](content-type), [`Content-Range`](content-range), and `Trailer` itself. Examples -------- ### Chunked transfer encoding using a trailing header In this example, the [`Expires`](expires) header is used at the end of the chunked message and serves as a trailing header. ``` HTTP/1.1 200 OK Content-Type: text/plain Transfer-Encoding: chunked Trailer: Expires 7\r\n Mozilla\r\n 9\r\n Developer\r\n 7\r\n Network\r\n 0\r\n Expires: Wed, 21 Oct 2015 07:28:00 GMT\r\n \r\n ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.trailer](https://httpwg.org/specs/rfc9110.html#field.trailer) | | [HTTP/1.1 # chunked.trailer.section](https://httpwg.org/specs/rfc9112.html#chunked.trailer.section) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Trailer` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Transfer-Encoding`](transfer-encoding) * [`TE`](te) * [Chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding) http Last-Modified Last-Modified ============= Last-Modified ============= The `Last-Modified` response HTTP header contains a date and time when the origin server believes the resource was last modified. It is used as a validator to determine if the resource is the same as the previously stored one. Less accurate than an [`ETag`](etag) header, it is a fallback mechanism. Conditional requests containing [`If-Modified-Since`](if-modified-since) or [`If-Unmodified-Since`](if-unmodified-since) headers make use of this field. | | | | --- | --- | | Header type | [Representation header](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [CORS-safelisted response header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header) | yes | Syntax ------ ``` Last-Modified: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT ``` Directives ---------- <day-name> One of "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", or "Sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". <month> One of "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" (case sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <hour> 2 digit hour number, e.g. "09" or "23". <minute> 2 digit minute number, e.g. "04" or "59". <second> 2 digit second number, e.g. "04" or "59". `GMT` Greenwich Mean Time. HTTP dates are always expressed in GMT, never in local time. Examples -------- ``` Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.last-modified](https://httpwg.org/specs/rfc9110.html#field.last-modified) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Last-Modified` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`If-Modified-Since`](if-modified-since) * [`If-Unmodified-Since`](if-unmodified-since) * [`Etag`](etag) http Content-Location Content-Location ================ Content-Location ================ The `Content-Location` header indicates an alternate location for the returned data. The principal use is to indicate the URL of a resource transmitted as the result of [content negotiation](../content_negotiation). [`Location`](location) and `Content-Location` are different. `Location` indicates the URL of a redirect, while `Content-Location` indicates the direct URL to use to access the resource, without further content negotiation in the future. `Location` is a header associated with the response, while `Content-Location` is associated with the data returned. This distinction may seem abstract without [examples](#examples). | | | | --- | --- | | Header type | [Representation header](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Content-Location: <url> ``` Directives ---------- <url> A [relative](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL#examples_of_relative_urls) (to the request URL) or [absolute](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL#examples_of_absolute_urls) URL. Examples -------- ### Requesting data from a server in different formats Let's say a site's API can return data in [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON), [XML](https://developer.mozilla.org/en-US/docs/Glossary/XML), or [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) formats. If the URL for a particular document is at `https://example.com/documents/foo`, the site could return different URLs for `Content-Location` depending on the request's [`Accept`](accept) header: | Request header | Response header | | --- | --- | | `Accept: application/json, text/json` | `Content-Location: /documents/foo.json` | | `Accept: application/xml, text/xml` | `Content-Location: /documents/foo.xml` | | `Accept: text/plain, text/*` | `Content-Location: /documents/foo.txt` | These URLs are examples — the site could serve the different filetypes with any URL patterns it wishes, such as a [query string parameter](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/search): `/documents/foo?format=json`, `/documents/foo?format=xml`, and so on. Then the client could remember that the JSON version is available at that particular URL, skipping content negotiation the next time it requests that document. The server could also consider other [content negotiation](../content_negotiation) headers, such as [`Accept-Language`](accept-language). ### Pointing to a new document (HTTP 201 Created) Say you're creating a new blog post through a site's API: ``` POST /new/post Host: example.com Content-Type: text/markdown # My first blog post! I made this through `example.com`'s API. I hope it worked. ``` The site returns the published post in the response body. The server specifies *where* the new post is with the `Content-Location` header, indicating that this location refers to the content (the body) of this response: ``` HTTP/1.1 201 Created Content-Type: text/markdown Content-Location: /my-first-blog-post # My first blog post I made this through `example.com`'s API. I hope it worked. ``` ### Indicating the URL of a transaction's result Say you have a [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) for sending money to another user of a site. ``` <form action="/send-payment" method="post"> <p> <label>Who do you want to send the money to? <input type="text" name="recipient" /> </label> </p> <p> <label>How much? <input type="number" name="amount" /> </label> </p> <button type="submit">Send Money</button> </form> ``` When the form is submitted, the site generates a receipt for the transaction. The server could use `Content-Location` to indicate that receipt's URL for future access. ``` HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 Content-Location: /my-receipts/38 <!doctype html> (Lots of HTML…) <p>You sent $38.00 to ExampleUser.</p> (Lots more HTML…) ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.content-location](https://httpwg.org/specs/rfc9110.html#field.content-location) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Content-Location` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Location`](location) http Sec-CH-UA-Platform Sec-CH-UA-Platform ================== Sec-CH-UA-Platform ================== **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). The `Sec-CH-UA-Platform` [user agent client hint](../client_hints#user-agent_client_hints) request header provides the platform or operating system on which the user agent is running. For example: "Windows" or "Android". `Sec-CH-UA-Platform` is a [low entropy hint](../client_hints#low_entropy_hints). Unless blocked by a user agent permission policy, it is sent by default (without the server opting in by sending [`Accept-CH`](accept-ch)). | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Sec-CH-UA-Platform: <platform> ``` ### Directives `<platform>` One of the following strings: `"Android"`, `"Chrome OS"`, `"Chromium OS"`, `"iOS"`, `"Linux"`, `"macOS"`, `"Windows"`, or `"Unknown"`. Examples -------- As `Sec-CH-UA-Platform` is a [low entropy hint](../client_hints#low_entropy_hints) it is typically sent in all requests. A browser running on a macOS computer might add the following header to all requests. ``` Sec-CH-UA-Platform: "macOS" ``` Specifications -------------- | Specification | | --- | | [User-Agent Client Hints # sec-ch-ua-platform](https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Sec-CH-UA-Platform` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | See also -------- * [Client hints](../client_hints) * [User-Agent Client Hints API](https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API) * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) http WWW-Authenticate WWW-Authenticate ================ WWW-Authenticate ================ The HTTP `WWW-Authenticate` response header defines the [HTTP authentication](../authentication) methods ("challenges") that might be used to gain access to a specific resource. **Note:** This header is part of the [General HTTP authentication framework](../authentication#the_general_http_authentication_framework), which can be used with a number of [authentication schemes](../authentication#authentication_schemes). Each "challenge" lists a scheme supported by the server and additional parameters that are defined for that scheme type. A server using [HTTP authentication](../authentication) will respond with a [`401`](../status/401) `Unauthorized` response to a request for a protected resource. This response must include at least one `WWW-Authenticate` header and at least one [challenge](https://developer.mozilla.org/en-US/docs/Glossary/challenge), to indicate what authentication schemes can be used to access the resource (and any additional data that each particular scheme needs). Multiple challenges are allowed in one `WWW-Authenticate` header, and multiple `WWW-Authenticate` headers are allowed in one response. A server may also include the `WWW-Authenticate` header in other response messages to indicate that supplying credentials might affect the response. After receiving the `WWW-Authenticate` header, a client will typically prompt the user for credentials, and then re-request the resource. This new request uses the [`Authorization`](authorization) header to supply the credentials to the server, encoded appropriately for the selected "challenge" authentication method. The client is expected to select the most secure of the challenges it understands (note that in some cases the "most secure" method is debatable). | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ At least one challenge must be specified. Multiple challenges may be specified, comma-separated, in a single header, or in individual headers: ``` // Challenges specified in single header WWW-Authenticate: challenge1, ..., challengeN // Challenges specified in multiple headers WWW-Authenticate: challenge1 ... WWW-Authenticate: challengeN ``` A single challenge has the following format. Note that the scheme token (`<auth-scheme>`) is mandatory. The presence of `realm`, `token68` and any other parameters depends on the definition of the selected scheme. ``` // Possible challenge formats (scheme dependent) WWW-Authenticate: <auth-scheme> WWW-Authenticate: <auth-scheme> realm=<realm> WWW-Authenticate: <auth-scheme> token68 WWW-Authenticate: <auth-scheme> auth-param1=token1, ..., auth-paramN=auth-paramN-token WWW-Authenticate: <auth-scheme> realm=<realm> token68 WWW-Authenticate: <auth-scheme> realm=<realm> token68 auth-param1=auth-param1-token , ..., auth-paramN=auth-paramN-token WWW-Authenticate: <auth-scheme> realm=<realm> auth-param1=auth-param1-token, ..., auth-paramN=auth-paramN-token WWW-Authenticate: <auth-scheme> token68 auth-param1=auth-param1-token, ..., auth-paramN=auth-paramN-token ``` For example, [Basic authentication](../authentication#basic_authentication_scheme) allows for optional `realm` and `charset` keys, but does not support `token68`. ``` WWW-Authenticate: Basic WWW-Authenticate: Basic realm=<realm> WWW-Authenticate: Basic realm=<realm>, charset="UTF-8" ``` Directives ---------- `<auth-scheme>` The [Authentication scheme](../authentication#authentication_schemes). Some of the more common types are (case-insensitive): [`Basic`](../authentication#basic_authentication_scheme), `Digest`, `Negotiate` and `AWS4-HMAC-SHA256`. **Note:** For more information/options see [HTTP Authentication > Authentication schemes](../authentication#authentication_schemes) **realm=**<realm> Optional A string describing a protected area. A realm allows a server to partition up the areas it protects (if supported by a scheme that allows such partitioning), and informs users about which particular username/password are required. If no realm is specified, clients often display a formatted hostname instead. `<token68>` Optional A token that may be useful for some schemes. The token allows the 66 unreserved URI characters plus a few others. According to the specification, it can hold a base64, base64url, base32, or base16 (hex) encoding, with or without padding, but excluding whitespace. Other than `<auth-scheme>` and the key `realm`, authorization parameters are specific to each [authentication scheme](../authentication#authentication_schemes). Generally you will need to check the relevant specifications for these (keys for a small subset of schemes are listed below). ### Basic `<realm>` Optional As above. `charset="UTF-8"` Optional Tells the client the server's preferred encoding scheme when submitting a username and password. The only allowed value is the case-insensitive string "UTF-8". This does not relate to the encoding of the realm string. ### Digest `<realm>` Optional String indicating which username/password to use. Minimally should include the host name, but might indicate the users or group that have access. `domain` Optional A quoted, space-separated list of URI prefixes that define all the locations where the authentication information may be used. If this key is not specified then the authentication information may be used anywhere on the web root. `nonce` A server-specified quoted string that the server can use to control the lifetime in which particular credentials will be considered valid. This must be uniquely generated each time a 401 response is made, and may be regenerated more often (for example, allowing a digest to be used only once). The specification contains advice on possible algorithms for generating this value. The nonce value is opaque to the client. `opaque` A server-specified quoted string that should be returned unchanged in the [`Authorization`](authorization). This is opaque to the client. The server is recommended to include Base64 or hexadecimal data. `stale` Optional A case-insensitive flag indicating that the previous request from the client was rejected because the `nonce` used is too old (stale). If this is `true` the request can be re-tried using the same username/password encrypted using the new `nonce`. If it is any other value then the username/password are invalid and must be re-requested from the user. `algorithm` Optional Algorithm used to produce the digest. Valid non-session values are: `"MD5"` (default if not specified), `"SHA-256"`, `"SHA-512"`. Valid session values are: `"MD5-sess"`, `"SHA-256-sess"`, `"SHA-512-sess"`. `qop` Quoted string indicating the quality of protection supported by the server. This must be supplied, and unrecognized options must be ignored. * `"auth"`: Authentication * `"auth-int"`: Authentication with integrity protection `charset="UTF-8"` Optional Tells the client the server's preferred encoding scheme when submitting a username and password. The only allowed value is the case-insensitive string "UTF-8". `userhash` Optional A server may specify `"true"` to indicate that it supports username hashing (default is `"false"`) Examples -------- ### Basic authentication A server that only supports basic authentication might have a `WWW-Authenticate` response header which looks like this: ``` WWW-Authenticate: Basic realm="Access to the staging site", charset="UTF-8" ``` A user-agent receiving this header would first prompt the user for their username and password, and then re-request the resource: this time including the (encoded) credentials in the [`Authorization`](authorization) header. The [`Authorization`](authorization) header might look like this: ``` Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l ``` For `"Basic"` authentication the credentials are constructed by first combining the username and the password with a colon (`aladdin:opensesame`), and then by encoding the resulting string in [`base64`](https://developer.mozilla.org/en-US/docs/Glossary/Base64) (`YWxhZGRpbjpvcGVuc2VzYW1l`). **Note:** See also [HTTP authentication](../authentication) for examples on how to configure Apache or Nginx servers to password protect your site with HTTP basic authentication. ### Digest authentication with SHA-256 and MD5 **Note:** This example is taken from [RFC 7616](https://datatracker.ietf.org/doc/html/rfc7616) "HTTP Digest Access Authentication" (other examples in the specification show the use of `SHA-512`, `charset`, and `userhash`). The client attempts to access a document at URI "<http://www.example.org/dir/index.html>" that is protected via digest authentication. The username for this document is "Mufasa" and the password is "Circle of Life" (note the single space between each of the words). The first time the client requests the document, no [`Authorization`](authorization) header field is sent. Here the server responds with an HTTP 401 message that includes a challenge for each digest algorithm it supports, in its order of preference (`SHA256` and then `MD5`) ``` HTTP/1.1 401 Unauthorized WWW-Authenticate: Digest realm="[email protected]", qop="auth, auth-int", algorithm=SHA-256, nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS" WWW-Authenticate: Digest realm="[email protected]", qop="auth, auth-int", algorithm=MD5, nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS" ``` The client prompts the user for their username and password, and then responds with a new request that encodes the credentials in the [`Authorization`](authorization) header field. If the client chose the MD5 digest the [`Authorization`](authorization) header field might look as shown below: ``` Authorization: Digest username="Mufasa", realm="[email protected]", uri="/dir/index.html", algorithm=MD5, nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", nc=00000001, cnonce="f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ", qop=auth, response="8ca523f5e9506fed4657c9700eebdbec", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS" ``` If the client chose the SHA-256 digest the [`Authorization`](authorization) header field might look as shown below: ``` Authorization: Digest username="Mufasa", realm="[email protected]", uri="/dir/index.html", algorithm=SHA-256, nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", nc=00000001, cnonce="f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ", qop=auth, response="753927fa0e85d155564e2e272a28d1802ca10daf449 6794697cf8db5856cb6c1", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS" ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.www-authenticate](https://httpwg.org/specs/rfc9110.html#field.www-authenticate) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Basic` | 1 | 12 | 1 | 1 | Yes | Yes | 37 | Yes | Yes | Yes | Yes | Yes | | `Digest` | Yes | Yes | Yes | No | Yes | No | Yes | Yes | Yes | Yes | No | Yes | | `NTLM` | Yes | Yes | Yes | No | Yes | No | Yes | Yes | Yes | Yes | No | Yes | | `Negotiate` | Yes | Yes | Yes | No | Yes | No | Yes | Yes | Yes | Yes | No | Yes | | `WWW-Authenticate` | 1 | 12 | 1 | 1 | Yes | Yes | 37 | Yes | Yes | Yes | Yes | Yes | See also -------- * [HTTP authentication](../authentication) * [`Authorization`](authorization) * [`Proxy-Authorization`](proxy-authorization) * [`Proxy-Authenticate`](proxy-authenticate) * [`401`](../status/401), [`403`](../status/403), [`407`](../status/407)
programming_docs
http Content-Length Content-Length ============== Content-Length ============== The `Content-Length` header indicates the size of the message body, in bytes, sent to the recipient. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header), [Payload header](https://developer.mozilla.org/en-US/docs/Glossary/Payload_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | | [CORS-safelisted response header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header) | yes | Syntax ------ ``` Content-Length: <length> ``` Directives ---------- <length> The length in decimal number of octets. Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.content-length](https://httpwg.org/specs/rfc9110.html#field.content-length) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Content-Length` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `cors_response_safelist` | 76 | ≤79 | 87 | No | 63 | 12.1 | 76 | 76 | 87 | 54 | 12.2 | 12.0 | See also -------- * [`Transfer-Encoding`](transfer-encoding) http Feature-Policy Feature-Policy ============== Feature-Policy ============== **Warning:** The header has now been renamed to `Permissions-Policy` in the spec, and this article will eventually be updated to reflect that change. The HTTP `Feature-Policy` header provides a mechanism to allow and deny the use of browser features in its own frame, and in content within any [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) elements in the document. For more information, see the main [Feature Policy](../feature_policy) article. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Feature-Policy: <directive> <allowlist> ``` `<directive>` The Feature Policy directive to apply the `allowlist` to. See [Directives](#directives) below for a list of the permitted directive names. `<allowlist>` An `allowlist` is a list of origins that takes one or more of the following values, separated by spaces: * `*`: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. * `'self'`: The feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. The feature is not allowed in cross-origin documents in nested browsing contexts. * `'src'`: (In an iframe `allow` attribute only) The feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the URL in the iframe's [src](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attributes) attribute. **Note:** The `'src'` origin is used in the iframe `allow` attribute only, and is the *default* `allowlist` value. * `'none'`: The feature is disabled in top-level and nested browsing contexts. * <origin(s)>: The feature is allowed for specific origins (for example, `https://example.com`). Origins should be separated by a space. The values `*` (enable for all origins) or `'none'` (disable for all origins) may only be used alone, while `'self'` and `'src'` may be used with one or more origins. Features have a *default* allowlist, which is one of: `*`, `'self'`, or `'none'`. Directives ---------- [`accelerometer`](feature-policy/accelerometer) Experimental Controls whether the current document is allowed to gather information about the acceleration of the device through the [`Accelerometer`](https://developer.mozilla.org/en-US/docs/Web/API/Accelerometer) interface. [`ambient-light-sensor`](feature-policy/ambient-light-sensor) Experimental Controls whether the current document is allowed to gather information about the amount of light in the environment around the device through the [`AmbientLightSensor`](https://developer.mozilla.org/en-US/docs/Web/API/AmbientLightSensor) interface. [`autoplay`](feature-policy/autoplay) Experimental Controls whether the current document is allowed to autoplay media requested through the [`HTMLMediaElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement) interface. When this policy is disabled and there were no user gestures, the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) returned by [`HTMLMediaElement.play()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) will reject with a [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException). The autoplay attribute on [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) and [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) elements will be ignored. [`battery`](feature-policy/battery) Experimental Controls whether the use of the [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API) is allowed. When this policy is disabled, the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) returned by [`Navigator.getBattery()`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getBattery) will reject with a `NotAllowedError` [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException). [`camera`](feature-policy/camera) Controls whether the current document is allowed to use video input devices. When this policy is disabled, the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) returned by [`getUserMedia()`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) will reject with a `NotAllowedError` [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException). [`display-capture`](feature-policy/display-capture) Controls whether or not the current document is permitted to use the [`getDisplayMedia()`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia) method to capture screen contents. When this policy is disabled, the promise returned by `getDisplayMedia()` will reject with a `NotAllowedError` if permission is not obtained to capture the display's contents. [`document-domain`](feature-policy/document-domain) Experimental Controls whether the current document is allowed to set [`document.domain`](https://developer.mozilla.org/en-US/docs/Web/API/Document/domain). When this policy is disabled, attempting to set [`document.domain`](https://developer.mozilla.org/en-US/docs/Web/API/Document/domain) will fail and cause a `SecurityError` [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) to be thrown. [`encrypted-media`](feature-policy/encrypted-media) Experimental Controls whether the current document is allowed to use the [Encrypted Media Extensions](https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API) API (EME). When this policy is disabled, the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) returned by [`Navigator.requestMediaKeySystemAccess()`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess) will reject with a [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException). [`execution-while-not-rendered`](feature-policy/execution-while-not-rendered) Controls whether tasks should execute in frames while they're not being rendered (e.g. if an iframe is [`hidden`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden) or `display: none`). [`execution-while-out-of-viewport`](feature-policy/execution-while-out-of-viewport) Controls whether tasks should execute in frames while they're outside of the visible viewport. [`fullscreen`](feature-policy/fullscreen) Controls whether the current document is allowed to use [`Element.requestFullscreen()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen). When this policy is disabled, the returned [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) rejects with a [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError). [`gamepad`](feature-policy/gamepad) Experimental Controls whether the current document is allowed to use the [Gamepad API](https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API). When this policy is disabled, calls to [`Navigator.getGamepads()`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getGamepads) will throw a `SecurityError` [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException), and the [`gamepadconnected`](https://developer.mozilla.org/en-US/docs/Web/API/Window/gamepadconnected_event) and [`gamepaddisconnected`](https://developer.mozilla.org/en-US/docs/Web/API/Window/gamepaddisconnected_event) events will not fire. [`geolocation`](feature-policy/geolocation) Controls whether the current document is allowed to use the [`Geolocation`](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation) Interface. When this policy is disabled, calls to [`getCurrentPosition()`](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) and [`watchPosition()`](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition) will cause those functions' callbacks to be invoked with a [`GeolocationPositionError`](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError) code of `PERMISSION_DENIED`. [`gyroscope`](feature-policy/gyroscope) Experimental Controls whether the current document is allowed to gather information about the orientation of the device through the [`Gyroscope`](https://developer.mozilla.org/en-US/docs/Web/API/Gyroscope) interface. [`layout-animations`](feature-policy/layout-animations) Experimental Non-standard Controls whether the current document is allowed to show layout animations. [`legacy-image-formats`](feature-policy/legacy-image-formats) Experimental Non-standard Controls whether the current document is allowed to display images in legacy formats. [`magnetometer`](feature-policy/magnetometer) Experimental Controls whether the current document is allowed to gather information about the orientation of the device through the [`Magnetometer`](https://developer.mozilla.org/en-US/docs/Web/API/Magnetometer) interface. [`microphone`](feature-policy/microphone) Controls whether the current document is allowed to use audio input devices. When this policy is disabled, the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) returned by [`MediaDevices.getUserMedia()`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) will reject with a `NotAllowedError` [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException). [`midi`](feature-policy/midi) Experimental Controls whether the current document is allowed to use the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). When this policy is disabled, the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) returned by [`Navigator.requestMIDIAccess()`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMIDIAccess) will reject with a [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException). [`navigation-override`](feature-policy/navigation-override) Controls the availability of mechanisms that enables the page author to take control over the behavior of [spatial navigation](https://www.w3.org/TR/css-nav/), or to cancel it outright. [`oversized-images`](feature-policy/oversized-images) Experimental Non-standard Controls whether the current document is allowed to download and display large images. [`payment`](feature-policy/payment) Experimental Controls whether the current document is allowed to use the [Payment Request API](https://developer.mozilla.org/en-US/docs/Web/API/Payment_Request_API). When this policy is enabled, the [`PaymentRequest()`](https://developer.mozilla.org/en-US/docs/Web/API/PaymentRequest) constructor will throw a `SecurityError` [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException). [`picture-in-picture`](feature-policy/picture-in-picture) Experimental Controls whether the current document is allowed to play a video in a Picture-in-Picture mode via the corresponding API. [`publickey-credentials-get`](feature-policy/publickey-credentials-get) Experimental Controls whether the current document is allowed to use the [Web Authentication API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API) to retrieve already stored public-key credentials, i.e. via [`navigator.credentials.get({publicKey: ..., ...})`](https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get). [`speaker-selection`](feature-policy/speaker-selection) Experimental Controls whether the current document is allowed to use the [Audio Output Devices API](https://developer.mozilla.org/en-US/docs/Web/API/Audio_Output_Devices_API) to list and select speakers. [`sync-xhr`](feature-policy/sync-xhr) Experimental Non-standard Controls whether the current document is allowed to make synchronous [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) requests. [`unoptimized-images`](feature-policy/unoptimized-images) Experimental Non-standard Controls whether the current document is allowed to download and display unoptimized images. [`unsized-media`](feature-policy/unsized-media) Experimental Non-standard Controls whether the current document is allowed to change the size of media elements after the initial layout is complete. [`usb`](feature-policy/usb) Experimental Controls whether the current document is allowed to use the [WebUSB API](https://wicg.github.io/webusb/). [`screen-wake-lock`](feature-policy/screen-wake-lock) Experimental Controls whether the current document is allowed to use [Screen Wake Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API) to indicate that device should not turn off or dim the screen. [`web-share`](feature-policy/web-share) Experimental Controls whether or not the current document is allowed to use the [`Navigator.share()`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share) of Web Share API to share text, links, images, and other content to arbitrary destinations of user's choice, e.g. mobile apps. [`xr-spatial-tracking`](feature-policy/xr-spatial-tracking) Experimental Controls whether or not the current document is allowed to use the [WebXR Device API](https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API) to interact with a WebXR session. Example ------- SecureCorp Inc. wants to disable Microphone and Geolocation APIs in its application. It can do so by delivering the following HTTP response header to define a feature policy: ``` Feature-Policy: microphone 'none'; geolocation 'none' ``` By specifying the `'none'` keyword for the origin list, the specified features will be disabled for all browsing contexts (this includes all iframes), regardless of their origin. Specifications -------------- | Specification | | --- | | [Permissions Policy # permissions-policy-http-header-field](https://w3c.github.io/webappsec-permissions-policy/#permissions-policy-http-header-field) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Feature-Policy` | 60 | 79 | 74 Only supported through the `allow` attribute on `<iframe>` elements. | No | 47 | 11.1 Only supported through the `allow` attribute on `<iframe>` elements. | 60 | 60 | 79 Only supported through the `allow` attribute on `<iframe>` elements. | 44 | 11.3 Only supported through the `allow` attribute on `<iframe>` elements. | 8.0 | | `accelerometer` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 | | `ambient-light-sensor` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 | | `autoplay` | 64 | 79 | 74 | No | 51 | No | 64 | 64 | No | 47 | No | 9.0 | | `battery` | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | No | No | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | No | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | No | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | No | No Will be implemented, see [bug 1007264](https://crbug.com/1007264). | | `camera` | 60 | 79 | 74 Only supported through the `allow` attribute on `<iframe>` elements. | No | 48 | 11.1 | 60 | 60 | 79 Only supported through the `allow` attribute on `<iframe>` elements. | 45 | 11.3 | 8.0 | | `display-capture` | 94 | 94 | 74 Only supported through the `allow` attribute on `<iframe>` elements. | No | 80 | 13 Only supported through the `allow` attribute on `<iframe>` elements. | No | No | No | No | No | No | | `document-domain` | 77 | 79 | 74 | No | 64 | No | No | No | No | No | No | No | | `encrypted-media` | 60 | 79 | 74 | No | 48 | No | 60 | 60 | No | 45 | No | 8.0 | | `fullscreen` | 62 | 79 | 74 ["Only supported through the `allow` attribute on `<iframe>` elements.", "Before Firefox 80, applying `fullscreen` to an `<iframe>` (i.e. via the `allow` attribute) does not work unless the `allowfullscreen` attribute is also present."] | No | 49 | No | 62 | 62 | 79 ["Only supported through the `allow` attribute on `<iframe>` elements.", "Before Firefox 80, applying `fullscreen` to an `<iframe>` (i.e. via the `allow` attribute) does not work unless the `allowfullscreen` attribute is also present."] | 46 | No | 8.0 | | `gamepad` | 86 | 86 | 91 ["Only supported through the `allow` attribute on `<iframe>` elements.", "The default allowlist is `*` instead of `self` (as required by the specification)."] | No | 72 | No | No | 86 | 91 ["Only supported through the `allow` attribute on `<iframe>` elements.", "The default allowlist is `*` instead of `self` (as required by the specification)."] | No | No | No | | `geolocation` | 60 | 79 | 74 Only supported through the `allow` attribute on `<iframe>` elements. | No | 47 | No | 60 | 60 | 79 Only supported through the `allow` attribute on `<iframe>` elements. | 44 | No | 8.0 | | `gyroscope` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 | | `layout-animations` | No | No | No | No | No | No | No | No | No | No | No | No | | `legacy-image-formats` | No | No | No | No | No | No | No | No | No | No | No | No | | `magnetometer` | 67 | 79 | No | No | 54 | No | No | 67 | No | 48 | No | 9.0 | | `microphone` | 60 | 79 | 74 Only supported through the `allow` attribute on `<iframe>` elements. | No | 48 | 11.1 | 60 | 60 | 79 Only supported through the `allow` attribute on `<iframe>` elements. | 45 | 11.3 | 8.0 | | `midi` | 60 | 79 | 74 | No | 47 | No | 60 | 60 | No | 44 | No | 8.0 | | `oversized-images` | No | No | No | No | No | No | No | No | No | No | No | No | | `payment` | 60 | 79 | 74 | No | 47 | No | 60 | 60 | No | 44 | No | 8.0 | | `picture-in-picture` | 71 | No | No | No | No | No | No | No | No | No | No | No | | `publickey-credentials-get` | 84 | 84 | No | No | No | No | 84 | 84 | No | No | No | 14.0 | | `screen-wake-lock` | No | No | No | No | No | No | No | No | No | No | No | No | | `speaker-selection` | No | No | 92 Only supported through the `allow` attribute on `<iframe>` elements. | No | No | No | No | No | No | No | No | No | | `sync-xhr` | 65 | 79 | No | No | 52 | No | 65 | 65 | No | 47 | No | 9.0 | | `unoptimized-images` | No | No | No | No | No | No | No | No | No | No | No | No | | `unsized-media` | No | No | No | No | No | No | No | No | No | No | No | No | | `usb` | 60 | 79 | No | No | 47 | No | No | 60 | No | 44 | No | 8.0 | | `web-share` | No | No | 81 ["Only supported through the `allow` attribute on `<iframe>` elements.", "Firefox recognizes the `web-share` permissions policy, but this has no effect in versions of Firefox that do not support the [`share()`](https://developer.mozilla.org/docs/Web/API/Navigator/share) method."] | No | No | No | No | No | 81 Only supported through the `allow` attribute on `<iframe>` elements. | No | No | No | | `xr-spatial-tracking` | 79 | 79 | No | No | 66 | No | No | 79 | No | No | No | 12.0 | See also -------- * [Feature Policy](../feature_policy) * [Using Feature Policy](../feature_policy/using_feature_policy) * [`Document.featurePolicy`](https://developer.mozilla.org/en-US/docs/Web/API/Document/featurePolicy) and [`FeaturePolicy`](https://developer.mozilla.org/en-US/docs/Web/API/FeaturePolicy) * [Feature-Policy Tester (Chrome Developer Tools extension)](https://chrome.google.com/webstore/detail/feature-policy-tester-dev/pchamnkhkeokbpahnocjaeednpbpacop) * [`Content-Security-Policy`](content-security-policy) * [`Referrer-Policy`](referrer-policy)
programming_docs
http Pragma Pragma ====== Pragma ====== **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. The `Pragma` HTTP/1.0 general header is an implementation-specific header that may have various effects along the request-response chain. This header serves for backwards compatibility with the HTTP/1.0 caches that do not have a [`Cache-Control`](cache-control) HTTP/1.1 header. **Note:** `Pragma` is not specified for HTTP responses and is therefore not a reliable replacement for the general HTTP/1.1 `Cache-Control` header, although its behavior is the same as `Cache-Control: no-cache` if the `Cache-Control` header field is omitted in a request. Use `Pragma` only for backwards compatibility with HTTP/1.0 clients. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) (response behavior is not specified and thus implementation-specific). | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [CORS-safelisted response header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header) | yes | Syntax ------ ``` Pragma: no-cache ``` Directives ---------- no-cache Same as `Cache-Control: no-cache`. Forces caches to submit the request to the origin server for validation before a cached copy is released. Examples -------- ``` Pragma: no-cache ``` Specifications -------------- | Specification | | --- | | [HTTP Caching # field.pragma](https://httpwg.org/specs/rfc9111.html#field.pragma) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Pragma` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Cache-Control`](cache-control) * [`Expires`](expires) http Timing-Allow-Origin Timing-Allow-Origin =================== Timing-Allow-Origin =================== The `Timing-Allow-Origin` response header specifies origins that are allowed to see values of attributes retrieved via features of the [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/Resource_Timing_API), which would otherwise be reported as zero due to cross-origin restrictions. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Timing-Allow-Origin: \* Timing-Allow-Origin: <origin>[, <origin>]\* ``` Directives ---------- `*` The server may specify "\*" as a wildcard, thereby allowing any origin to see timing resources. <origin> Specifies a URI that may see the timing resources. You can specify multiple origins, separated by commas. Examples -------- To allow any resource to see timing resources: ``` Timing-Allow-Origin: \* ``` To allow `https://developer.mozilla.org` to see timing resources, you can specify: ``` Timing-Allow-Origin: https://developer.mozilla.org ``` Specifications -------------- | Specification | | --- | | [Resource Timing # sec-timing-allow-origin](https://w3c.github.io/resource-timing/#sec-timing-allow-origin) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Timing-Allow-Origin` | Yes | ≤79 | Yes | No | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/Resource_Timing_API) * [Using the Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/Resource_Timing_API/Using_the_Resource_Timing_API) * [`Vary`](vary) http Set-Cookie Set-Cookie ========== Set-Cookie ========== The `Set-Cookie` HTTP response header is used to send a cookie from the server to the user agent, so that the user agent can send it back to the server later. To send multiple cookies, multiple `Set-Cookie` headers should be sent in the same response. **Warning:** Browsers block frontend JavaScript code from accessing the `Set-Cookie` header, as required by the Fetch spec, which defines `Set-Cookie` as a [forbidden response-header name](https://fetch.spec.whatwg.org/#forbidden-response-header-name) that [must be filtered out](https://fetch.spec.whatwg.org/#ref-for-forbidden-response-header-name%E2%91%A0) from any response exposed to frontend code. For more information, see the guide on [Using HTTP cookies](../cookies). | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [Forbidden response header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_response_header_name) | yes | Syntax ------ ``` Set-Cookie: <cookie-name>=<cookie-value> Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date> Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<number> Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value> Set-Cookie: <cookie-name>=<cookie-value>; Path=<path-value> Set-Cookie: <cookie-name>=<cookie-value>; Secure Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Strict Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Lax Set-Cookie: <cookie-name>=<cookie-value>; SameSite=None; Secure // Multiple attributes are also possible, for example: Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly ``` Attributes ---------- `<cookie-name>=<cookie-value>` Defines the cookie name and its value. A cookie definition begins with a name-value pair. A `<cookie-name>` can contain any US-ASCII characters except for: the control character, space, or a tab. It also must not contain separator characters like the following: `( ) < > @ , ; : \ " / [ ] ? = { }`. A `<cookie-value>` can optionally be wrapped in double quotes and include any US-ASCII character excluding a control character, [Whitespace](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace), double quotes, comma, semicolon, and backslash. **Encoding**: Many implementations perform URL encoding on cookie values. However, this is not required by the RFC specification. The URL encoding does help to satisfy the requirements of the characters allowed for `<cookie-value>`. **Note:** Some `<cookie-name>` have a specific semantic: `__Secure-`: Cookies with names starting with `__Secure-` (dash is part of the prefix) must be set with the `secure` flag from a secure page (HTTPS). `__Host-`: Cookies with names starting with `__Host-` must be set with the `secure` flag, must be from a secure page (HTTPS), must not have a domain specified (and therefore, are not sent to subdomains), and the path must be `/`. `Expires=<date>` Optional Indicates the maximum lifetime of the cookie as an HTTP-date timestamp. See [`Date`](date) for the required formatting. If unspecified, the cookie becomes a **session cookie**. A session finishes when the client shuts down, after which the session cookie is removed. **Warning:** Many web browsers have a *session restore* feature that will save all tabs and restore them the next time the browser is used. Session cookies will also be restored, as if the browser was never closed. When an `Expires` date is set, the deadline is relative to the *client* the cookie is being set on, not the server. `Max-Age=<number>` Optional Indicates the number of seconds until the cookie expires. A zero or negative number will expire the cookie immediately. If both `Expires` and `Max-Age` are set, `Max-Age` has precedence. `Domain=<domain-value>` Optional Defines the host to which the cookie will be sent. If omitted, this attribute defaults to the host of the current document URL, not including subdomains. Contrary to earlier specifications, leading dots in domain names (`.example.com`) are ignored. Multiple host/domain values are *not* allowed, but if a domain *is* specified, then subdomains are always included. `Path=<path-value>` Optional Indicates the path that *must* exist in the requested URL for the browser to send the `Cookie` header. The forward slash (`/`) character is interpreted as a directory separator, and subdirectories are matched as well. For example, for `Path=/docs`, * the request paths `/docs`, `/docs/`, `/docs/Web/`, and `/docs/Web/HTTP` will all match. * the request paths `/`, `/docsets`, `/fr/docs` will not match. `Secure` Optional Indicates that the cookie is sent to the server only when a request is made with the `https:` scheme (except on localhost), and therefore, is more resistant to [man-in-the-middle](https://developer.mozilla.org/en-US/docs/Glossary/MitM) attacks. **Note:** Do not assume that `Secure` prevents all access to sensitive information in cookies (session keys, login details, etc.). Cookies with this attribute can still be read/modified either with access to the client's hard disk or from JavaScript if the `HttpOnly` cookie attribute is not set. Insecure sites (`http:`) cannot set cookies with the `Secure` attribute (since Chrome 52 and Firefox 52). For Firefox, the `https:` requirements are ignored when the `Secure` attribute is set by localhost (since Firefox 75). `HttpOnly` Optional Forbids JavaScript from accessing the cookie, for example, through the [`Document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) property. Note that a cookie that has been created with `HttpOnly` will still be sent with JavaScript-initiated requests, for example, when calling [`XMLHttpRequest.send()`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send) or [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch). This mitigates attacks against cross-site scripting ([XSS](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting)). `SameSite=<samesite-value>` Optional Controls whether or not a cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks ([CSRF](https://developer.mozilla.org/en-US/docs/Glossary/CSRF)). The possible attribute values are: `Strict` means that the browser sends the cookie only for same-site requests, that is, requests originating from the same site that set the cookie. If a request originates from a different domain or scheme (even with the same domain), no cookies with the `SameSite=Strict` attribute are sent. `Lax` means that the cookie is not sent on cross-site requests, such as on requests to load images or frames, but is sent when a user is navigating to the origin site from an external site (for example, when following a link). This is the default behavior if the `SameSite` attribute is not specified. `None` means that the browser sends the cookie with both cross-site and same-site requests. The `Secure` attribute must also be set when setting this value, like so `SameSite=None; Secure` **Note:** Standards related to the [SameSite Cookies](set-cookie/samesite) recently changed, such that: 1. The cookie-sending behavior if `SameSite` is not specified is `SameSite=Lax`. Previously, cookies were sent for all requests by default. 2. Cookies with `SameSite=None` must now also specify the `Secure` attribute (in other words, they require a secure context). 3. Cookies from the same domain are no longer considered to be from the same site if sent using a different scheme (`http:` or `https:`). See the [Browser compatibility](set-cookie/samesite#browser_compatibility) table for information about specific browser implementation (rows: "`SameSite`: Defaults to `Lax`", "`SameSite`: Secure context required", and "`SameSite`: URL scheme-aware ("schemeful")"). Examples -------- ### Session cookie **Session cookies** are removed when the client shuts down. Cookies are session cookies if they do not specify the `Expires` or `Max-Age` attribute. ``` Set-Cookie: sessionId=38afes7a8 ``` ### Permanent cookie **Permanent cookies** are removed at a specific date (`Expires`) or after a specific length of time (`Max-Age`) and not when the client is closed. ``` Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT ``` ``` Set-Cookie: id=a3fWa; Max-Age=2592000 ``` ### Invalid domains A cookie for a domain that does not include the server that set it [should be rejected by the user agent](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.2.3). The following cookie will be rejected if set by a server hosted on `originalcompany.com`: ``` Set-Cookie: qwerty=219ffwef9w0f; Domain=somecompany.co.uk ``` A cookie for a subdomain of the serving domain will be rejected. The following cookie will be rejected if set by a server hosted on `example.com`: ``` Set-Cookie: sessionId=e8bb43229de9; Domain=foo.example.com ``` ### Cookie prefixes Cookie names prefixed with `__Secure-` or `__Host-` can be used only if they are set with the `secure` attribute from a secure (HTTPS) origin. In addition, cookies with the `__Host-` prefix must have a path of `/` (meaning any path at the host) and must not have a `Domain` attribute. **Warning:** For clients that don't implement cookie prefixes, you cannot count on these additional assurances, and prefixed cookies will always be accepted. ``` // Both accepted when from a secure origin (HTTPS) Set-Cookie: \_\_Secure-ID=123; Secure; Domain=example.com Set-Cookie: \_\_Host-ID=123; Secure; Path=/ // Rejected due to missing Secure attribute Set-Cookie: \_\_Secure-id=1 // Rejected due to the missing Path=/ attribute Set-Cookie: \_\_Host-id=1; Secure // Rejected due to setting a Domain Set-Cookie: \_\_Host-id=1; Secure; Path=/; Domain=example.com ``` Specifications -------------- | Specification | | --- | | [HTTP State Management Mechanism # sane-set-cookie](https://httpwg.org/specs/rfc6265.html#sane-set-cookie) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `HttpOnly` | 1 | 12 | 3 | 9 | 11 | 5 | 37 | Yes | 4 | Yes | 4 | Yes | | `Max-Age` | Yes | 12 | Yes | 8 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `SameSite` | 51 | 16 | 60 | 11 | 39 | 13 Safari 13 on macOS 10.14 (Mojave), treats `SameSite=None` and invalid values as `Strict`. This is fixed in version 10.15 (Catalina) and later. 12 Treats `SameSite=None` and invalid values as `Strict` in macOS before 10.15 Catalina. See [bug 198181](https://webkit.org/b/198181). | 51 | 51 | 60 | 41 | 13 12.2 Treats `SameSite=None` and invalid values as `Strict` in iOS before 13. See [bug 198181](https://webkit.org/b/198181). | 5.0 | | `Set-Cookie` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `cookie_prefixes` | 49 | 79 | 50 | No | 36 | Yes | 49 | 49 | 50 | 36 | Yes | 5.0 | ### Compatibility notes * Starting with Chrome 52 and Firefox 52, insecure sites (`http:`) can't set cookies with the `Secure` attribute anymore. See also -------- * [HTTP cookies](../cookies) * [`Cookie`](cookie) * [`Document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) * [SameSite cookies](set-cookie/samesite) http Expect-CT Expect-CT ========= Expect-CT ========= **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. The `Expect-CT` header lets sites opt in to reporting and/or enforcement of [Certificate Transparency](https://developer.mozilla.org/en-US/docs/Web/Security/Certificate_Transparency) requirements. Certificate Transparency (CT) aims to prevent the use of misissued certificates for that site from going unnoticed. Only Google Chrome and other Chromium-based browsers implemented `Expect-CT`, and Chromium has deprecated the header from version 107, because Chromium now enforces CT by default. See the [Chrome Platform Status](https://chromestatus.com/feature/6244547273687040) update. CT requirements can be satisfied via any one of the following mechanisms: * X.509v3 certificate extension to allow embedding of signed certificate timestamps issued by individual logs. Most TLS certificates issued by publicly-trusted CAs and used online contain embedded CT. * A TLS extension of type `signed_certificate_timestamp` sent during the handshake * Supporting OCSP stapling (that is, the `status_request` TLS extension) and providing a `SignedCertificateTimestampList` **Note:** When a site enables the `Expect-CT` header, they are requesting that the browser check that any certificate for that site appears in **[public CT logs](https://github.com/google/certificate-transparency-community-site/blob/master/docs/google/known-logs.md)**. **Note:** Browsers **ignore** the `Expect-CT` header over HTTP; the header only has effect on HTTPS connections. **Note:** The `Expect-CT` is mostly obsolete since June 2021. Since May 2018, all new TLS certificates are expected to support SCTs by default. Certificates issued before March 2018 were allowed to have a lifetime of 39 months, so they had expired in June 2021. Chromium plans to deprecate `Expect-CT` header and to eventually remove it. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Expect-CT: report-uri="<uri>", enforce, max-age=<age> ``` Directives ---------- `max-age` The number of seconds after reception of the `Expect-CT` header field during which the user agent should regard the host of the received message as a known `Expect-CT` host. If a cache receives a value greater than it can represent, or if any of its subsequent calculations overflows, the cache will consider this value to be either 2,147,483,648 (2^31) or the greatest positive integer it can represent. `report-uri="<uri>"` Optional The URI where the user agent should report `Expect-CT` failures. When present with the `enforce` directive, the configuration is referred to as an "enforce-and-report" configuration, signalling to the user agent both that compliance to the Certificate Transparency policy should be enforced *and* that violations should be reported. `enforce` Optional Signals to the user agent that compliance with the Certificate Transparency policy should be enforced (rather than only reporting compliance) and that the user agent should refuse future connections that violate its Certificate Transparency policy. When both the `enforce` directive and the `report-uri` directive are present, the configuration is referred to as an "enforce-and-report" configuration, signalling to the user agent both that compliance to the Certificate Transparency policy should be enforced and that violations should be reported. Example ------- The following example specifies enforcement of Certificate Transparency for 24 hours and reports violations to `foo.example.com`. ``` Expect-CT: max-age=86400, enforce, report-uri="https://foo.example.com/report" ``` Notes ----- Root CAs manually added to the trust store override and suppress `Expect-CT` reports/enforcement. Browsers will not remember an `Expect-CT` policy, unless the site has 'proven' it can serve a certificate satisfying the certificate transparency requirements. Browsers implement their own trust model regarding which CT logs are considered trusted for the certificate to have been logged to. Builds of Chrome are designed to stop enforcing the `Expect-CT` policy 10 weeks after the installation's build date. Specifications -------------- | Specification | | --- | | [Expect-CT # section-2.1](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-expect-ct-08#section-2.1) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Expect-CT` | 61 Before later builds of Chrome 64, invalid Expect-CT reports would be sent. Newer versions do not send reports after 10 weeks from the build date. See [bug 786563](https://crbug.com/786563). | ≤79 | No See [bug 1281469](https://bugzil.la/1281469). | No | 48 | No | No | 61 Before later builds of Chrome 64, invalid Expect-CT reports would be sent. Newer versions do not send reports after 10 weeks from the build date. See [bug 786563](https://crbug.com/786563). | No See [bug 1281469](https://bugzil.la/1281469). | 45 Before later builds of Opera 47, invalid Expect-CT reports would be sent. Newer versions do not send reports after 10 weeks from the build date. See [bug 786563](https://crbug.com/786563). | No | 8.0 Before later builds of Samsung Internet 9.0, invalid Expect-CT reports would be sent. Newer versions do not send reports after 10 weeks from the build date. See [bug 786563](https://crbug.com/786563). |
programming_docs
http If-Range If-Range ======== If-Range ======== The `If-Range` HTTP request header makes a range request conditional: if the condition is fulfilled, the range request is issued, and the server sends back a [`206`](../status/206) `Partial Content` answer with the appropriate body. If the condition is not fulfilled, the full resource is sent back with a [`200`](../status/200) `OK` status. This header can be used either with the [`Last-Modified`](last-modified) validator or with [`ETag`](etag), but not with both. The most common use case is to resume a download, to guarantee that the stored resource has not been modified since the last fragment has been received. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` If-Range: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT If-Range: <etag> ``` Directives ---------- <etag> An entity tag uniquely representing the requested resource. It is a string of ASCII characters placed between double quotes (Like `"675af34563dc-tr34"`). A weak entity tag (one prefixed by `W/`) must not be used in this header. <day-name> One of "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", or "Sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". <month> One of "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" (case-sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <hour> 2 digit hour number, e.g. "09" or "23". <minute> 2 digit minute number, e.g. "04" or "59". <second> 2 digit second number, e.g. "04" or "59". `GMT` Greenwich Mean Time. HTTP dates are always expressed in GMT, never in local time. Examples -------- ``` If-Range: Wed, 21 Oct 2015 07:28:00 GMT ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.if-range](https://httpwg.org/specs/rfc9110.html#field.if-range) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `If-Range` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`ETag`](etag) * [`Last-Modified`](last-modified) * [`If-Modified-Since`](if-modified-since) * [`If-Unmodified-Since`](if-unmodified-since) * [`If-Match`](if-match) * [`If-None-Match`](if-none-match) * [`206 Partial Content`](../status/206) * [HTTP Conditional Requests](../conditional_requests) http X-Forwarded-Proto X-Forwarded-Proto ================= X-Forwarded-Proto ================= The `X-Forwarded-Proto` (XFP) header is a de-facto standard header for identifying the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer. Your server access logs contain the protocol used between the server and the load balancer, but not the protocol used between the client and the load balancer. To determine the protocol used between the client and the load balancer, the `X-Forwarded-Proto` request header can be used. A standardized version of this header is the HTTP [`Forwarded`](forwarded) header. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` X-Forwarded-Proto: <protocol> ``` Directives ---------- <protocol> The forwarded protocol (http or https). Examples -------- ``` X-Forwarded-Proto: https ``` Other non-standard forms: ``` # Microsoft Front-End-Https: on X-Forwarded-Protocol: https X-Forwarded-Ssl: on X-Url-Scheme: https ``` Specifications -------------- Not part of any current specification. The standardized version of this header is [`Forwarded`](forwarded). See also -------- * [`Forwarded`](forwarded) * [`X-Forwarded-For`](x-forwarded-for) * [`X-Forwarded-Host`](x-forwarded-host) http Expect Expect ====== Expect ====== The `Expect` HTTP request header indicates expectations that need to be met by the server to handle the request successfully. Upon `Expect: 100-continue`, the server responds with: * [`100`](../status/100) (Continue) if the information from the request header is insufficient to resolve the response and the client should proceed with sending the body. * [`417`](../status/417) (Expectation Failed) if the server cannot meet the expectation or any other status otherwise (e.g. a 4xx status for a client error, or a 2xx status if the request can be resolved successfully without further processing). For example, the server may reject a request if its [`Content-Length`](content-length) is too large. No common browsers send the `Expect` header, but some other clients such as cURL do so by default. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Expect: 100-continue ``` Directives ---------- There is only one defined expectation: `100-continue` Informs recipients that the client is about to send a (presumably large) message body in this request and wishes to receive a [`100`](../status/100) (Continue) interim response. Examples -------- ### Large message body A client sends a request with `Expect` header and waits for the server to respond before sending the message body. ``` PUT /somewhere/fun HTTP/1.1 Host: origin.example.com Content-Type: video/h264 Content-Length: 1234567890987 Expect: 100-continue ``` The server checks the headers and generates the response. The server sends [`100`](../status/100) (Continue), which instructs the client to send the message body. Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.expect](https://httpwg.org/specs/rfc9110.html#field.expect) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Expect` | No | No | No | No | No | No | No | No | No | No | No | No | See also -------- * [`417 Expectation Failed`](../status/417) * [`100 Continue`](../status/100) http Content-Security-Policy-Report-Only Content-Security-Policy-Report-Only =================================== Content-Security-Policy-Report-Only =================================== The HTTP `Content-Security-Policy-Report-Only` response header allows web developers to experiment with policies by monitoring (but not enforcing) their effects. These violation reports consist of [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON) documents sent via an HTTP `POST` request to the specified URI. For more information, see also this article on [Content Security Policy (CSP)](../csp). | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | This header is not supported inside a [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) element. | Syntax ------ ``` Content-Security-Policy-Report-Only: <policy-directive>; <policy-directive> ``` Directives ---------- The directives of the [`Content-Security-Policy`](content-security-policy) header can also be applied to `Content-Security-Policy-Report-Only`. The CSP [`report-uri`](content-security-policy/report-uri) directive should be used with this header, otherwise this header will be an expensive no-op machine. Examples -------- This header reports violations that would have occurred. You can use this to iteratively work on your content security policy. You observe how your site behaves, watching for violation reports, or [malware redirects](https://secure.wphackedhelp.com/blog/wordpress-malware-redirect-hack-cleanup/), then choose the desired policy enforced by the [`Content-Security-Policy`](content-security-policy) header. ``` Content-Security-Policy-Report-Only: default-src https:; report-uri /csp-violation-report-endpoint/ ``` If you still want to receive reporting, but also want to enforce a policy, use the [`Content-Security-Policy`](content-security-policy) header with the [`report-uri`](content-security-policy/report-uri) directive. ``` Content-Security-Policy: default-src https:; report-uri /csp-violation-report-endpoint/ ``` Violation report syntax ----------------------- The report JSON object contains the following data: `blocked-uri` The URI of the resource that was blocked from loading by the Content Security Policy. If the blocked URI is from a different origin than the document-uri, then the blocked URI is truncated to contain just the scheme, host, and port. `disposition` Either `"enforce"` or `"report"` depending on whether the [`Content-Security-Policy`](content-security-policy) header or the `Content-Security-Policy-Report-Only` header is used. `document-uri` The URI of the document in which the violation occurred. `effective-directive` The directive whose enforcement caused the violation. `original-policy` The original policy as specified by the `Content-Security-Policy-Report-Only` HTTP header. `referrer` The referrer of the document in which the violation occurred. `script-sample` The first 40 characters of the inline script, event handler, or style that caused the violation. `status-code` The HTTP status code of the resource on which the global object was instantiated. `violated-directive` The name of the policy section that was violated. Sample violation report ----------------------- Let's consider a page located at `http://example.com/signup.html`. It uses the following policy, disallowing everything but stylesheets from `cdn.example.com`. ``` Content-Security-Policy-Report-Only: default-src 'none'; style-src cdn.example.com; report-uri /\_/csp-reports ``` The HTML of `signup.html` looks like this: ``` <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>Sign Up</title> <link rel="stylesheet" href="css/style.css" /> </head> <body> Page content </body> </html> ``` Can you spot the violation? Stylesheets are only allowed to be loaded from `cdn.example.com`, yet the website tries to load one from its own origin (`http://example.com`). A browser capable of enforcing CSP will send the following violation report as a POST request to `http://example.com/_/csp-reports`, when the document is visited: ``` { "csp-report": { "document-uri": "http://example.com/signup.html", "referrer": "", "blocked-uri": "http://example.com/css/style.css", "violated-directive": "style-src cdn.example.com", "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri /\_/csp-reports", "disposition": "report" } } ``` As you can see, the report includes the full path to the violating resource in `blocked-uri`. This is not always the case. For example, when the `signup.html` would attempt to load CSS from `http://anothercdn.example.com/stylesheet.css`, the browser would *not* include the full path but only the origin (`http://anothercdn.example.com`). This is done to prevent leaking sensitive information about cross-origin resources. Specifications -------------- | Specification | | --- | | [Content Security Policy Level 3 # cspro-header](https://w3c.github.io/webappsec-csp/#cspro-header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Content-Security-Policy-Report-Only` | 25 | 14 | 23 | 10 | 15 | 7 | 4.4 | Yes | 23 | No | 7 | Yes | See also -------- * [`Content-Security-Policy`](content-security-policy) * CSP [`report-uri`](content-security-policy/report-uri) directive http Access-Control-Request-Headers Access-Control-Request-Headers ============================== Access-Control-Request-Headers ============================== The `Access-Control-Request-Headers` request header is used by browsers when issuing a [preflight request](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request) to let the server know which [HTTP headers](../headers) the client might send when the actual request is made (such as with [`setRequestHeader()`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader)). The complementary server-side header of [`Access-Control-Allow-Headers`](access-control-allow-headers) will answer this browser-side header. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Access-Control-Request-Headers: <header-name>, <header-name>, … ``` Directives ---------- <header-name> A comma-delimited list of [HTTP headers](../headers) that are included in the request. Examples -------- ``` Access-Control-Request-Headers: X-PINGOTHER, Content-Type ``` Specifications -------------- | Specification | | --- | | [Fetch Standard # http-access-control-request-headers](https://fetch.spec.whatwg.org/#http-access-control-request-headers) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Access-Control-Request-Headers` | 4 | 12 | 3.5 | 10 | 12 | 4 | 2 | Yes | 4 | 12 | 3.2 | Yes | See also -------- * [`Access-Control-Request-Method`](access-control-request-method) http Service-Worker-Navigation-Preload Service-Worker-Navigation-Preload ================================= Service-Worker-Navigation-Preload ================================= The `Service-Worker-Navigation-Preload` request header indicates that the request was the result of a [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) operation made during service worker navigation preloading. It allows a server to respond with a different resource than for a normal `fetch()`. If a different response may result from setting this header, the server must set `Vary: Service-Worker-Navigation-Preload` to ensure that the different responses are cached. For more information see [`NavigationPreloadManager.setHeaderValue()`](https://developer.mozilla.org/en-US/docs/Web/API/NavigationPreloadManager/setHeaderValue) (and [`NavigationPreloadManager`](https://developer.mozilla.org/en-US/docs/Web/API/NavigationPreloadManager)). | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Service-Worker-Navigation-Preload: <value> ``` Directives ---------- `<value>` An arbitrary value that indicates what data should be sent in the response to the preload request. This defaults to `true`. It maybe set to any other string value in the service worker, using [`NavigationPreloadManager.setHeaderValue()`](https://developer.mozilla.org/en-US/docs/Web/API/NavigationPreloadManager/setHeaderValue). Examples -------- The header below is sent by default. ``` Service-Worker-Navigation-Preload: true ``` The service worker can set a different header value using [`NavigationPreloadManager.setHeaderValue()`](https://developer.mozilla.org/en-US/docs/Web/API/NavigationPreloadManager/setHeaderValue). For example, in order to request that a fragment of the requested resource be returned in JSON format, the value could be set with the string `json_fragment1`. ``` Service-Worker-Navigation-Preload: json\_fragment1 ``` Specifications -------------- | Specification | | --- | | [Service Workers # handle-fetch](https://w3c.github.io/ServiceWorker/#handle-fetch) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Service-Worker-Navigation-Preload` | 59 | 18 | 97 preview | No | 46 | 15.4 | 59 | 59 | No | 43 | 15.4 | 7.0 | http ETag ETag ==== ETag ==== The `ETag` (or **entity tag**) HTTP response header is an identifier for a specific version of a resource. It lets caches be more efficient and save bandwidth, as a web server does not need to resend a full response if the content was not changed. Additionally, etags help to prevent simultaneous updates of a resource from overwriting each other (["mid-air collisions"](#avoiding_mid-air_collisions)). If the resource at a given URL changes, a new `Etag` value *must* be generated. A comparison of them can determine whether two representations of a resource are the same. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` ETag: W/"<etag\_value>" ETag: "<etag\_value>" ``` Directives ---------- `W/` Optional `'W/'` (case-sensitive) indicates that a [weak validator](../conditional_requests#weak_validation) is used. Weak etags are easy to generate, but are far less useful for comparisons. Strong validators are ideal for comparisons but can be very difficult to generate efficiently. Weak `ETag` values of two representations of the same resources might be semantically equivalent, but not byte-for-byte identical. This means weak etags prevent caching when [byte range requests](accept-ranges) are used, but strong etags mean range requests can still be cached. "<etag\_value>" Entity tag that uniquely represents the requested resource. It is a string of ASCII characters placed between double quotes, like `"675af34563dc-tr34"`. The method by which `ETag` values are generated is not specified. Typically, the ETag value is a hash of the content, a hash of the last modification timestamp, or just a revision number. For example, a wiki engine can use a hexadecimal hash of the documentation article content. Examples -------- ``` ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4" ETag: W/"0815" ``` ### Avoiding mid-air collisions With the help of the `ETag` and the [`If-Match`](if-match) headers, you can detect mid-air edit collisions. For example, when editing a wiki, the current wiki content may be hashed and put into an `Etag` header in the response: ``` ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4" ``` When saving changes to a wiki page (posting data), the [`POST`](../methods/post) request will contain the [`If-Match`](if-match) header containing the `ETag` values to check freshness against. ``` If-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4" ``` If the hashes don't match, it means that the document has been edited in-between and a [`412`](../status/412) `Precondition Failed` error is thrown. ### Caching of unchanged resources Another typical use of the `ETag` header is to cache resources that are unchanged. If a user visits a given URL again (that has an `ETag` set), and it is *stale* (too old to be considered usable), the client will send the value of its `ETag` along in an [`If-None-Match`](if-none-match) header field: ``` If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4" ``` The server compares the client's `ETag` (sent with `If-None-Match`) with the `ETag` for its current version of the resource, and if both values match (that is, the resource has not changed), the server sends back a [`304`](../status/304) `Not Modified` status, without a body, which tells the client that the cached version of the response is still good to use (*fresh*). Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.etag](https://httpwg.org/specs/rfc9110.html#field.etag) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `ETag` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`If-Match`](if-match) * [`If-None-Match`](if-none-match) * [`304 Not Modified`](../status/304) * [`Precondition Failed`](../status/412) * [W3C Note: Editing the Web – Detecting the Lost Update Problem Using Unreserved Checkout](https://www.w3.org/1999/04/Editing/)
programming_docs
http Accept-Language Accept-Language =============== Accept-Language =============== The `Accept-Language` request HTTP header indicates the natural language and locale that the client prefers. The server uses [content negotiation](../content_negotiation) to select one of the proposals and informs the client of the choice with the [`Content-Language`](content-language) response header. Browsers set required values for this header according to their active user interface language. Users rarely change it, and such changes are not recommended because they may lead to fingerprinting. This header serves as a hint when the server cannot determine the target content language otherwise (for example, use a specific URL that depends on an explicit user decision). The server should never override an explicit user language choice. The content of `Accept-Language` is often out of a user's control (when traveling, for instance). A user may also want to visit a page in a language different from the user interface language. The server possibly can send back a [`406`](../status/406) (Not Acceptable) error code when unable to serve content in a matching language. However, such a behavior is rarely implemented for a better user experience, and servers often ignore the `Accept-Language` header in such cases. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [CORS-safelisted request header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header) | yes, with the additional restriction that values can only be `0-9`, `A-Z`, `a-z`, space or `*,-.;=`. | Syntax ------ ``` Accept-Language: <language> Accept-Language: \* // Multiple types, weighted with the quality value syntax: Accept-Language: fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, \*;q=0.5 ``` Directives ---------- `<language>` A language tag (which is sometimes referred to as a "locale identifier"). This consists of a 2-3 letter base language tag that indicates a language, optionally followed by additional subtags separated by `'-'`. The most common extra information is the country or region variant (like `'en-US'` or `'fr-CA'`) or the type of alphabet to use (like `'sr-Latn'`). Other variants, like the type of orthography (`'de-DE-1996'`), are usually not used in the context of this header. `*` Any language; `'*'` is used as a wildcard. `;q=` (q-factor weighting) Any value placed in an order of preference expressed using a relative [quality value](https://developer.mozilla.org/en-US/docs/Glossary/Quality_values) called *weight*. Examples -------- ``` Accept-Language: de ``` ``` Accept-Language: de-CH ``` ``` Accept-Language: en-US,en;q=0.5 ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.accept-language](https://httpwg.org/specs/rfc9110.html#field.accept-language) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Accept-Language` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * HTTP [content negotiation](../content_negotiation) * A header with the result of the content negotiation: [`Content-Language`](content-language) * Other similar headers: [`TE`](te), [`Accept-Encoding`](accept-encoding), [`Accept`](accept) http Accept-Encoding Accept-Encoding =============== Accept-Encoding =============== The `Accept-Encoding` request HTTP header indicates the content encoding (usually a compression algorithm) that the client can understand. The server uses [content negotiation](../content_negotiation) to select one of the proposals and informs the client of that choice with the [`Content-Encoding`](content-encoding) response header. Even if both the client and the server support the same compression algorithms, the server may choose not to compress the body of a response if the `identity` value is also acceptable. Two common cases lead to this: * The data to be sent is already compressed, therefore a second compression will not reduce the transmitted data size. This is true for pre-compressed image formats (JPEG, for instance); * The server is overloaded and cannot allocate computing resources to perform the compression. For example, Microsoft recommends not to compress if a server uses more than 80% of its computational power. As long as the `identity;q=0` or `*;q=0` directives do not explicitly forbid the `identity` value that means no encoding, the server must never return a [`406`](../status/406) `Not Acceptable` error. **Note:** * An IANA registry maintains [a complete list of official content encodings](https://www.iana.org/assignments/http-parameters/http-parameters.xml#http-parameters-1). * Two other content encodings, namely `bzip` and `bzip2`, are sometimes used, These non-standard encodings implement the algorithm that these two UNIX programs use. Note that `bzip` was discontinued due to patent licensing issues. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Accept-Encoding: gzip Accept-Encoding: compress Accept-Encoding: deflate Accept-Encoding: br Accept-Encoding: identity Accept-Encoding: \* // Multiple algorithms, weighted with the quality value syntax: Accept-Encoding: deflate, gzip;q=1.0, \*;q=0.5 ``` Directives ---------- `gzip` A compression format that uses the [Lempel-Ziv coding](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ77) (LZ77) with a 32-bit CRC. `compress` A compression format that uses the [Lempel-Ziv-Welch](https://en.wikipedia.org/wiki/LZW) (LZW) algorithm. `deflate` A compression format that uses the [zlib](https://en.wikipedia.org/wiki/Zlib) structure with the [*deflate*](https://en.wikipedia.org/wiki/DEFLATE) compression algorithm. `br` A compression format that uses the [Brotli](https://en.wikipedia.org/wiki/Brotli) algorithm. `identity` Indicates the identity function (that is, without modification or compression). This value is always considered as acceptable, even if omitted. `*` Matches any content encoding not already listed in the header. This is the default value if the header is not present. This directive does not suggest that any algorithm is supported but indicates that no preference is expressed. `;q=` (qvalues weighting) Any value is placed in an order of preference expressed using a relative [quality value](https://developer.mozilla.org/en-US/docs/Glossary/Quality_values) called *weight*. Examples -------- ``` Accept-Encoding: gzip Accept-Encoding: gzip, compress, br Accept-Encoding: br;q=1.0, gzip;q=0.8, \*;q=0.1 ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.accept-encoding](https://httpwg.org/specs/rfc9110.html#field.accept-encoding) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Accept-Encoding` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * HTTP [content negotiation](../content_negotiation) * A header with the result of the content negotiation: [`Content-Encoding`](content-encoding) * Other similar headers: [`TE`](te), [`Accept`](accept), [`Accept-Language`](accept-language) http Content-Range Content-Range ============= Content-Range ============= The `Content-Range` response HTTP header indicates where in a full body message a partial message belongs. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header), [Payload header](https://developer.mozilla.org/en-US/docs/Glossary/Payload_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [CORS-safelisted response-header](https://developer.mozilla.org/en-US/docs/Glossary/Simple_response_header) | no | Syntax ------ ``` Content-Range: <unit> <range-start>-<range-end>/<size> Content-Range: <unit> <range-start>-<range-end>/\* Content-Range: <unit> \*/<size> ``` Directives ---------- <unit> The unit in which ranges are specified. This is usually `bytes`. <range-start> An integer in the given unit indicating the start position (zero-indexed & inclusive) of the request range. <range-end> An integer in the given unit indicating the end position (zero-indexed & inclusive) of the requested range. <size> The total length of the document (or `'*'` if unknown). Examples -------- ``` Content-Range: bytes 200-1000/67589 ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.content-range](https://httpwg.org/specs/rfc9110.html#field.content-range) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Content-Range` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`If-Range`](if-range) * [`Range`](range) * [`Content-Type`](content-type) * [`206`](../status/206) `Partial Content` * [`416`](../status/416) `Range Not Satisfiable` http Content-DPR Content-DPR =========== Content-DPR =========== **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). **Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The `Content-DPR` response header is used to confirm the *image* device to pixel ratio in requests where the screen [`DPR`](dpr) [client hint](../client_hints) was used to select an image resource. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [CORS-safelisted response header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header) | no | If the [`DPR`](dpr) client hint is used to select an image the server must specify `Content-DPR` in the response. If the value in `Content-DPR` is different from the [`DPR`](dpr) value in the request (i.e. image DPR is not the same as screen DPR) then the client must use the `Content-DPR` for determining intrinsic image size and scaling the image. If the `Content-DPR` header appears more than once in a message the last occurrence is used. **Note:** * `Content-DPR` was removed from the client hints specification in [draft-ietf-httpbis-client-hints-07](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-client-hints-07). The [Responsive Image Client Hints](https://wicg.github.io/responsive-image-client-hints/) spec proposes to replace this header by specifying intrinsic resolution/dimensions in EXIF metadata. Syntax ------ ``` Content-DPR: <number> ``` Directives ---------- `<number>` The image device pixel ratio, calculated according to the following formula: Content-DPR = *Selected image resource size* / (*Width* / *DPR*) Examples -------- See the [`DPR`](dpr#examples) header example. Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Content-DPR` | 46 | ≤79 | No | No | 33 | No | 46 | 46 | No | 33 | No | 5.0 | See also -------- * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * Device client hints + [`Device-Memory`](device-memory) + [`DPR`](dpr) + [`Viewport-Width`](viewport-width) + [`Width`](width) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) http Proxy-Authorization Proxy-Authorization =================== Proxy-Authorization =================== The HTTP `Proxy-Authorization` request header contains the credentials to authenticate a user agent to a proxy server, usually after the server has responded with a [`407`](../status/407) `Proxy Authentication Required` status and the [`Proxy-Authenticate`](proxy-authenticate) header. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Proxy-Authorization: <type> <credentials> ``` Directives ---------- <type> [Authentication type](../authentication#authentication_schemes). A common type is ["Basic"](../authentication#basic_authentication_scheme). See also the [IANA registry of Authentication schemes](https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml). <credentials> The credentials are constructed like this: * The username and the password are combined with a colon (`aladdin:opensesame`). * The resulting string is [base64](https://developer.mozilla.org/en-US/docs/Glossary/Base64) encoded (`YWxhZGRpbjpvcGVuc2VzYW1l`). **Note:** Base64 encoding does not mean encryption or hashing! This method is as secure as sending the credentials in clear text (base64 is a reversible encoding). It is preferable to use HTTPS in conjunction with Basic Authentication. Examples -------- ``` Proxy-Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.proxy-authorization](https://httpwg.org/specs/rfc9110.html#field.proxy-authorization) | See also -------- * [HTTP authentication](../authentication) * [`Proxy-Authenticate`](proxy-authenticate) * [`WWW-Authenticate`](www-authenticate) * [`Authorization`](authorization) * [`401`](../status/401), [`403`](../status/403), [`407`](../status/407) http Access-Control-Allow-Credentials Access-Control-Allow-Credentials ================================ Access-Control-Allow-Credentials ================================ The `Access-Control-Allow-Credentials` response header tells browsers whether to expose the response to the frontend JavaScript code when the request's credentials mode ([`Request.credentials`](https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials)) is `include`. When a request's credentials mode ([`Request.credentials`](https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials)) is `include`, browsers will only expose the response to the frontend JavaScript code if the `Access-Control-Allow-Credentials` value is `true`. Credentials are cookies, authorization headers, or TLS client certificates. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. Note that simple [`GET`](../methods/get) requests are not preflighted. So, if a request is made for a resource with credentials, and if this header is not returned with the resource, the response is ignored by the browser and not returned to the web content. The `Access-Control-Allow-Credentials` header works in conjunction with the [`XMLHttpRequest.withCredentials`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials) property or with the `credentials` option in the [`Request()`](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) constructor of the Fetch API. For a CORS request with credentials, for browsers to expose the response to the frontend JavaScript code, both the server (using the `Access-Control-Allow-Credentials` header) and the client (by setting the credentials mode for the XHR, Fetch, or Ajax request) must indicate that they're opting into including credentials. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Access-Control-Allow-Credentials: true ``` Directives ---------- true The only valid value for this header is `true` (case-sensitive). If you don't need credentials, omit this header entirely (rather than setting its value to `false`). Examples -------- Allow credentials: ``` Access-Control-Allow-Credentials: true ``` Using [XHR](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) with credentials: ``` const xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/', true); xhr.withCredentials = true; xhr.send(null); ``` Using [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) with credentials: ``` fetch(url, { credentials: 'include' }) ``` Specifications -------------- | Specification | | --- | | [Fetch Standard # http-access-control-allow-credentials](https://fetch.spec.whatwg.org/#http-access-control-allow-credentials) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Access-Control-Allow-Credentials` | 4 | 12 | 3.5 | 10 | 12 | 4 | 2 | Yes | 4 | 12 | 3.2 | Yes | See also -------- * [`XMLHttpRequest.withCredentials`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials) * [`Request()`](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) http Sec-Fetch-Site Sec-Fetch-Site ============== Sec-Fetch-Site ============== The `Sec-Fetch-Site` [fetch metadata request header](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_metadata_request_header) indicates the relationship between a request initiator's origin and the origin of the requested resource. In other words, this header tells a server whether a request for a resource is coming from the same origin, the same site, a different site, or is a "user initiated" request. The server can then use this information to decide if the request should be allowed. Same-origin requests would usually be allowed by default, but what happens for requests from other origins may further depend on what resource is being requested, or information in other [Fetch metadata request headers](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_metadata_request_header). By default, requests that are not accepted should be rejected with a [`403`](../status/403) response code. | | | | --- | --- | | Header type | [Fetch Metadata Request Header](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_metadata_request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes (prefix `Sec-`) | | [CORS-safelisted request header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header) | no | Syntax ------ ``` Sec-Fetch-Site: cross-site Sec-Fetch-Site: same-origin Sec-Fetch-Site: same-site Sec-Fetch-Site: none ``` Directives ---------- `cross-site` The request initiator and the server hosting the resource have a different site (i.e. a request by "potentially-evil.com" for a resource at "example.com"). `same-origin` The request initiator and the server hosting the resource have the same [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) (same scheme, host and port). `same-site` The request initiator and the server hosting the resource have the same scheme, domain and/or subdomain, but not necessarily the same port. `none` This request is a user-originated operation. For example: entering a URL into the address bar, opening a bookmark, or dragging-and-dropping a file into the browser window. Examples -------- A fetch request to `https://mysite.example/foo.json` originating from a web page on `https://mysite.example` (with the same port) is a same-origin request. The browser will generate the `Sec-Fetch-Site: same-origin` header as shown below, and the server will typically allow the request: ``` GET /foo.json Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-origin ``` A fetch request to the same URL from another site, for example `potentially-evil.com`, causes the browser to generate a different header (e.g. `Sec-Fetch-Site: cross-site`), which the server can choose to accept or reject: ``` GET /foo.json Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: cross-site ``` Specifications -------------- | Specification | | --- | | [Fetch Metadata Request Headers # sec-fetch-site-header](https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Sec-Fetch-Site` | 76 | 79 | 90 | No | 63 | No | 76 | 76 | 90 | 54 | No | 12.0 | See also -------- * Related headers + [`Sec-Fetch-Mode`](sec-fetch-mode) + [`Sec-Fetch-User`](sec-fetch-user) + [`Sec-Fetch-Dest`](sec-fetch-dest) * [Protect your resources from web attacks with Fetch Metadata](https://web.dev/fetch-metadata/) (web.dev) * [Fetch Metadata Request Headers playground](https://secmetadata.appspot.com/) (secmetadata.appspot.com)
programming_docs
http Accept Accept ====== Accept ====== The `Accept` request HTTP header indicates which content types, expressed as [MIME types](../basics_of_http/mime_types), the client is able to understand. The server uses [content negotiation](../content_negotiation) to select one of the proposals and informs the client of the choice with the [`Content-Type`](content-type) response header. Browsers set required values for this header based on the context of the request. For example, a browser uses different values in a request when fetching a CSS stylesheet, image, video, or a script. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [CORS-safelisted request header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header) | yes, with the additional restriction that values can't contain a *CORS-unsafe request header byte*: 0x00-0x1F (except 0x09 (HT)), `"():<>?@[\]{}`, and 0x7F (DEL). | Syntax ------ ``` Accept: <MIME\_type>/<MIME\_subtype> Accept: <MIME\_type>/\* Accept: \*/\* // Multiple types, weighted with the quality value syntax: Accept: text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, \*/\*;q=0.8 ``` Directives ---------- `<MIME_type>/<MIME_subtype>` A single, precise [MIME type](../basics_of_http/mime_types), like `text/html`. `<MIME_type>/*` A MIME type, but without a subtype. `image/*` corresponds to `image/png`, `image/svg`, `image/gif`, and other image types. `*/*` Any MIME type `;q=` (q-factor weighting) A value used is placed in an order of preference expressed using a relative [quality value](https://developer.mozilla.org/en-US/docs/Glossary/Quality_values) called the *weight*. Examples -------- ``` Accept: text/html Accept: image/\* // General default Accept: \*/\* // Default for navigation requests Accept: text/html, application/xhtml+xml, application/xml;q=0.9, \*/\*;q=0.8 ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.accept](https://httpwg.org/specs/rfc9110.html#field.accept) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Accept` | Yes | 12 | Yes In Firefox 66, the default `Accept` header value changed to `*/*`. | Yes | Yes | Yes | Yes | Yes | Yes In Firefox 66, the default `Accept` header value changed to `*/*`. | Yes | Yes | Yes | See also -------- * HTTP [content negotiation](../content_negotiation) * [List of default Accept values](../content_negotiation/list_of_default_accept_values) * A header with the result of the content negotiation: [`Content-Type`](content-type) * Other similar headers: [`TE`](te), [`Accept-Encoding`](accept-encoding), [`Accept-Language`](accept-language) http Cross-Origin-Embedder-Policy Cross-Origin-Embedder-Policy ============================ Cross-Origin-Embedder-Policy ============================ The HTTP `Cross-Origin-Embedder-Policy` (COEP) response header prevents a document from loading any cross-origin resources that don't explicitly grant the document permission (using [CORP](../cross-origin_resource_policy_(corp)) or [CORS](../cors)). | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Cross-Origin-Embedder-Policy: unsafe-none | require-corp ``` ### Directives `unsafe-none` This is the default value. Allows the document to fetch cross-origin resources without giving explicit permission through the CORS protocol or the [`Cross-Origin-Resource-Policy`](cross-origin-resource-policy) header. `require-corp` A document can only load resources from the same origin, or resources explicitly marked as loadable from another origin. If a cross origin resource supports CORS, the [`crossorigin`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) attribute or the [`Cross-Origin-Resource-Policy`](cross-origin-resource-policy) header must be used to load it without being blocked by COEP. Examples -------- ### Certain features depend on cross-origin isolation You can only access certain features like [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) objects or [`Performance.now()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now) with unthrottled timers, if your document has a COEP header with the value `require-corp` value set. ``` Cross-Origin-Embedder-Policy: require-corp Cross-Origin-Opener-Policy: same-origin ``` See also the [`Cross-Origin-Opener-Policy`](cross-origin-opener-policy) header which you'll need to set as well. To check if cross origin isolation has been successful, you can test against the [`crossOriginIsolated`](https://developer.mozilla.org/en-US/docs/Web/API/crossOriginIsolated) property available to window and worker contexts: ``` if (crossOriginIsolated) { // Post SharedArrayBuffer } else { // Do something else } ``` ### Avoiding COEP blockage with CORS If you enable COEP using `require-corp` and have a cross origin resource that needs to be loaded, it needs to support [CORS](../cors) and you need to explicitly mark the resource as loadable from another origin to avoid blockage from COEP. For example, you can use the [`crossorigin`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) attribute for this image from a third-party site: ``` <img src="https://thirdparty.com/img.png" crossorigin /> ``` Specifications -------------- | Specification | | --- | | [HTML Standard # coep](https://html.spec.whatwg.org/multipage/origin.html#coep) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Cross-Origin-Embedder-Policy` | 83 | 83 | 79 | No | 69 | 15.2 | 86 | 83 | 79 | 59 | 15.2 | 13.0 | | `credentialless` | 96 | 96 | No | No | 82 | No | 96 | 96 | No | No | No | 17.0 | See also -------- * [`Cross-Origin-Opener-Policy`](cross-origin-opener-policy) http Transfer-Encoding Transfer-Encoding ================= Transfer-Encoding ================= The `Transfer-Encoding` header specifies the form of encoding used to safely transfer the [payload body](https://developer.mozilla.org/en-US/docs/Glossary/Payload_body) to the user. **Note:** [HTTP/2](https://en.wikipedia.org/wiki/HTTP/2) disallows all uses of the Transfer-Encoding header other than the HTTP/2 specific: `"trailers"`. HTTP 2 provides its own more efficient mechanisms for data streaming than chunked transfer and forbids the use of the header. Usage of the header in HTTP/2 may likely result in a specific `protocol error` as HTTP/2 Protocol prohibits the use. `Transfer-Encoding` is a [hop-by-hop header](../headers#hop-by-hop_headers), that is applied to a message between two nodes, not to a resource itself. Each segment of a multi-node connection can use different `Transfer-Encoding` values. If you want to compress data over the whole connection, use the end-to-end [`Content-Encoding`](content-encoding) header instead. When present on a response to a [`HEAD`](../methods/head) request that has no body, it indicates the value that would have applied to the corresponding [`GET`](../methods/get) message. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header), [Payload header](https://developer.mozilla.org/en-US/docs/Glossary/Payload_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Transfer-Encoding: chunked Transfer-Encoding: compress Transfer-Encoding: deflate Transfer-Encoding: gzip // Several values can be listed, separated by a comma Transfer-Encoding: gzip, chunked ``` Directives ---------- `chunked` Data is sent in a series of chunks. The [`Content-Length`](content-length) header is omitted in this case and at the beginning of each chunk you need to add the length of the current chunk in hexadecimal format, followed by '`\r\n`' and then the chunk itself, followed by another '`\r\n`'. The terminating chunk is a regular chunk, with the exception that its length is zero. It is followed by the trailer, which consists of a (possibly empty) sequence of header fields. `compress` A format using the [Lempel-Ziv-Welch](https://en.wikipedia.org/wiki/LZW) (LZW) algorithm. The value name was taken from the UNIX *compress* program, which implemented this algorithm. Like the compress program, which has disappeared from most UNIX distributions, this content-encoding is used by almost no browsers today, partly because of a patent issue (which expired in 2003). `deflate` Using the [zlib](https://en.wikipedia.org/wiki/Zlib) structure (defined in [RFC 1950](https://datatracker.ietf.org/doc/html/rfc1950)), with the [*deflate*](https://en.wikipedia.org/wiki/DEFLATE) compression algorithm (defined in [RFC 1951](https://datatracker.ietf.org/doc/html/rfc1952)). `gzip` A format using the [Lempel-Ziv coding](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ77) (LZ77), with a 32-bit CRC. This is originally the format of the UNIX *gzip* program. The HTTP/1.1 standard also recommends that the servers supporting this content-encoding should recognize `x-gzip` as an alias, for compatibility purposes. Examples -------- ### Chunked encoding Chunked encoding is useful when larger amounts of data are sent to the client and the total size of the response may not be known until the request has been fully processed. For example, when generating a large HTML table resulting from a database query or when transmitting large images. A chunked response looks like this: ``` HTTP/1.1 200 OK Content-Type: text/plain Transfer-Encoding: chunked 7\r\n Mozilla\r\n 11\r\n Developer Network\r\n 0\r\n \r\n ``` Specifications -------------- | Specification | | --- | | [HTTP/1.1 # field.transfer-encoding](https://httpwg.org/specs/rfc9112.html#field.transfer-encoding) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Transfer-Encoding` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Accept-Encoding`](accept-encoding) * [`Content-Encoding`](content-encoding) * [`Content-Length`](content-length) * Header fields that regulate the use of trailers: [`TE`](te) (requests) and [`Trailer`](trailer) (responses). * [Chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding) http X-DNS-Prefetch-Control X-DNS-Prefetch-Control ====================== X-DNS-Prefetch-Control ====================== **Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The `X-DNS-Prefetch-Control` HTTP response header controls DNS prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as URLs for items referenced by the document, including images, CSS, JavaScript, and so forth. This prefetching is performed in the background, so that the [DNS](https://developer.mozilla.org/en-US/docs/Glossary/DNS) is likely to have been resolved by the time the referenced items are needed. This reduces latency when the user clicks a link. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` X-DNS-Prefetch-Control: on X-DNS-Prefetch-Control: off ``` ### Directives on Enables DNS prefetching. This is what browsers do, if they support the feature, when this header is not present off Disables DNS prefetching. This is useful if you don't control the link on the pages, or know that you don't want to leak information to these domains. Description ----------- DNS requests are very small in terms of bandwidth, but latency can be quite high, especially on mobile networks. By speculatively prefetching DNS results, latency can be reduced significantly at certain times, such as when the user clicks the link. In some cases, latency can be reduced by a second. The implementation of this prefetching in some browsers allows domain name resolution to occur in parallel with (instead of in serial with) the fetching of actual page content. By doing this, the high-latency domain name resolution process doesn't cause any delay while fetching content. Page load times – especially on mobile networks – can be measurably improved in this way. If the domain names for images can be resolved in advance of the images being requested, pages that load many images can see an improvement of 5% or more in the time of loading images. ### Configuring prefetching in the browser In general, you don't need to do anything to manage prefetching. However, the user may wish to disable prefetching. On Firefox, this can be done by setting the `network.dns.disablePrefetch` preference to `true`. Also, by default, prefetching of embedded link hostnames is not performed on documents loaded over [HTTPS](https://developer.mozilla.org/en-US/docs/Glossary/https). On Firefox, this can be changed by setting the `network.dns.disablePrefetchFromHTTPS` preference to `false`. Examples -------- ### Turning on and off prefetching You can either send the `X-DNS-Prefetch-Control` header server-side, or from individual documents, using the [`http-equiv`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#attr-http-equiv) attribute on the [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) element, like this: ``` <meta http-equiv="x-dns-prefetch-control" content="off" /> ``` You can reverse this setting by setting `content` to "`on`". ### Forcing lookup of specific hostnames You can force the lookup of specific hostnames without providing specific anchors using that hostname by using the [`rel`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-rel) attribute on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) element with a [link type](https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types) of `dns-prefetch`: ``` <link rel="dns-prefetch" href="https://www.mozilla.org/contribute/" /> ``` In this example, the domain name `www.mozilla.org/contribute` will be pre-resolved. Similarly, the link element can be used to resolve hostnames without providing a complete URL, but only, by preceding the hostname with two slashes: ``` <link rel="dns-prefetch" href="//www.mozilla.org/contribute/" /> ``` Forced prefetching of hostnames might be useful, for example, on the homepage of a site to force pre-resolution of domain names that are referenced frequently throughout the site even though they are not used on the home page itself. This will improve the overall performance of site even though the performance of the home page may not be affected. Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `X-DNS-Prefetch-Control` | 1 | ≤79 | 2 | No | Yes | No | Yes | 18 | 4 | Yes | No | Yes | See also -------- * [DNS Prefetching for Firefox (blog post)](https://bitsup.blogspot.com/2008/11/dns-prefetching-for-firefox.html) * [Google Chrome handles DNS prefetching control](https://www.chromium.org/developers/design-documents/dns-prefetching/) http Cache-Control Cache-Control ============= Cache-Control ============= The `Cache-Control` HTTP header field holds *directives* (instructions) — in both requests and responses — that control [caching](../caching) in browsers and shared caches (e.g. Proxies, CDNs). | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [CORS-safelisted response header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header) | yes | Syntax ------ Caching directives follow the validation rules below: * Caching directives are case-insensitive. However, lowercase is recommended because some implementations do not recognize uppercase directives. * Multiple directives are comma-separated. * Some directives have an optional argument. ### Cache directives The following table lists the standard `Cache-Control` directives: | Request | Response | | --- | --- | | `max-age` | `max-age` | | `max-stale` | - | | `min-fresh` | - | | - | `s-maxage` | | `no-cache` | `no-cache` | | `no-store` | `no-store` | | `no-transform` | `no-transform` | | `only-if-cached` | - | | - | `must-revalidate` | | - | `proxy-revalidate` | | - | `must-understand` | | - | `private` | | - | `public` | | - | `immutable` | | - | `stale-while-revalidate` | | `stale-if-error` | `stale-if-error` | Note: Check the [compatibility table](#browser_compatibility) for their support; user agents that don't recognize them should ignore them. Vocabulary ---------- This section defines the terms used in this document, some of which are from the specification. `(HTTP) cache` Implementation that holds requests and responses for reusing in subsequent requests. It can be either a shared cache or a private cache. `Shared cache` Cache that exists between the origin server and clients (e.g. Proxy, CDN). It stores a single response and reuses it with multiple users — so developers should avoid storing personalized contents to be cached in the shared cache. `Private cache` Cache that exists in the client. It is also called *local cache* or *browser cache*. It can store and reuse personalized content for a single user. `Store response` Store a response in caches when the response is cacheable. However, the cached response is not always reused as-is. (Usually, "cache" means storing a response.) `Reuse response` Reuse cached responses for subsequent requests. `Revalidate response` Ask the origin server whether or not the stored response is still [fresh](../caching#fresh_and_stale_based_on_age). Usually, the revalidation is done through a conditional request. `Fresh response` Indicates that the response is [fresh](../caching#fresh_and_stale_based_on_age). This usually means the response can be reused for subsequent requests, depending on request directives. `Stale response` Indicates that the response is a [stale response](../caching#fresh_and_stale_based_on_age). This usually means the response can't be reused as-is. Cache storage isn't required to remove stale responses immediately because revalidation could change the response from being stale to being [fresh](../caching#fresh_and_stale_based_on_age) again. `Age` The time since a response was generated. It is a criterion for whether a response is [fresh or stale](../caching#fresh_and_stale_based_on_age). Directives ---------- This section lists directives that affect caching — both response directives and request directives. ### Response Directives #### `max-age` The `max-age=N` response directive indicates that the response remains [fresh](../caching#fresh_and_stale_based_on_age) until *N* seconds after the response is generated. ``` Cache-Control: max-age=604800 ``` Indicates that caches can store this response and reuse it for subsequent requests while it's [fresh](../caching#fresh_and_stale_based_on_age). Note that `max-age` is not the elapsed time since the response was received; it is the elapsed time since the response was generated on the origin server. So if the other cache(s) — on the network route taken by the response — store the response for 100 seconds (indicated using the `Age` response header field), the browser cache would deduct 100 seconds from its [freshness lifetime](../caching#freshness_lifetime). ``` Cache-Control: max-age=604800 Age: 100 ``` #### `s-maxage` The `s-maxage` response directive also indicates how long the response is [fresh](../caching#fresh_and_stale_based_on_age) for (similar to `max-age`) — but it is specific to shared caches, and they will ignore `max-age` when it is present. ``` Cache-Control: s-maxage=604800 ``` #### `no-cache` The `no-cache` response directive indicates that the response can be stored in caches, but the response must be validated with the origin server before each reuse, even when the cache is disconnected from the origin server. ``` Cache-Control: no-cache ``` If you want caches to always check for content updates while reusing stored content, `no-cache` is the directive to use. It does this by requiring caches to revalidate each request with the origin server. Note that `no-cache` does not mean "don't cache". `no-cache` allows caches to store a response but requires them to revalidate it before reuse. If the sense of "don't cache" that you want is actually "don't store", then `no-store` is the directive to use. #### `must-revalidate` The `must-revalidate` response directive indicates that the response can be stored in caches and can be reused while [fresh](../caching#fresh_and_stale_based_on_age). If the response becomes [stale](../caching#fresh_and_stale_based_on_age), it must be validated with the origin server before reuse. Typically, `must-revalidate` is used with `max-age`. ``` Cache-Control: max-age=604800, must-revalidate ``` HTTP allows caches to reuse [stale responses](../caching#fresh_and_stale_based_on_age) when they are disconnected from the origin server. `must-revalidate` is a way to prevent this from happening - either the stored response is revalidated with the origin server or a 504 (Gateway Timeout) response is generated. #### `proxy-revalidate` The `proxy-revalidate` response directive is the equivalent of `must-revalidate`, but specifically for shared caches only. #### `no-store` The `no-store` response directive indicates that any caches of any kind (private or shared) should not store this response. ``` Cache-Control: no-store ``` #### `private` The `private` response directive indicates that the response can be stored only in a private cache (e.g. local caches in browsers). ``` Cache-Control: private ``` You should add the `private` directive for user-personalized content, especially for responses received after login and for sessions managed via cookies. If you forget to add `private` to a response with personalized content, then that response can be stored in a shared cache and end up being reused for multiple users, which can cause personal information to leak. #### `public` The `public` response directive indicates that the response can be stored in a shared cache. Responses for requests with `Authorization` header fields must not be stored in a shared cache; however, the `public` directive will cause such responses to be stored in a shared cache. ``` Cache-Control: public ``` In general, when pages are under Basic Auth or Digest Auth, the browser sends requests with the `Authorization` header. This means that the response is access-controlled for restricted users (who have accounts), and it's fundamentally not shared-cacheable, even if it has `max-age`. You can use the `public` directive to unlock that restriction. ``` Cache-Control: public, max-age=604800 ``` Note that `s-maxage` or `must-revalidate` also unlock that restriction. If a request doesn't have an `Authorization` header, or you are already using `s-maxage` or `must-revalidate` in the response, then you don't need to use `public`. #### `must-understand` The `must-understand` response directive indicates that a cache should store the response only if it understands the requirements for caching based on status code. `must-understand` should be coupled with `no-store` for fallback behavior. ``` Cache-Control: must-understand, no-store ``` If a cache doesn't support `must-understand`, it will be ignored. If `no-store` is also present, the response isn't stored. If a cache supports `must-understand`, it stores the response with an understanding of cache requirements based on its status code. #### `no-transform` Some intermediaries transform content for various reasons. For example, some convert images to reduce transfer size. In some cases, this is undesirable for the content provider. `no-transform` indicates that any intermediary (regardless of whether it implements a cache) shouldn't transform the response contents. Note: [Google's Web Light](https://developers.google.com/search/docs/advanced/mobile/web-light?visit_id=637855965115455923-776951611&rd=1) is one kind of such an intermediary. It converts images to minimize data for a cache store or slow connection and supports `no-transform` as an opt-out option. #### `immutable` The `immutable` response directive indicates that the response will not be updated while it's [fresh](../caching#fresh_and_stale_based_on_age). ``` Cache-Control: public, max-age=604800, immutable ``` A modern best practice for static resources is to include version/hashes in their URLs, while never modifying the resources — but instead, when necessary, *updating* the resources with newer versions that have new version-numbers/hashes, so that their URLs are different. That's called the **cache-busting** pattern. ``` <script src=https://example.com/react.0.0.0.js></script> ``` When a user reloads the browser, the browser will send conditional requests for validating to the origin server. But it's not necessary to revalidate those kinds of static resources even when a user reloads the browser, because they're never modified. `immutable` tells a cache that the response is immutable while it's [fresh](../caching#fresh_and_stale_based_on_age) and avoids those kinds of unnecessary conditional requests to the server. When you use a cache-busting pattern for resources and apply them to a long `max-age`, you can also add `immutable` to avoid revalidation. #### `stale-while-revalidate` The `stale-while-revalidate` response directive indicates that the cache could reuse a stale response while it revalidates it to a cache. ``` Cache-Control: max-age=604800, stale-while-revalidate=86400 ``` In the example above, the response is [fresh](../caching#fresh_and_stale_based_on_age) for 7 days (604800s). After 7 days it becomes [stale](../caching#fresh_and_stale_based_on_age), but the cache is allowed to reuse it for any requests that are made in the following day (86400s), provided that they revalidate the response in the background. Revalidation will make the cache be [fresh](../caching#fresh_and_stale_based_on_age) again, so it appears to clients that it was always [fresh](../caching#fresh_and_stale_based_on_age) during that period — effectively hiding the latency penalty of revalidation from them. If no request happened during that period, the cache became [stale](../caching#fresh_and_stale_based_on_age) and the next request will revalidate normally. #### `stale-if-error` The `stale-if-error` response directive indicates that the cache can reuse a [stale response](../caching#fresh_and_stale_based_on_age) when an origin server responds with an error (500, 502, 503, or 504). ``` Cache-Control: max-age=604800, stale-if-error=86400 ``` In the example above, the response is [fresh](../caching#fresh_and_stale_based_on_age) for 7 days (604800s). After 7 days it becomes [stale](../caching#fresh_and_stale_based_on_age), but it can be used for an extra 1 day (86400s) if the server responds with an error. After a period of time, the stored response became [stale](../caching#fresh_and_stale_based_on_age) normally. This means that the client will receive an error response as-is if the origin server sends it. Request Directives ------------------ ### `no-cache` The `no-cache` request directive asks caches to validate the response with the origin server before reuse. ``` Cache-Control: no-cache ``` `no-cache` allows clients to request the most up-to-date response even if the cache has a [fresh](../caching#fresh_and_stale_based_on_age) response. Browsers usually add `no-cache` to requests when users are **force reloading** a page. ### `no-store` The `no-store` request directive allows a client to request that caches refrain from storing the request and corresponding response — even if the origin server's response could be stored. ``` Cache-Control: no-store ``` Note that the major browsers do not support requests with `no-store`. ### `max-age` The `max-age=N` request directive indicates that the client allows a stored response that is generated on the origin server within *N* seconds — where *N* may be any non-negative integer (including `0`). ``` Cache-Control: max-age=3600 ``` In the case above, if the response with `Cache-Control: max-age=604800` was generated more than 3 hours ago (calculated from `max-age` and the `Age` header), the cache couldn't reuse that response. Many browsers use this directive for **reloading**, as explained below. ``` Cache-Control: max-age=0 ``` `max-age=0` is a workaround for `no-cache`, because many old (HTTP/1.0) cache implementations don't support `no-cache`. Recently browsers are still using `max-age=0` in "reloading" — for backward compatibility — and alternatively using `no-cache` to cause a "force reloading". If the `max-age` value isn't non-negative (for example, `-1`) or isn't an integer (for example, `3599.99`), then the caching behavior is undefined. However, the [Calculating Freshness Lifetime](https://httpwg.org/specs/rfc9111.html#calculating.freshness.lifetime) section of the HTTP specification states: > Caches are encouraged to consider responses that have invalid freshness information to be stale. > > In other words, for any `max-age` value that isn't an integer or isn't non-negative, the caching behavior that's encouraged is to treat the value as if it were `0`. ### `max-stale` The `max-stale=N` request directive indicates that the client allows a stored response that is [stale](../caching#fresh_and_stale_based_on_age) within *N* seconds. ``` Cache-Control: max-stale=3600 ``` In the case above, if the response with `Cache-Control: max-age=604800` was generated more than 3 hours ago (calculated from `max-age` and the `Age` header), the cache couldn't reuse that response. Clients can use this header when the origin server is down or too slow and can accept cached responses from caches even if they are a bit old. Note that the major browsers do not support requests with `max-stale`. ### `min-fresh` The `min-fresh=N` request directive indicates that the client allows a stored response that is [fresh](../caching#fresh_and_stale_based_on_age) for at least *N* seconds. ``` Cache-Control: min-fresh=600 ``` In the case above, if the response with `Cache-Control: max-age=3600` was stored in caches 51 minutes ago, the cache couldn't reuse that response. Clients can use this header when the user requires the response to not only be [fresh](../caching#fresh_and_stale_based_on_age), but also requires that it won't be updated for a period of time. Note that the major browsers do not support requests with `min-fresh`. ### `no-transform` Same meaning that `no-transform` has for a response, but for a request instead. ### `only-if-cached` The client indicates that cache should obtain an already-cached response. If a cache has stored a response, it's reused. Use Cases --------- ### Preventing storing If you don't want a response stored in caches, use the `no-store` directive. ``` Cache-Control: no-store ``` Note that `no-cache` means "it can be stored but don't reuse before validating" — so it's not for preventing a response from being stored. ``` Cache-Control: no-cache ``` In theory, if directives are conflicted, the most restrictive directive should be honored. So the example below is basically meaningless because `private`, `no-cache`, `max-age=0` and `must-revalidate` conflict with `no-store`. ``` # conflicted Cache-Control: private, no-cache, no-store, max-age=0, must-revalidate # equivalent to Cache-Control: no-store ``` ### Caching static assets with "cache busting" When you build static assets with versioning/hashing mechanisms, adding a version/hash to the filename or query string is a good way to manage caching. For example: ``` <!-- index.html --> <script src="/assets/react.min.js"></script> <img src="/assets/hero.png" width="900" height="400" /> ``` The React library version will change when you update the library, and `hero.png` will also change when you edit the picture. So those are hard to store in a cache with `max-age`. In such a case, you could address the caching needs by using a specific, numbered version of the library, and including the hash of the picture in its URL. ``` <!-- index.html --> <script src="/assets/react.0.0.0min.js"></script> <img src="/assets/hero.png?hash=deadbeef" width="900" height="400" /> ``` You can add a long `max-age` value and `immutable` because the content will never change. ``` # /assets/* Cache-Control: max-age=31536000, immutable ``` When you update the library or edit the picture, new content should have a new URL, and caches aren't reused. That is called the "cache busting" pattern. Use a `no-cache` to make sure that the HTML response itself is not cached. `no-cache` could cause revalidation, and the client will correctly receive a new version of the HTML response and static assets. ``` # /index.html Cache-Control: no-cache ``` Note: If `index.html` is controlled under Basic Authentication or Digest Authentication, files under `/assets` are not stored in the shared cache. If `/assets/` files are suitable for storing in a shared cache, you also need one of `public`, `s-maxage` or `must-revalidate`. ### Up-to-date contents always For content that's generated dynamically, or that's static but updated often, you want a user to always receive the most up-to-date version. If you don't add a `Cache-Control` header because the response is not intended to be cached, that could cause an unexpected result. Cache storage is allowed to cache it heuristically — so if you have any requirements on caching, you should always indicate them explicitly, in the `Cache-Control` header. Adding `no-cache` to the response causes revalidation to the server, so you can serve a [fresh](../caching#fresh_and_stale_based_on_age) response every time — or if the client already has a new one, just respond `304 Not Modified`. ``` Cache-Control: no-cache ``` Most HTTP/1.0 caches don't support `no-cache` directives, so historically `max-age=0` was used as a workaround. But only `max-age=0` could cause a [stale response](../caching#fresh_and_stale_based_on_age) to be reused when caches disconnected from the origin server. `must-revalidate` addresses that. That's why the example below is equivalent to `no-cache`. ``` Cache-Control: max-age=0, must-revalidate ``` But for now, you can simply use `no-cache` instead. ### Clearing an already-stored cache Unfortunately, there are no cache directives for clearing already-stored responses from caches. Imagine that clients/caches store a [fresh](../caching#fresh_and_stale_based_on_age) response for a path, with no request flight to the server. There is nothing a server could do to that path. Alternatively, `Clear-Site-Data` can clear a browser cache for a site. But be careful: that clears every stored response for a site — and only in browsers, not for a shared cache. Specifications -------------- | Specification | | --- | | [HTTP Caching # field.cache-control](https://httpwg.org/specs/rfc9111.html#field.cache-control) | | [HTTP Immutable Responses # the-immutable-cache-control-extension](https://httpwg.org/specs/rfc8246.html#the-immutable-cache-control-extension) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Cache-Control` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `immutable` | No See Chromium [bug 611416](https://crbug.com/611416). | 15-79 | 49 | No | No See Chromium [bug 611416](https://crbug.com/611416). | 11 | No See Chromium [bug 611416](https://crbug.com/611416). | No See Chromium [bug 611416](https://crbug.com/611416). | No | No See Chromium [bug 611416](https://crbug.com/611416). | 11 | No See Chromium [bug 611416](https://crbug.com/611416). | | `stale-if-error` | No See Chromium [bug 348877](https://crbug.com/348877). | No See Chromium [bug 348877](https://crbug.com/348877). | No See Bugzilla [bug 995651](https://bugzil.la/995651) comment 7. | No | No See Chromium [bug 348877](https://crbug.com/348877). | No | No See Chromium [bug 348877](https://crbug.com/348877). | No See Chromium [bug 348877](https://crbug.com/348877). | No See Bugzilla [bug 995651](https://bugzil.la/995651) comment 7. | No See Chromium [bug 348877](https://crbug.com/348877). | No | No See Chromium [bug 348877](https://crbug.com/348877). | | `stale-while-revalidate` | 75 | 79 | 68 | No | No | No | 75 | 75 | 68 | No | No | 11.0 | See also -------- * [HTTP caching](../caching) * [Caching Tutorial for Web Authors and Webmasters](https://www.mnot.net/cache_docs/) * [Caching best practices & max-age gotchas](https://jakearchibald.com/2016/caching-best-practices/) * [Cache-Control for Civilians](https://csswizardry.com/2019/03/cache-control-for-civilians/) * [RFC 9111 – HTTP Caching](https://httpwg.org/specs/rfc9111.html) * [RFC 5861 – HTTP Cache-Control Extensions for Stale Content](https://httpwg.org/specs/rfc5861.html) * [RFC 8246 – HTTP Immutable Responses](https://httpwg.org/specs/rfc8246.html)
programming_docs
http If-None-Match If-None-Match ============= If-None-Match ============= The `If-None-Match` HTTP request header makes the request conditional. For [`GET`](../methods/get) and [`HEAD`](../methods/head) methods, the server will return the requested resource, with a [`200`](../status/200) status, only if it doesn't have an [`ETag`](etag) matching the given ones. For other methods, the request will be processed only if the eventually existing resource's [`ETag`](etag) doesn't match any of the values listed. When the condition fails for [`GET`](../methods/get) and [`HEAD`](../methods/head) methods, then the server must return HTTP status code 304 (Not Modified). For methods that apply server-side changes, the status code 412 (Precondition Failed) is used. Note that the server generating a 304 response MUST generate any of the following header fields that would have been sent in a 200 (OK) response to the same request: Cache-Control, Content-Location, Date, ETag, Expires, and Vary. The comparison with the stored [`ETag`](etag) uses the *weak comparison algorithm*, meaning two files are considered identical if the content is equivalent — they don't have to be identical byte by byte. For example, two pages that differ by their creation date in the footer would still be considered identical. When used in combination with [`If-Modified-Since`](if-modified-since), `If-None-Match` has precedence (if the server supports it). There are two common use cases: * For [`GET`](../methods/get) and [`HEAD`](../methods/head) methods, to update a cached entity that has an associated [`ETag`](etag). * For other methods, and in particular for [`PUT`](../methods/put), `If-None-Match` used with the `*` value can be used to save a file not known to exist, guaranteeing that another upload didn't happen before, losing the data of the previous put; this problem is a variation of the [lost update problem](https://www.w3.org/1999/04/Editing/#3.1). | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` If-None-Match: "<etag\_value>" If-None-Match: "<etag\_value>", "<etag\_value>", … If-None-Match: \* ``` Directives ---------- <etag\_value> Entity tags uniquely representing the requested resources. They are a string of ASCII characters placed between double quotes (Like `"675af34563dc-tr34"`) and may be prefixed by `W/` to indicate that the weak comparison algorithm should be used (this is useless with `If-None-Match` as it only uses that algorithm). `*` The asterisk is a special value representing any resource. They are only useful when uploading a resource, usually with [`PUT`](../methods/put), to check if another resource with the identity has already been uploaded before. Examples -------- ``` If-None-Match: "bfc13a64729c4290ef5b2c2730249c88ca92d82d" If-None-Match: W/"67ab43", "54ed21", "7892dd" If-None-Match: \* ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.if-none-match](https://httpwg.org/specs/rfc9110.html#field.if-none-match) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `If-None-Match` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`ETag`](etag) * [`If-Unmodified-Since`](if-unmodified-since) * [`If-Modified-Since`](if-modified-since) * [`If-Match`](if-match) * [`304 Not Modified`](../status/304) * [`412 Precondition Failed`](../status/412) http Upgrade Upgrade ======= Upgrade ======= The HTTP 1.1 (only) `Upgrade` header can be used to upgrade an already established client/server connection to a different protocol (over the same transport protocol). For example, it can be used by a client to upgrade a connection from HTTP 1.1 to HTTP 2.0, or an HTTP or HTTPS connection into a WebSocket. **Warning:** HTTP/2 explicitly disallows the use of this mechanism/header; it is specific to HTTP/1.1. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Overview -------- The `Upgrade` header field may be used by clients to invite a server to switch to one (or more) of the listed protocols, in descending preference order. For example, the client might send a `GET` request as shown, listing the preferred protocols to switch to (in this case "example/1" and "foo/2"): ``` GET /index.html HTTP/1.1 Host: www.example.com Connection: upgrade Upgrade: example/1, foo/2 ``` **Note:** `Connection: upgrade` must be set whenever `Upgrade` is sent. The server can choose to ignore the request, for any reason, in which case it should just respond as though the `Upgrade` header had not been sent (for example, with a [`200 OK`](../status/200)). If the server decides to upgrade the connection, it must: 1. Send back a [`101 Switching Protocols`](../status/101) response status with an `Upgrade` header that specifies the protocol(s) being switched to. For example: ``` HTTP/1.1 101 Switching Protocols Upgrade: foo/2 Connection: Upgrade ``` 2. Send a response to the original request *using the new protocol* (the server may only switch to a protocol with which it can complete the original request). A server may also send the header as part of a [`426`](../status/426) `Upgrade Required` response, to indicate that the server won't perform the request using the current protocol, but might do so if the protocol is changed. The client can then request a protocol change using the process above. More detail and examples are provided in the topic [Protocol upgrade mechanism](../protocol_upgrade_mechanism). Syntax ------ ``` Connection: upgrade Upgrade: protocol\_name[/protocol\_version] ``` Notes: * The [`Connection`](connection) header with type `upgrade` must *always* be sent with the `Upgrade` header (as shown above). * Protocols are listed, comma-separated, in order of descending preference. Protocol version is optional. For example: ``` Connection: upgrade Upgrade: a\_protocol/1, example, another\_protocol/2.2 ``` Directives ---------- any comma-separated list protocol names (each with optional protocol version) One or more protocol names with optional version ("/" separated). The protocols are listed in order of descending preference. Examples -------- ``` Connection: upgrade Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11 ``` ``` Connection: Upgrade Upgrade: websocket ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.upgrade](https://httpwg.org/specs/rfc9110.html#field.upgrade) | | [HTTP Semantics # status.426](https://httpwg.org/specs/rfc9110.html#status.426) | | [HTTP/2 # informational-responses](https://httpwg.org/specs/rfc9113.html#informational-responses) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Upgrade` | Yes | Yes | Yes | No | Yes | No | Yes | Yes | Yes | Yes | No | Yes | See also -------- * [Protocol upgrade mechanism](../protocol_upgrade_mechanism) * [`101`](../status/101) `Switching Protocol` * [`426`](../status/426) `Upgrade Required` * [`Connection`](connection) http Authorization Authorization ============= Authorization ============= The HTTP `Authorization` request header can be used to provide credentials that authenticate a user agent with a server, allowing access to a protected resource. The `Authorization` header is usually, but not always, sent after the user agent first attempts to request a protected resource without credentials. The server responds with a [`401`](../status/401) `Unauthorized` message that includes at least one [`WWW-Authenticate`](www-authenticate) header. This header indicates what authentication schemes can be used to access the resource (and any additional information needed by the client to use them). The user-agent should select the most secure authentication scheme that it supports from those offered, prompt the user for their credentials, and then re-request the resource (including the encoded credentials in the `Authorization` header). **Note:** This header is part of the [General HTTP authentication framework](../authentication#the_general_http_authentication_framework). It can be used with a number of [authentication schemes](../authentication#authentication_schemes). | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Authorization: <auth-scheme> <authorization-parameters> ``` Basic authentication ``` Authorization: Basic <credentials> ``` Digest authentication ``` Authorization: Digest username=<username>, realm="<realm>", uri="<url>", algorithm=<algorithm>, nonce="<nonce>", nc=<nc>, cnonce="<cnonce>", qop=<qop>, response="<response>", opaque="<opaque>" ``` Directives ---------- `<auth-scheme>` The [Authentication scheme](../authentication#authentication_schemes) that defines how the credentials are encoded. Some of the more common types are (case-insensitive): [`Basic`](../authentication#basic_authentication_scheme), `Digest`, `Negotiate` and `AWS4-HMAC-SHA256`. **Note:** For more information/options see [HTTP Authentication > Authentication schemes](../authentication#authentication_schemes) Other than `<auth-scheme>` the remaining directives are specific to each [authentication scheme](../authentication#authentication_schemes). Generally you will need to check the relevant specifications for these (keys for a small subset of schemes are listed below). ### Basic <credentials> The credentials, encoded according to the specified scheme. **Note:** For information about the encoding algorithm, see the examples: below, in [`WWW-Authenticate`](www-authenticate), in [HTTP Authentication](../authentication), and in the relevant specifications. ### Digest <response> A string of the hex digits that proves that the user knows a password. The algorithm encodes the username and password, realm, cnonce, qop, nc, and so on. It is described in detail in the specification. `username` A quoted string containing user's name for the specified `realm` in either plain text or the hash code in hexadecimal notation. If the name contains characters that aren't allowed in the field, then `username*` can be used instead (not "as well"). `username*` The user's name formatted using an extended notation defined in RFC5987. This should be used only if the name can't be encoded in `username` and if `userhash` is set `"false"`. `uri` The *Effective Request URI*. See the specification for more information. `realm` Realm of the requested username/password (again, should match the value in the corresponding [`WWW-Authenticate`](www-authenticate) response for the resource being requested). `opaque` The value in the corresponding [`WWW-Authenticate`](www-authenticate) response for the resource being requested. `algorithm` The algorithm used to calculate the digest. Must be a supported algorithm from the [`WWW-Authenticate`](www-authenticate) response for the resource being requested. `qop` A token indicating the *quality of protection* applied to the message. Must match the one value in the set specified in the [`WWW-Authenticate`](www-authenticate) response for the resource being requested. * `"auth"`: Authentication * `"auth-int"`: Authentication with integrity protection `cnonce` An quoted ASCII-only string value provided by the client. This is used by both the client and server to provide mutual authentication, provide some message integrity protection, and avoid "chosen plaintext attacks". See the specification for additional information. `nc` Nonce count. The hexadecimal count of requests in which the client has sent the current `cnonce` value (including the current request). The server can use duplicate `nc` values to recognize replay requests. `userhash` Optional `"true"` if the username has been hashed. `"false"` by default. Examples -------- ### Basic authentication For `"Basic"` authentication the credentials are constructed by first combining the username and the password with a colon (`aladdin:opensesame`), and then by encoding the resulting string in [`base64`](https://developer.mozilla.org/en-US/docs/Glossary/Base64) (`YWxhZGRpbjpvcGVuc2VzYW1l`). ``` Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l ``` **Warning:** [Base64](https://developer.mozilla.org/en-US/docs/Glossary/Base64)-encoding can easily be reversed to obtain the original name and password, so Basic authentication is completely insecure. [HTTPS](https://developer.mozilla.org/en-US/docs/Glossary/https) is always recommended when using authentication, but is even more so when using `Basic` authentication. See also [HTTP authentication](../authentication) for examples on how to configure Apache or Nginx servers to password protect your site with HTTP basic authentication. Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.authorization](https://httpwg.org/specs/rfc9110.html#field.authorization) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Basic` | 1 | 12 | 1 | 1 | Yes | Yes | 37 | Yes | Yes | Yes | Yes | Yes | | `Digest` | Yes | Yes | Yes | No | Yes | No | Yes | Yes | Yes | Yes | No | Yes | | `NTLM` | Yes | Yes | Yes | No | Yes | No | Yes | Yes | Yes | Yes | No | Yes | | `Negotiate` | Yes | Yes | Yes | No | Yes | No | Yes | Yes | Yes | Yes | No | Yes | | `Authorization` | 1 | 12 | 1 | 1 | Yes | Yes | 37 | Yes | Yes | Yes | Yes | Yes | See also -------- * [HTTP authentication](../authentication) * [`WWW-Authenticate`](www-authenticate) * [`Proxy-Authorization`](proxy-authorization) * [`Proxy-Authenticate`](proxy-authenticate) * [`401`](../status/401), [`403`](../status/403), [`407`](../status/407) http If-Modified-Since If-Modified-Since ================= If-Modified-Since ================= The `If-Modified-Since` request HTTP header makes the request conditional: the server sends back the requested resource, with a [`200`](../status/200) status, only if it has been last modified after the given date. If the resource has not been modified since, the response is a [`304`](../status/304) without any body; the [`Last-Modified`](last-modified) response header of a previous request contains the date of last modification. Unlike [`If-Unmodified-Since`](if-unmodified-since), `If-Modified-Since` can only be used with a [`GET`](../methods/get) or [`HEAD`](../methods/head). When used in combination with [`If-None-Match`](if-none-match), it is ignored, unless the server doesn't support `If-None-Match`. The most common use case is to update a cached entity that has no associated [`ETag`](etag). | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` If-Modified-Since: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT ``` Directives ---------- <day-name> One of "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", or "Sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". <month> One of "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" (case sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <hour> 2 digit hour number, e.g. "09" or "23". <minute> 2 digit minute number, e.g. "04" or "59". <second> 2 digit second number, e.g. "04" or "59". `GMT` Greenwich Mean Time. HTTP dates are always expressed in GMT, never in local time. Examples -------- ``` If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.if-modified-since](https://httpwg.org/specs/rfc9110.html#field.if-modified-since) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `If-Modified-Since` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`ETag`](etag) * [`If-Unmodified-since`](if-unmodified-since) * [`If-Match`](if-match) * [`If-None-Match`](if-none-match) * [`304 Not Modified`](../status/304) http Access-Control-Request-Method Access-Control-Request-Method ============================= Access-Control-Request-Method ============================= The `Access-Control-Request-Method` request header is used by browsers when issuing a [preflight request](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request), to let the server know which [HTTP method](../methods) will be used when the actual request is made. This header is necessary as the preflight request is always an [`OPTIONS`](../methods/options) and doesn't use the same method as the actual request. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Access-Control-Request-Method: <method> ``` Directives ---------- <method> One of the [HTTP request methods](../methods), for example [`GET`](../methods/get), [`POST`](../methods/post), or [`DELETE`](../methods/delete). Examples -------- ``` Access-Control-Request-Method: POST ``` Specifications -------------- | Specification | | --- | | [Fetch Standard # http-access-control-request-method](https://fetch.spec.whatwg.org/#http-access-control-request-method) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Access-Control-Request-Method` | 4 | 12 | 3.5 | 10 | 12 | 4 | 2 | Yes | 4 | 12 | 3.2 | Yes | See also -------- * [`Access-Control-Request-Headers`](access-control-request-headers) http Access-Control-Allow-Origin Access-Control-Allow-Origin =========================== Access-Control-Allow-Origin =========================== The `Access-Control-Allow-Origin` response header indicates whether the response can be shared with requesting code from the given [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin). | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Access-Control-Allow-Origin: \* Access-Control-Allow-Origin: <origin> Access-Control-Allow-Origin: null ``` Directives ---------- `*` For requests *without credentials*, the literal value "`*`" can be specified as a wildcard; the value tells browsers to allow requesting code from any origin to access the resource. Attempting to use the wildcard with credentials [results in an error](../cors/errors/corsnotsupportingcredentials). `<origin>` Specifies an origin. Only a single origin can be specified. If the server supports clients from multiple origins, it must return the origin for the specific client making the request. `null` Specifies the origin "null". **Note:** `null` [should not be used](https://w3c.github.io/webappsec-cors-for-developers/#avoid-returning-access-control-allow-origin-null): "It may seem safe to return `Access-Control-Allow-Origin: "null"`, but the serialization of the Origin of any resource that uses a non-hierarchical scheme (such as `data:` or `file:`) and sandboxed documents is defined to be "null". Many User Agents will grant such documents access to a response with an `Access-Control-Allow-Origin: "null"` header, and any origin can create a hostile document with a "null" Origin. The "null" value for the ACAO header should therefore be avoided." Examples -------- A response that tells the browser to allow code from any origin to access a resource will include the following: ``` Access-Control-Allow-Origin: \* ``` A response that tells the browser to allow requesting code from the origin `https://developer.mozilla.org` to access a resource will include the following: ``` Access-Control-Allow-Origin: https://developer.mozilla.org ``` Limiting the possible `Access-Control-Allow-Origin` values to a set of allowed origins requires code on the server side to check the value of the [`Origin`](origin) request header, compare that to a list of allowed origins, and then if the [`Origin`](origin) value is in the list, set the `Access-Control-Allow-Origin` value to the same value as the [`Origin`](origin) value. ### CORS and caching Suppose the server sends a response with an `Access-Control-Allow-Origin` value with an explicit origin (rather than the "`*`" wildcard). In that case, the response should also include a [`Vary`](vary) response header with the value `Origin` — to indicate to browsers that server responses can differ based on the value of the `Origin` request header. ``` Access-Control-Allow-Origin: https://developer.mozilla.org Vary: Origin ``` Specifications -------------- | Specification | | --- | | [Fetch Standard # http-access-control-allow-origin](https://fetch.spec.whatwg.org/#http-access-control-allow-origin) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Access-Control-Allow-Origin` | 4 | 12 | 3.5 | 10 | 12 | 4 | 2 | Yes | 4 | 12 | 3.2 | Yes | See also -------- * [`Origin`](origin) * [`Vary`](vary) * [Cross-Origin Resource Sharing (CORS)](../cors) * [`Cross-Origin-Resource-Policy`](cross-origin-resource-policy)
programming_docs
http Referrer-Policy Referrer-Policy =============== Referrer-Policy =============== The `Referrer-Policy` [HTTP header](https://developer.mozilla.org/en-US/docs/Glossary/HTTP_header) controls how much [referrer information](https://developer.mozilla.org/en-US/docs/Web/Security/Referer_header:_privacy_and_security_concerns) (sent with the [`Referer`](referer) header) should be included with requests. Aside from the HTTP header, you can [set this policy in HTML](#integration_with_html). | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Referrer-Policy: no-referrer Referrer-Policy: no-referrer-when-downgrade Referrer-Policy: origin Referrer-Policy: origin-when-cross-origin Referrer-Policy: same-origin Referrer-Policy: strict-origin Referrer-Policy: strict-origin-when-cross-origin Referrer-Policy: unsafe-url ``` **Note:** The original header name [`Referer`](referer) is a misspelling of the word "referrer". The `Referrer-Policy` header does not share this misspelling. Directives ---------- `no-referrer` The [`Referer`](referer) header will be omitted: sent requests do not include any referrer information. `no-referrer-when-downgrade` Send the [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin), path, and querystring in [`Referer`](referer) when the protocol security level stays the same or improves (HTTP→HTTP, HTTP→HTTPS, HTTPS→HTTPS). Don't send the [`Referer`](referer) header for requests to less secure destinations (HTTPS→HTTP, HTTPS→file). `origin` Send only the [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) in the [`Referer`](referer) header. For example, a document at `https://example.com/page.html` will send the referrer `https://example.com/`. `origin-when-cross-origin` When performing a [same-origin](https://developer.mozilla.org/en-US/docs/Glossary/Same-origin_policy) request to the same protocol level (HTTP→HTTP, HTTPS→HTTPS), send the [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin), path, and query string. Send only the origin for cross origin requests and requests to less secure destinations (HTTPS→HTTP). `same-origin` Send the [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin), path, and query string for [same-origin](https://developer.mozilla.org/en-US/docs/Glossary/Same-origin_policy) requests. Don't send the [`Referer`](referer) header for cross-origin requests. `strict-origin` Send only the origin when the protocol security level stays the same (HTTPS→HTTPS). Don't send the [`Referer`](referer) header to less secure destinations (HTTPS→HTTP). `strict-origin-when-cross-origin` (default) Send the origin, path, and querystring when performing a same-origin request. For cross-origin requests send the origin (only) when the protocol security level stays same (HTTPS→HTTPS). Don't send the [`Referer`](referer) header to less secure destinations (HTTPS→HTTP). **Note:** This is the default policy if no policy is specified, or if the provided value is invalid (see spec revision [November 2020](https://github.com/whatwg/fetch/pull/1066)). Previously the default was `no-referrer-when-downgrade`. `unsafe-url` Send the origin, path, and query string when performing any request, regardless of security. **Warning:** This policy will leak potentially-private information from HTTPS resource URLs to insecure origins. Carefully consider the impact of this setting. Integration with HTML --------------------- You can also set referrer policies inside HTML. For example, you can set the referrer policy for the entire document with a [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) element with a [name](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#attr-name) of `referrer`: ``` <meta name="referrer" content="origin" /> ``` You can specify the `referrerpolicy` attribute on [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a), [`<area>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area), [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img), [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe), [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script), or [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) elements to set referrer policies for individual requests: ``` <a href="http://example.com" referrerpolicy="origin">…</a> ``` Alternatively, you can set a `noreferrer` [link relation](https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types) on an `a`, `area`, or `link` elements: ``` <a href="http://example.com" rel="noreferrer">…</a> ``` **Warning:** As seen above, the `noreferrer` link relation is written without a dash. When you specify the referrer policy for the entire document with a [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) element, it should be written *with* a dash: `<meta name="referrer" content="no-referrer">`. Integration with CSS -------------------- CSS can fetch resources referenced from stylesheets. These resources follow a referrer policy as well: * External CSS stylesheets use the default policy (`strict-origin-when-cross-origin`), unless it's overwritten by a `Referrer-Policy` HTTP header on the CSS stylesheet's response. * For [`<style>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style) elements or [`style` attributes](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style), the owner document's referrer policy is used. Examples -------- ### `no-referrer` | From document | Navigation to | Referrer used | | --- | --- | --- | | `https://example.com/page` | *anywhere* | *(no referrer)* | ### `no-referrer-when-downgrade` | From document | Navigation to | Referrer used | | --- | --- | --- | | `https://example.com/page` | `https://example.com/otherpage` | `https://example.com/page` | | `https://example.com/page` | `https://mozilla.org` | `https://example.com/page` | | `https://example.com/page` | **http**://example.com | *(no referrer)* | ### `origin` | From document | Navigation to | Referrer used | | --- | --- | --- | | `https://example.com/page` | *anywhere* | `https://example.com/` | ### `origin-when-cross-origin` | From document | Navigation to | Referrer used | | --- | --- | --- | | `https://example.com/page` | `https://example.com/otherpage` | `https://example.com/page` | | `https://example.com/page` | `https://mozilla.org` | `https://example.com/` | | `https://example.com/page` | **http**://example.com/page | `https://example.com/` | ### `same-origin` | From document | Navigation to | Referrer used | | --- | --- | --- | | `https://example.com/page` | `https://example.com/otherpage` | `https://example.com/page` | | `https://example.com/page` | `https://mozilla.org` | *(no referrer)* | ### `strict-origin` | From document | Navigation to | Referrer used | | --- | --- | --- | | `https://example.com/page` | `https://mozilla.org` | `https://example.com/` | | `https://example.com/page` | **http**://example.com | *(no referrer)* | | **http**://example.com/page | *anywhere* | `http://example.com/` | ### `strict-origin-when-cross-origin` | From document | Navigation to | Referrer used | | --- | --- | --- | | `https://example.com/page` | `https://example.com/otherpage` | `https://example.com/page` | | `https://example.com/page` | `https://mozilla.org` | `https://example.com/` | | `https://example.com/page` | **http**://example.com | *(no referrer)* | ### `unsafe-url` | From document | Navigation to | Referrer used | | --- | --- | --- | | `https://example.com/page?q=123` | *anywhere* | `https://example.com/page?q=123` | ### Specify a fallback policy If you want to specify a fallback policy in case the desired policy hasn't got wide enough browser support, use a comma-separated list with the desired policy specified last: ``` Referrer-Policy: no-referrer, strict-origin-when-cross-origin ``` In the above scenario, `no-referrer` is used only if the browser does not support the `strict-origin-when-cross-origin` policy. **Note:** Specifying multiple values is only supported in the `Referrer-Policy` HTTP header, and not in the `referrerpolicy` attribute. Browser-specific preferences/settings ------------------------------------- ### Firefox preferences You can configure the *default* referrer policy in Firefox preferences. The preference names are version specific: * Firefox version 59 and later: `network.http.referer.defaultPolicy` (and `network.http.referer.defaultPolicy.pbmode` for private networks) * Firefox versions 53 to 58: `network.http.referer.userControlPolicy` All of these settings take the same set of values: `0 = no-referrer`, `1 = same-origin`, `2 = strict-origin-when-cross-origin`, `3 = no-referrer-when-downgrade`. Specifications -------------- | Specification | | --- | | [Referrer Policy # referrer-policy-header](https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Referrer-Policy` | 56 | 79 | 50 | No | 43 | 11.1 | 56 | 56 | 50 | 43 | 12 | 7.2 | | `default_strict-origin-when-cross-origin` | 85 | 85 | 87 | No | 71 | 15 | 85 | 85 | 87 | 60 | 15 | 14.0 | | `same-origin` | 61 | 79 | 52 | No | 48 | 11.1 | 61 | 61 | 52 | 45 | 12 | 7.2 | | `strict-origin` | 61 | 79 | 52 | No | 48 | 11.1 | 61 | 61 | 52 | 45 | 12 | 7.2 | | `strict-origin-when-cross-origin` | 61 | 79 | 52 | No | 48 | 11.1 | 61 | 61 | 52 | 45 | 12 | 7.2 | See also -------- * [Web security > Referer header: privacy and security concerns](https://developer.mozilla.org/en-US/docs/Web/Security/Referer_header:_privacy_and_security_concerns) * [HTTP referer on Wikipedia](https://en.wikipedia.org/wiki/HTTP_referer) * When using [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API): [`Request.referrerPolicy`](https://developer.mozilla.org/en-US/docs/Web/API/Request/referrerPolicy) * The obsolete [`Content-Security-Policy`](content-security-policy)'s [`referrer`](content-security-policy/referrer) Deprecated directive. * [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) * [Tighter Control Over Your Referrers – Mozilla Security Blog](https://blog.mozilla.org/security/2015/01/21/meta-referrer/) http Upgrade-Insecure-Requests Upgrade-Insecure-Requests ========================= Upgrade-Insecure-Requests ========================= The HTTP `Upgrade-Insecure-Requests` request header sends a signal to the server expressing the client's preference for an encrypted and authenticated response, and that it can successfully handle the [`upgrade-insecure-requests`](content-security-policy/upgrade-insecure-requests) [CSP](../csp) directive. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Upgrade-Insecure-Requests: 1 ``` Examples -------- A client's request signals to the server that it supports the upgrade mechanisms of [`upgrade-insecure-requests`](content-security-policy/upgrade-insecure-requests): ``` GET / HTTP/1.1 Host: example.com Upgrade-Insecure-Requests: 1 ``` The server can now redirect to a secure version of the site. A [`Vary`](vary) header can be used so that the site isn't served by caches to clients that don't support the upgrade mechanism. ``` Location: https://example.com/ Vary: Upgrade-Insecure-Requests ``` Specifications -------------- | Specification | | --- | | [Upgrade Insecure Requests # preference](https://w3c.github.io/webappsec-upgrade-insecure-requests/#preference) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Upgrade-Insecure-Requests` | 44 | 17 | 48 | No | 31 | 10.1 | 44 | 44 | 48 | 32 | 10.3 | 4.0 | See also -------- * [`Content-Security-Policy`](content-security-policy) * CSP [`upgrade-insecure-requests`](content-security-policy/upgrade-insecure-requests) directive http RTT RTT === RTT === **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. The `RTT` [Client hint](../client_hints) request header field provides the approximate round trip time on the application layer, in milliseconds. The RTT hint, unlike transport layer RTT, includes server processing time. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | The RTT value is rounded to the nearest 25 milliseconds to prevent fingerprinting; There are many other mechanisms an attacker might use to obtain similar round-trip information. The hint allows a server to choose what information is sent based on the network responsiveness/latency. For example, it might choose to send fewer resources. **Note:** The [`Vary`](vary) header is used in responses to indicate that a different resource is sent for every different value of the header (see [HTTP Caching > Varying responses](../caching#varying_responses)). Even if [`RTT`](rtt) is used to configure what resources are sent consider omitting it in the [`Vary`](vary) header — it is likely to change often, which effectively makes the resource uncacheable. Syntax ------ ``` RTT: <number> ``` Directives ---------- <number> The approximate round trip time in milliseconds, rounded to the nearest 25 milliseconds. Examples -------- A server first needs to opt in to receive the `RTT` header by sending the [`Accept-CH`](accept-ch) response header containing `RTT`. ``` Accept-CH: RTT ``` Then on subsequent requests the client might send an `RTT` header back: ``` RTT: 125 ``` Specifications -------------- | Specification | | --- | | [Network Information API # rtt-request-header-field](https://wicg.github.io/netinfo/#rtt-request-header-field) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `RTT` | 67 The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | ≤79 The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | No | No | 54 The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | No | 67 The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | 67 The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | No | 48 The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | No | 9.0 The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | See also -------- * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * Network client hints + [`Downlink`](downlink) + [`ECT`](ect) + [`Save-Data`](save-data) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) * [`NetworkInformation.effectiveType`](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/effectiveType) http Accept-Patch Accept-Patch ============ Accept-Patch ============ The `Accept-Patch` response HTTP header advertises which media-type the server is able to understand in a PATCH request. `Accept-Patch` in response to any method means that PATCH is allowed on the resource identified by the Request-URI. Two common cases lead to this: A server receiving a PATCH request with an unsupported media type could reply with [`415`](../status/415) `Unsupported Media Type` and an Accept-Patch header referencing one or more supported media types. **Note:** * An IANA registry maintains [a complete list of official content encodings](https://www.iana.org/assignments/http-parameters/http-parameters.xml#http-parameters-1). * Two others content encoding, `bzip` and `bzip2`, are sometimes used, though not standard. They implement the algorithm used by these two UNIX programs. Note that the first one was discontinued due to patent licensing problems. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Accept-Patch: application/example, text/example Accept-Patch: text/example;charset=utf-8 Accept-Patch: application/merge-patch+json ``` Directives ---------- None Examples -------- ``` Accept-Patch: application/example, text/example Accept-Patch: text/example;charset=utf-8 Accept-Patch: application/merge-patch+json ``` Specifications -------------- | Specification | | --- | | [RFC 5789 # section-3.1](https://www.rfc-editor.org/rfc/rfc5789#section-3.1) | Browser compatibility --------------------- See also -------- * Http method [`PATCH`](../methods/patch) * HTTP Semantic and context [RFC 7231, section 4.3.4: PUT](https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.4) http X-Forwarded-Host X-Forwarded-Host ================ X-Forwarded-Host ================ The `X-Forwarded-Host` (XFH) header is a de-facto standard header for identifying the original host requested by the client in the [`Host`](host) HTTP request header. Host names and ports of reverse proxies (load balancers, CDNs) may differ from the origin server handling the request, in that case the `X-Forwarded-Host` header is useful to determine which Host was originally used. This header is used for debugging, statistics, and generating location-dependent content and by design it exposes privacy sensitive information, such as the IP address of the client. Therefore the user's privacy must be kept in mind when deploying this header. A standardized version of this header is the HTTP [`Forwarded`](forwarded) header. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` X-Forwarded-Host: <host> ``` Directives ---------- <host> The domain name of the forwarded server. Examples -------- ``` X-Forwarded-Host: id42.example-cdn.com ``` Specifications -------------- Not part of any current specification. The standardized version of this header is [`Forwarded`](forwarded). See also -------- * [`Host`](host) * [`Forwarded`](forwarded) * [`X-Forwarded-For`](x-forwarded-for) * [`X-Forwarded-Proto`](x-forwarded-proto) http Downlink Downlink ======== Downlink ======== **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. The `Downlink` [Client hint](../client_hints) request header field provides the approximate bandwidth of the client's connection to the server, in Mbps. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | The `Downlink` value is given in Mbps and rounded to the nearest 25 kilobits per second to prevent fingerprinting; There are many other mechanisms an attacker might use to obtain similar information. The hint allows a server to choose what information is sent based on the network bandwidth. For example, a server might choose to send smaller versions of images and other resources on low bandwidth networks. **Note:** The [`Vary`](vary) header is used in responses to indicate that a different resource is sent for every different value of the header (see [HTTP Caching > Varying responses](../caching#varying_responses)). Even if [`Downlink`](downlink) is used to configure what resources are sent, consider omitting it in the [`Vary`](vary) header — it is likely to change often, which effectively makes the resource uncacheable. Syntax ------ ``` Downlink: <number> ``` Directives ---------- <number> The downlink rate in Mbps, rounded to the nearest 25 kilobits. Examples -------- A server first needs to opt in to receive the `Downlink` header by sending the [`Accept-CH`](accept-ch) response header containing `Downlink`. ``` Accept-CH: Downlink ``` Then on subsequent requests the client might send a `Downlink` header back: ``` Downlink: 1.7 ``` Specifications -------------- | Specification | | --- | | [Network Information API # downlink-request-header-field](https://wicg.github.io/netinfo/#downlink-request-header-field) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Downlink` | 67 The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | ≤79 The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | No | No | 54 The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | No | 67 The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | 67 The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | No | 48 The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | No | 9.0 The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | See also -------- * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * Network client hints + [`RTT`](rtt) + [`ECT`](ect) + [`Save-Data`](save-data) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) * [`NetworkInformation.effectiveType`](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/effectiveType)
programming_docs
http Connection Connection ========== Connection ========== The `Connection` general header controls whether the network connection stays open after the current transaction finishes. If the value sent is `keep-alive`, the connection is persistent and not closed, allowing for subsequent requests to the same server to be done. **Warning:** Connection-specific header fields such as [`Connection`](connection) and [`Keep-Alive`](keep-alive) are prohibited in [HTTP/2](https://httpwg.org/specs/rfc9113.html#ConnectionSpecific) and [HTTP/3](https://httpwg.org/specs/rfc9114.html#header-formatting). Chrome and Firefox ignore them in HTTP/2 responses, but Safari conforms to the HTTP/2 spec requirements and does not load any response that contains them. Except for the standard hop-by-hop headers ([`Keep-Alive`](keep-alive), [`Transfer-Encoding`](transfer-encoding), [`TE`](te), [`Connection`](connection), [`Trailer`](trailer), [`Upgrade`](upgrade), [`Proxy-Authorization`](proxy-authorization) and [`Proxy-Authenticate`](proxy-authenticate)), any hop-by-hop headers used by the message must be listed in the `Connection` header, so that the first proxy knows it has to consume them and not forward them further. Standard hop-by-hop headers are also required to be listed. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Connection: keep-alive Connection: close ``` Directives ---------- `close` Indicates that either the client or the server would like to close the connection. This is the default on HTTP/1.0 requests. any comma-separated list of HTTP headers [Usually `keep-alive` only] Indicates that the client would like to keep the connection open. Keeping a connection open is the default on HTTP/1.1 requests. The list of headers are the name of the header to be removed by the first non-transparent proxy or cache in-between: these headers define the connection between the emitter and the first entity, not the destination node. Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.connection](https://httpwg.org/specs/rfc9110.html#field.connection) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Connection` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | http Allow Allow ===== Allow ===== The `Allow` header lists the set of methods supported by a resource. This header must be sent if the server responds with a [`405`](../status/405) `Method Not Allowed` status code to indicate which request methods can be used. An empty `Allow` header indicates that the resource allows no request methods, which might occur temporarily for a given resource, for example. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Allow: <http-methods> ``` Directives ---------- <http-methods> The comma-separated list of allowed [HTTP request methods](../methods). Examples -------- ``` Allow: GET, POST, HEAD ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.allow](https://httpwg.org/specs/rfc9110.html#field.allow) | See also -------- * [`405`](../status/405) * [`Server`](server) http Range Range ===== Range ===== The `Range` HTTP request header indicates the part of a document that the server should return. Several parts can be requested with one `Range` header at once, and the server may send back these ranges in a multipart document. If the server sends back ranges, it uses the [`206 Partial Content`](../status/206) for the response. If the ranges are invalid, the server returns the [`416 Range Not Satisfiable`](../status/416) error. The server can also ignore the `Range` header and return the whole document with a [`200`](../status/200) status code. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Range: <unit>=<range-start>- Range: <unit>=<range-start>-<range-end> Range: <unit>=<range-start>-<range-end>, <range-start>-<range-end> Range: <unit>=<range-start>-<range-end>, <range-start>-<range-end>, <range-start>-<range-end> Range: <unit>=-<suffix-length> ``` Directives ---------- <unit> The unit in which ranges are specified. This is usually `bytes`. <range-start> An integer in the given unit indicating the beginning of the request range. <range-end> An integer in the given unit indicating the end of the requested range. This value is optional and, if omitted, the end of the document is taken as the end of the range. <suffix-length> An integer in the given unit indicating the number of units at the end of the file to return. Examples -------- Requesting three ranges from the file. ``` Range: bytes=200-1000, 2000-6576, 19000- ``` The ranges-specifier value `19000-` specifies `19000` as the first position, and omits any last position — in order to indicate that all bytes from 19000 onward are part of the third range. Requesting the first 500 and last 500 bytes of the file. The request may be rejected by the server if the ranges overlap. ``` Range: bytes=0-499, -500 ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.range](https://httpwg.org/specs/rfc9110.html#field.range) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Range` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`If-Range`](if-range) * [`Content-Range`](content-range) * [`Content-Type`](content-type) * [`206 Partial Content`](../status/206) * [`416 Range Not Satisfiable`](../status/416) http Location Location ======== Location ======== The `Location` response header indicates the URL to redirect a page to. It only provides a meaning when served with a `3xx` (redirection) or `201` (created) status response. In cases of redirection, the HTTP method used to make the new request to fetch the page pointed to by `Location` depends on the original method and the kind of redirection: * [`303`](../status/303) (See Other) responses always lead to the use of a [`GET`](../methods/get) method. * [`307`](../status/307) (Temporary Redirect) and [`308`](../status/308) (Permanent Redirect) don't change the method used in the original request. * [`301`](../status/301) (Moved Permanently) and [`302`](../status/302) (Found) don't change the method most of the time, though older user-agents may (so you basically don't know). All responses with one of these status codes send a `Location` header. In cases of resource creation, it indicates the URL to the newly created resource. `Location` and [`Content-Location`](content-location) are different. `Location` indicates the target of a redirection or the URL of a newly created resource. [`Content-Location`](content-location) indicates the direct URL to use to access the resource when [content negotiation](../content_negotiation) happened, without the need of further content negotiation. `Location` is a header associated with the response, while [`Content-Location`](content-location) is associated with the entity returned. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Location: <url> ``` Directives ---------- <url> A relative (to the request URL) or absolute URL. Examples -------- ``` Location: /index.html ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.location](https://httpwg.org/specs/rfc9110.html#field.location) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Location` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Content-Location`](content-location) * Status of responses including a `Location` header: [`201`](../status/201), [`301`](../status/301), [`302`](../status/302), [`303`](../status/303), [`307`](../status/307), [`308`](../status/308). http Sec-WebSocket-Accept Sec-WebSocket-Accept ==================== Sec-WebSocket-Accept ==================== The **Sec-WebSocket-Accept** header is used in the websocket opening handshake. It would appear in the response headers. That is, this is header is sent from server to client to inform that server is willing to initiate a websocket connection. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Sec-WebSocket-Accept: <hashed key> ``` Directives ---------- <hashed key> The server takes the value of the Sec-WebSocket-Key sent in the handshake request, appends `258EAFA5-E914-47DA-95CA-C5AB0DC85B11`, takes SHA-1 of the new value, and is then [base64](https://developer.mozilla.org/en-US/docs/Glossary/Base64) encoded. Examples -------- ``` Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= ``` Specifications -------------- **No specification found**No specification data found for `http.headers.Sec-WebSocket-Accept`. [Check for problems with this page](#on-github) or contribute a missing `spec_url` to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). Also make sure the specification is included in [w3c/browser-specs](https://github.com/w3c/browser-specs). See also -------- * [`Sec-WebSocket-Key`](sec-websocket-key) Browser compatibility --------------------- No compatibility data found for `http.headers.Sec-WebSocket-Accept`. [Check for problems with this page](#on-github) or contribute missing data to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). http Referer Referer ======= Referer ======= The `Referer` HTTP request header contains the absolute or partial address from which a resource has been requested. The `Referer` header allows a server to identify referring pages that people are visiting from or where requested resources are being used. This data can be used for analytics, logging, optimized caching, and more. When you click a link, the `Referer` contains the address of the page that includes the link. When you make resource requests to another domain, the `Referer` contains the address of the page that uses the requested resource. The `Referer` header can contain an *origin*, *path*, and *querystring*, and may not contain URL fragments (i.e. `#section`) or `username:password` information. The request's *referrer policy* defines the data that can be included. See [`Referrer-Policy`](referrer-policy) for more [information](referrer-policy#directives) and [examples](referrer-policy#examples). **Note:** The header name "referer" is actually a misspelling of the word "referrer". See [HTTP referer on Wikipedia](https://en.wikipedia.org/wiki/HTTP_referer) for more details. **Warning:** This header may have undesirable consequences for user security and privacy. See [Referer header: privacy and security concerns](https://developer.mozilla.org/en-US/docs/Web/Security/Referer_header:_privacy_and_security_concerns) for more information and mitigation hints. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Referer: <url> ``` Directives ---------- <url> An absolute or partial address of the web page that makes the request. URL fragments (i.e. `#section`) and userinfo (i.e. `username:password` in `https\://username:password\@example.com/foo/bar/`) are not included. Origin, path, and querystring may be included, depending on the [referrer policy](referrer-policy#directives). Examples -------- ``` Referer: https://developer.mozilla.org/en-US/docs/Web/JavaScript Referer: https://example.com/page?q=123 Referer: https://example.com/ ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.referer](https://httpwg.org/specs/rfc9110.html#field.referer) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Referer` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `length_limit_4096B` | 77 | 79 | 70 | No | 64 | 14 | 77 | 77 | No | 55 | 14 | 12.0 | See also -------- * [HTTP referer on Wikipedia](https://en.wikipedia.org/wiki/HTTP_referer) * [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API): [`Request.referrerPolicy`](https://developer.mozilla.org/en-US/docs/Web/API/Request/referrerPolicy) * The obsolete [`Content-Security-Policy`](content-security-policy) [`referrer`](content-security-policy/referrer) Deprecated directive. * [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) * [Tighter Control Over Your Referrers – Mozilla Security Blog](https://blog.mozilla.org/security/2015/01/21/meta-referrer/) http Early-Data Early-Data ========== Early-Data ========== **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. The `Early-Data` header is set by an intermediary to indicate that the request has been conveyed in [TLS early data](https://developer.mozilla.org/en-US/docs/Web/Security/Transport_Layer_Security#tls_1.3), and also indicates that the intermediary understands the [`425 (Too Early)`](../status/425) status code. The `Early-Data` header is **not** set by the originator of the request (i.e., a browser). | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Early-Data: 1 ``` Examples -------- ``` GET /resource HTTP/1.0 Host: example.com Early-Data: 1 ``` Specifications -------------- | Specification | | --- | | [Using Early Data in HTTP # header](https://httpwg.org/specs/rfc8470.html#header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Early-Data` | No | No | 58 | No | No | No | No | No | 58 | No | No | No | http From From ==== From ==== The `From` request header contains an Internet email address for a human user who controls the requesting user agent. If you are running a robotic user agent (e.g. a crawler), the `From` header must be sent, so you can be contacted if problems occur on servers, such as if the robot is sending excessive, unwanted, or invalid requests. **Warning:** You must not use the `From` header for access control or authentication. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` From: <email> ``` Directives ---------- <email> A machine-usable email address. Examples -------- ``` From: [email protected] ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.from](https://httpwg.org/specs/rfc9110.html#field.from) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `From` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Host`](host) http Sec-CH-UA-Full-Version Sec-CH-UA-Full-Version ====================== Sec-CH-UA-Full-Version ====================== **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). **Note:** This is being replaced by the [`Sec-CH-UA-Full-Version-List`](sec-ch-ua-full-version-list). The `Sec-CH-UA-Full-Version` [user agent client hint](../client_hints#user-agent_client_hints) request header provides the user-agent's full version string. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Sec-CH-UA-Full-Version: <version> ``` ### Directives `<version>` A string containing the full version number, like "96.0.4664.93". Examples -------- A server requests the `Sec-CH-UA-Full-Version` header by including the [`Accept-CH`](accept-ch) in a *response* to any request from the client, using the name of the desired header as a token: ``` HTTP/1.1 200 OK Accept-CH: Sec-CH-UA-Full-Version ``` The client may choose to provide the hint, and add the `Sec-CH-UA-Full-Version` header to subsequent requests. For example, the client might add the header as shown: ``` GET /GET /my/page HTTP/1.1 Host: example.site Sec-CH-UA: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96" Sec-CH-UA-Mobile: ?0 Sec-CH-UA-Full-Version: "96.0.4664.110" Sec-CH-UA-Platform: "Windows" ``` Specifications -------------- | Specification | | --- | | [User-Agent Client Hints # sec-ch-ua-full-version](https://wicg.github.io/ua-client-hints/#sec-ch-ua-full-version) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Sec-CH-UA-Full-Version` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | See also -------- * [Client hints](../client_hints) * [User-Agent Client Hints API](https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API) * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary)
programming_docs
http DNT DNT === DNT === **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. The `DNT` (**D**o **N**ot **T**rack) request header indicates the user's tracking preference. It lets users indicate whether they would prefer privacy rather than personalized content. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` DNT: 0 DNT: 1 DNT: null ``` Directives ---------- 0 The user prefers to allow tracking on the target site. 1 The user prefers not to be tracked on the target site. null The user has not specified a preference about tracking. Examples -------- ### Reading Do Not Track status from JavaScript The user's DNT preference can also be read from JavaScript using the [`Navigator.doNotTrack`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/doNotTrack) property: ``` navigator.doNotTrack; // "0" or "1" ``` Specifications -------------- | Specification | | --- | | [Tracking Preference Expression (DNT) # dnt-header-field](https://www.w3.org/TR/tracking-dnt/#dnt-header-field) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `DNT` | 23 | 12 | 4 | 9 | Yes | 6-12.1 | Yes | Yes | Yes | Yes | Yes-12.2 | Yes | See also -------- * [`Navigator.doNotTrack`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/doNotTrack) * [`Tk`](tk) header * [Do Not Track on Wikipedia](https://en.wikipedia.org/wiki/Do_Not_Track) * [What Does the "Track" in "Do Not Track" Mean? – EFF](https://www.eff.org/deeplinks/2011/02/what-does-track-do-not-track-mean) * [DNT on Electronic Frontier Foundation](https://www.eff.org/issues/do-not-track) * DNT browser settings help: + [Firefox](https://support.mozilla.org/en-US/kb/how-do-i-turn-do-not-track-feature) + [Chrome](https://support.google.com/chrome/answer/2790761) http Save-Data Save-Data ========= Save-Data ========= **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. The `Save-Data` [network client hint](../client_hints#network_client_hints) request header field is a boolean which indicates the client's preference for reduced data usage. This could be for reasons such as high transfer costs, slow connection speeds, etc. `Save-Data` is a [low entropy hint](../client_hints#low_entropy_hints), and hence may be sent by the client even if not requested by the server using an [`Accept-CH`](accept-ch) response header. Further, it should be used to reduce data sent to the client irrespective of the values of other client hints that indicate network capability, like [`Downlink`](downlink) and [`RTT`](rtt). | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [CORS-safelisted response header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header) | no | A value of `On` indicates explicit user opt-in into a reduced data usage mode on the client, and when communicated to origins allows them to deliver alternative content to reduce the data downloaded such as smaller image and video resources, different markup and styling, disabled polling and automatic updates, and so on. **Note:** Disabling HTTP/2 Server Push ([RFC 7540, section 8.2: Server Push](https://datatracker.ietf.org/doc/html/rfc7540#section-8.2)) might be desirable too for reducing data downloads. Syntax ------ ``` Save-Data: <sd-token> ``` Directives ---------- `<sd-token>` A value indicating whether the client wants to opt in to reduced data usage mode. `on` indicates yes, while `off` (the default) indicates no. Examples -------- The [`Vary`](vary) header ensures that the content is cached properly (for instance ensuring that the user is not served a lower-quality image from the cache when `Save-Data` header is no longer present [*e.g.* after having switched from cellular to Wi-Fi]). ### With `Save-Data: on` Request: ``` GET /image.jpg HTTP/1.0 Host: example.com Save-Data: on ``` Response: ``` HTTP/1.0 200 OK Content-Length: 102832 Vary: Accept-Encoding, Save-Data Cache-Control: public, max-age=31536000 Content-Type: image/jpeg […] ``` ### Without `Save-Data` Request: ``` GET /image.jpg HTTP/1.0 Host: example.com ``` Response: ``` HTTP/1.0 200 OK Content-Length: 481770 Vary: Accept-Encoding, Save-Data Cache-Control: public, max-age=31536000 Content-Type: image/jpeg […] ``` Specifications -------------- | Specification | | --- | | [Save Data API # save-data-request-header-field](https://wicg.github.io/savedata/#save-data-request-header-field) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Save-Data` | 49 | ≤79 | No | No | 35 | No | 49 | 49 | No | 35 | No | 5.0 | See also -------- * [Help Your Users `Save-Data` - CSS Tricks](https://css-tricks.com/help-users-save-data/) * [Delivering Fast and Light Applications with Save-Data - web.dev](https://web.dev/optimizing-content-efficiency-save-data/) * [`Vary`](vary) header which indicates that the content served varies depending on the value of `Save-Data` (see [HTTP Caching > Varying responses](../caching#varying_responses)) * CSS @media feature [`prefers-reduced-data`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-data) Experimental * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * [`NetworkInformation.saveData`](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/saveData) http Server Server ====== Server ====== The `Server` header describes the software used by the origin server that handled the request — that is, the server that generated the response. **Warning:** Avoid overly-detailed `Server` values, as they can reveal information that may make it (slightly) easier for attackers to exploit known security holes. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Server: <product> ``` Directives ---------- <product> A name of the software or the product that handled the request. Usually in a format similar to [`User-Agent`](user-agent). How much detail to include is an interesting balance to strike; exposing the OS version is probably a bad idea, as mentioned in the earlier warning about overly-detailed values. However, exposed Apache versions helped browsers to work around a bug of the versions with [`Content-Encoding`](content-encoding) and [`Range`](range) in combination. Examples -------- ``` Server: Apache/2.4.1 (Unix) ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.server](https://httpwg.org/specs/rfc9110.html#field.server) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Server` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Allow`](allow) http Cookie Cookie ====== Cookie ====== The `Cookie` HTTP request header contains stored [HTTP cookies](../cookies) associated with the server (i.e. previously sent by the server with the [`Set-Cookie`](set-cookie) header or set in JavaScript using [`Document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie)). The `Cookie` header is optional and may be omitted if, for example, the browser's privacy settings block cookies. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Cookie: <cookie-list> Cookie: name=value Cookie: name=value; name2=value2; name3=value3 ``` Directives ---------- <cookie-list> A list of name-value pairs in the form of `<cookie-name>=<cookie-value>`. Pairs in the list are separated by a semicolon and a space (`'; '`). Examples -------- ``` Cookie: PHPSESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; \_gat=1 ``` Specifications -------------- | Specification | | --- | | [HTTP State Management Mechanism # cookie](https://httpwg.org/specs/rfc6265.html#cookie) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Cookie` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Set-Cookie`](set-cookie) * [`Document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) http Sec-CH-UA Sec-CH-UA ========= Sec-CH-UA ========= **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). The `Sec-CH-UA` [user agent client hint](../client_hints#user-agent_client_hints) request header provides the user-agent's branding and significant version information. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | The `Sec-CH-UA` header provides the brand and significant version for each brand associated with the browser in a comma-separated list. A brand is a commercial name for the user agent like: Chromium, Opera, Google Chrome, Microsoft Edge, Firefox, and Safari. A user agent might have several associated brands. For example, Opera, Chrome, and Edge are all based on Chromium, and will provide both brands in the `Sec-CH-UA` header. The *significant version* is the "marketing" version identifier that is used to distinguish between major releases of the brand. For example a Chromium build with *full version number* "96.0.4664.45" has a significant version number of "96". The header therefore allows the server to customize its response based on both shared brands and on particular customizations in their respective versions. `Sec-CH-UA` is a [low entropy hint](../client_hints#low_entropy_hints). Unless blocked by a user agent permission policy, it is sent by default, without the server opting in by sending [`Accept-CH`](accept-ch). The header may include "fake" brands in any position and with any name. This is a feature designed to prevent servers from rejecting unknown user agents outright, forcing user agents to lie about their brand identity. **Note:** [`Sec-CH-UA-Full-Version-List`](sec-ch-ua-full-version-list) is the same as `Sec-CH-UA`, but includes the full version number rather than the significant version number for each brand. Syntax ------ A comma separated list of brands in the user agent brand list, and their associated significant version number. The syntax for a single entry has the following format: ``` Sec-CH-UA: "<brand>";v="<significant version>", ... ``` ### Directives `<brand>` A brand associated with the user agent, like "Chromium", "Google Chrome", or an intentionally incorrect brand like `"Not A;Brand"`. `<significant version>` The "marketing" version number associated with distinguishable web-exposed features. Examples -------- `Sec-CH-UA` is a [low entropy hint](../client_hints#low_entropy_hints). Unless explicitly blocked by a user agent policy, it will be sent in all requests (without the server having to opt in by sending [`Accept-CH`](accept-ch)). Strings from Chromium, Chrome, Edge, and Opera desktop browsers are shown below. Note that they all share the "Chromium" brand, but have an additional brand indicating their origin. They also have an intentionally incorrect brand string, which may appear in any position and have different text. ``` Sec-CH-UA: "(Not(A:Brand";v="8", "Chromium";v="98" ``` ``` Sec-CH-UA: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96" ``` ``` Sec-CH-UA: " Not A;Brand";v="99", "Chromium";v="96", "Microsoft Edge";v="96" ``` ``` Sec-CH-UA: "Opera";v="81", " Not;A Brand";v="99", "Chromium";v="95" ``` Specifications -------------- | Specification | | --- | | [User-Agent Client Hints # sec-ch-ua](https://wicg.github.io/ua-client-hints/#sec-ch-ua) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Sec-CH-UA` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | See also -------- * [Client hints](../client_hints) * [User-Agent Client Hints API](https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API) * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) http Host Host ==== Host ==== The `Host` request header specifies the host and port number of the server to which the request is being sent. If no port is included, the default port for the service requested is implied (e.g., `443` for an HTTPS URL, and `80` for an HTTP URL). A `Host` header field must be sent in all HTTP/1.1 request messages. A [`400`](../status/400) (Bad Request) status code may be sent to any HTTP/1.1 request message that lacks or contains more than one `Host` header field. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Host: <host>:<port> ``` Directives ---------- <host> the domain name of the server (for virtual hosting). <port> Optional TCP port number on which the server is listening. Examples -------- ``` Host: developer.mozilla.org ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.host](https://httpwg.org/specs/rfc9110.html#field.host) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Host` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`400`](../status/400) * [`<base>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base) http Origin Origin ====== Origin ====== The `Origin` request header indicates the [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) (scheme, hostname, and port) that *caused* the request. For example, if a user agent needs to request resources included in a page, or fetched by scripts that it executes, then the origin of the page may be included in the request. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Origin: null Origin: <scheme>://<hostname> Origin: <scheme>://<hostname>:<port> ``` Directives ---------- `null` The origin is "privacy sensitive", or is an *opaque origin* as defined by the HTML specification (specific cases are listed in the [description](#description) section). `<scheme>` The protocol that is used. Usually, it is the HTTP protocol or its secured version, HTTPS. `<hostname>` The domain name or the IP address of the origin server. `<port>` Optional Port number on which the server is listening. If no port is given, the default port for the requested service is implied (e.g., "80" for an HTTP URL) . Description ----------- The `Origin` header is similar to the [`Referer`](referer) header, but does not disclose the path, and may be `null`. It is used to provide the "security context" for the origin request, except in cases where the origin information would be sensitive or unnecessary. Broadly speaking, user agents add the [`Origin`](origin) request header to: * [cross origin](https://developer.mozilla.org/en-US/docs/Glossary/CORS) requests. * [same-origin](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) requests except for [`GET`](../methods/get) or [`HEAD`](../methods/head) requests (i.e. they are added to same-origin [`POST`](../methods/post), [`OPTIONS`](../methods/options), [`PUT`](../methods/put), [`PATCH`](../methods/patch), and [`DELETE`](../methods/delete) requests). There are some exceptions to the above rules; for example, if a cross-origin [`GET`](../methods/get) or [`HEAD`](../methods/head) request is made in [no-cors mode](https://developer.mozilla.org/en-US/docs/Web/API/Request/mode#value), the `Origin` header will not be added. The `Origin` header value may be `null` in a number of cases, including (non-exhaustively): * Origins whose scheme is not one of `http`, `https`, `ftp`, `ws`, `wss`, or `gopher` (including `blob`, `file` and `data`). * Cross-origin images and media data, including that in `<img>`, `<video>` and `<audio>` elements. * Documents created programmatically using `createDocument()`, generated from a `data:` URL, or that do not have a creator browsing context. * Redirects across origins. * iframes with a sandbox attribute that doesn't contain the value `allow-same-origin`. * Responses that are network errors. * [`Referrer-Policy`](referrer-policy) set to `no-referrer` for non-`cors` request modes (e.g. simple form posts). **Note:** There is a more detailed listing of cases that may return `null` on Stack Overflow: [When do browsers send the Origin header? When do browsers set the origin to null?](https://stackoverflow.com/questions/42239643/when-do-browsers-send-the-origin-header-when-do-browsers-set-the-origin-to-null/42242802) Examples -------- ``` Origin: https://developer.mozilla.org ``` ``` Origin: http://developer.mozilla.org:80 ``` Specifications -------------- | Specification | | --- | | [The Web Origin Concept # section-7](https://www.rfc-editor.org/rfc/rfc6454#section-7) | | [Fetch Standard # origin-header](https://fetch.spec.whatwg.org/#origin-header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Origin` | Yes | 12 Before Edge 79, this header was not sent with `POST` requests. | 70 Yes Not sent with `POST` requests until Firefox 58, see [bug 446344](https://bugzil.la/446344). | Yes | Yes | Yes | Yes | Yes | 79 Yes Not sent with `POST` requests until Firefox 58, see [bug 446344](https://bugzil.la/446344). | Yes | Yes | Yes | See also -------- * [`Host`](host) * [`Referer`](referer) * [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) * [When do browsers send the Origin header? When do browsers set the origin to null?](https://stackoverflow.com/questions/42239643/when-do-browsers-send-the-origin-header-when-do-browsers-set-the-origin-to-null/42242802) (Stack Overflow)
programming_docs
http Content-Security-Policy Content-Security-Policy ======================= Content-Security-Policy ======================= The HTTP `Content-Security-Policy` response header allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. This helps guard against cross-site scripting attacks ([Cross-site\_scripting](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting)). For more information, see the introductory article on [Content Security Policy (CSP)](../csp). | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Content-Security-Policy: <policy-directive>; <policy-directive> ``` where `<policy-directive>` consists of: `<directive> <value>` with no internal punctuation. Directives ---------- ### Fetch directives [Fetch directives](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_directive) control the locations from which certain resource types may be loaded. [`child-src`](content-security-policy/child-src) Defines the valid sources for [web workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and nested browsing contexts loaded using elements such as [`<frame>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frame) and [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe). **Warning:** Instead of `child-src`, if you want to regulate nested browsing contexts and workers, you should use the [`frame-src`](content-security-policy/frame-src) and [`worker-src`](content-security-policy/worker-src) directives, respectively. [`connect-src`](content-security-policy/connect-src) Restricts the URLs which can be loaded using script interfaces [`default-src`](content-security-policy/default-src) Serves as a fallback for the other [fetch directives](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_directive). [`font-src`](content-security-policy/font-src) Specifies valid sources for fonts loaded using [`@font-face`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face). [`frame-src`](content-security-policy/frame-src) Specifies valid sources for nested browsing contexts loading using elements such as [`<frame>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frame) and [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe). [`img-src`](content-security-policy/img-src) Specifies valid sources of images and favicons. [`manifest-src`](content-security-policy/manifest-src) Specifies valid sources of application manifest files. [`media-src`](content-security-policy/media-src) Specifies valid sources for loading media using the [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) , [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) and [`<track>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track) elements. [`object-src`](content-security-policy/object-src) Specifies valid sources for the [`<object>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object), [`<embed>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed), and [`<applet>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/applet) elements. **Note:** Elements controlled by `object-src` are perhaps coincidentally considered legacy HTML elements and are not receiving new standardized features (such as the security attributes `sandbox` or `allow` for `<iframe>`). Therefore it is **recommended** to restrict this fetch-directive (e.g., explicitly set `object-src 'none'` if possible). [`prefetch-src`](content-security-policy/prefetch-src) Experimental Specifies valid sources to be prefetched or prerendered. [`script-src`](content-security-policy/script-src) Specifies valid sources for JavaScript and WebAssembly resources. [`script-src-elem`](content-security-policy/script-src-elem) Specifies valid sources for JavaScript [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) elements. [`script-src-attr`](content-security-policy/script-src-attr) Specifies valid sources for JavaScript inline event handlers. [`style-src`](content-security-policy/style-src) Specifies valid sources for stylesheets. [`style-src-elem`](content-security-policy/style-src-elem) Specifies valid sources for stylesheets [`<style>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style) elements and [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) elements with `rel="stylesheet"`. [`style-src-attr`](content-security-policy/style-src-attr) Specifies valid sources for inline styles applied to individual DOM elements. [`worker-src`](content-security-policy/worker-src) Specifies valid sources for [`Worker`](https://developer.mozilla.org/en-US/docs/Web/API/Worker), [`SharedWorker`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker), or [`ServiceWorker`](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker) scripts. ### Document directives Document directives govern the properties of a document or [worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) environment to which a policy applies. [`base-uri`](content-security-policy/base-uri) Restricts the URLs which can be used in a document's [`<base>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base) element. [`sandbox`](content-security-policy/sandbox) Enables a sandbox for the requested resource similar to the [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) [`sandbox`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox) attribute. ### Navigation directives Navigation directives govern to which locations a user can navigate or submit a form, for example. [`form-action`](content-security-policy/form-action) Restricts the URLs which can be used as the target of a form submissions from a given context. [`frame-ancestors`](content-security-policy/frame-ancestors) Specifies valid parents that may embed a page using [`<frame>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frame), [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe), [`<object>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object), [`<embed>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed), or [`<applet>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/applet). [`navigate-to`](content-security-policy) Experimental Restricts the URLs to which a document can initiate navigation by any means, including [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) (if [`form-action`](content-security-policy/form-action) is not specified), [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a), [`window.location`](https://developer.mozilla.org/en-US/docs/Web/API/Window/location), [`window.open`](https://developer.mozilla.org/en-US/docs/Web/API/Window/open), etc. ### Reporting directives Reporting directives control the reporting process of CSP violations. See also the [`Content-Security-Policy-Report-Only`](content-security-policy-report-only) header. [`report-uri`](content-security-policy/report-uri) Deprecated Instructs the user agent to report attempts to violate the Content Security Policy. These violation reports consist of [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON) documents sent via an HTTP `POST` request to the specified URI. **Warning:** Though the [`report-to`](content-security-policy/report-to) directive is intended to replace the deprecated `report-uri` directive, [`report-to`](content-security-policy/report-to) is not supported in most browsers yet. So for compatibility with current browsers while also adding forward compatibility when browsers get [`report-to`](content-security-policy/report-to) support, you can specify both `report-uri` and [`report-to`](content-security-policy/report-to): ``` Content-Security-Policy: …; report-uri https://endpoint.example.com; report-to groupname ``` In browsers that support [`report-to`](content-security-policy/report-to), the `report-uri` directive will be ignored. [`report-to`](content-security-policy/report-to) Fires a `SecurityPolicyViolationEvent`. ### Other directives [`require-sri-for`](content-security-policy/require-sri-for) Deprecated Non-standard Requires the use of [SRI](https://developer.mozilla.org/en-US/docs/Glossary/SRI) for scripts or styles on the page. [`require-trusted-types-for`](content-security-policy/require-trusted-types-for) Experimental Enforces [Trusted Types](https://w3c.github.io/trusted-types/dist/spec/) at the DOM XSS injection sinks. [`trusted-types`](content-security-policy/trusted-types) Experimental Used to specify an allow-list of [Trusted Types](https://w3c.github.io/trusted-types/dist/spec/) policies. Trusted Types allows applications to lock down DOM XSS injection sinks to only accept non-spoofable, typed values in place of strings. [`upgrade-insecure-requests`](content-security-policy/upgrade-insecure-requests) Instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for websites with large numbers of insecure legacy URLs that need to be rewritten. ### Deprecated directives [`block-all-mixed-content`](content-security-policy/block-all-mixed-content) Deprecated Prevents loading any assets using HTTP when the page is loaded using HTTPS. [`plugin-types`](content-security-policy/plugin-types) Deprecated Non-standard Restricts the set of plugins that can be embedded into a document by limiting the types of resources which can be loaded. [`referrer`](content-security-policy/referrer) Deprecated Non-standard Used to specify information in the [Referer](referer) (sic) header for links away from a page. Use the [`Referrer-Policy`](referrer-policy) header instead. Values ------ An overview of the allowed values are listed below. For detailed reference see [CSP Source Values](content-security-policy/sources#sources) and the documentation for individual directives. ### Keyword values `none` Won't allow loading of any resources. `self` Only allow resources from the current origin. `strict-dynamic` The trust granted to a script in the page due to an accompanying nonce or hash is extended to the scripts it loads. `report-sample` Require a sample of the violating code to be included in the violation report. ### Unsafe keyword values `unsafe-inline` Allow use of inline resources. `unsafe-eval` Allow use of dynamic code evaluation such as [`eval`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval), [`setImmediate`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate) Non-standard , and `window.execScript` Non-standard . `unsafe-hashes` Allows enabling specific inline event handlers. `unsafe-allow-redirects` Experimental TBD ### Hosts values * Host + Only allow loading of resources from a specific host, with optional scheme, port, and path. e.g. `example.com`, `*.example.com`, `https://*.example.com:12/path/to/file.js` + Path parts in the CSP that end in `/` match any path they are a prefix of. e.g. `example.com/api/` will match URLs like `example.com/api/users/new`. + Other path parts in the CSP are matched exactly e.g. `example.com/file.js` will match `http://example.com/file.js` and `https://example.com/file.js`, but not `https://example.com/file.js/file2.js` * Scheme + Only allow loading of resources over a specific scheme, should always end with "`:`". e.g. `https:`, `http:`, `data:` etc. ### Other values nonce-\* A cryptographic nonce (only used once) to allow scripts. The server must generate a unique nonce value each time it transmits a policy. It is critical to provide a nonce that cannot be guessed as bypassing a resource's policy is otherwise trivial. This is used in conjunction with the [script tag nonce attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-nonce). e.g. `nonce-DhcnhD3khTMePgXwdayK9BsMqXjhguVV` sha\*-\* sha256, sha384, or sha512. followed by a dash and then the sha\* value. e.g. `sha256-jzgBGA4UWFFmpOBq0JpdsySukE1FrEN5bUpoK8Z29fY=` CSP in workers -------------- [Workers](https://developer.mozilla.org/en-US/docs/Web/API/Worker) are in general *not* governed by the content security policy of the document (or parent worker) that created them. To specify a content security policy for the worker, set a `Content-Security-Policy` response header for the request which requested the worker script itself. The exception to this is if the worker script's origin is a globally unique identifier (for example, if its URL has a scheme of data or blob). In this case, the worker does inherit the content security policy of the document or worker that created it. Multiple content security policies ---------------------------------- The CSP mechanism allows multiple policies being specified for a resource, including via the `Content-Security-Policy` header, the [`Content-Security-Policy-Report-Only`](content-security-policy-report-only) header and a [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) element. You can use the `Content-Security-Policy` header more than once, as in the example below. Pay special attention to the [`connect-src`](content-security-policy/connect-src) directive here. Even though the second policy would allow the connection, the first policy contains `connect-src 'none'`. Adding additional policies *can only further restrict* the capabilities of the protected resource, which means that there will be no connection allowed and, as the strictest policy, `connect-src 'none'` is enforced. ``` Content-Security-Policy: default-src 'self' http://example.com; connect-src 'none'; Content-Security-Policy: connect-src http://example.com/; script-src http://example.com/ ``` Examples -------- Example: Disable unsafe inline/eval, only allow loading of resources (images, fonts, scripts, etc.) over https: ### Using the HTTP header ``` Content-Security-Policy: default-src https: ``` ### Using the HTML meta element ``` <meta http-equiv="Content-Security-Policy" content="default-src https:" /> ``` Example: Pre-existing site that uses too much inline code to fix but wants to ensure resources are loaded only over HTTPS and to disable plugins: ``` Content-Security-Policy: default-src https: 'unsafe-eval' 'unsafe-inline'; object-src 'none' ``` Example: Do not implement the above policy yet; instead just report violations that would have occurred: ``` Content-Security-Policy-Report-Only: default-src https:; report-uri /csp-violation-report-endpoint/ ``` See [Mozilla Web Security Guidelines](https://infosec.mozilla.org/guidelines/web_security#Examples_5) for more examples. Specifications -------------- | Specification | | --- | | [Content Security Policy Level 3 # csp-header](https://w3c.github.io/webappsec-csp/#csp-header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Content-Security-Policy` | 25 14 | 14 | 23 4 | 10 Only supporting 'sandbox' directive. | 15 | 7 6 | Yes | Yes | 23 | Yes | 7 6 | Yes | | `base-uri` | 40 | 79 | 35 | No | 27 | 10 | Yes | Yes | 35 | Yes | 9.3 | Yes | | `block-all-mixed-content` | Yes | ≤79 | 48 | No | Yes | No | Yes | Yes | 48 | Yes | No | Yes | | `child-src` | 40 | 15 | 45 | No | 27 | 10 | Yes | Yes | 45 | Yes | 9.3 | Yes | | `connect-src` | 25 | 14 | 23 Before Firefox 50, ping attributes of <a> elements weren't covered by connect-src. | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `default-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `font-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `form-action` | 40 | 15 | 36 | No | 27 | 10 | Yes | Yes | 36 | Yes | 9.3 | Yes | | `frame-ancestors` | 40 | 15 | 33 Before Firefox 58, `frame-ancestors` is ignored in `Content-Security-Policy-Report-Only`. | No | 26 | 10 | Yes | Yes | 33 Before Firefox for Android 58, `frame-ancestors` is ignored in `Content-Security-Policy-Report-Only`. | Yes | 9.3 | Yes | | `frame-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `img-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `manifest-src` | Yes | 79 | 41 | No | Yes | No | Yes | Yes | 41 | Yes | No | Yes | | `media-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `meta-element-support` | Yes | ≤18 | 45 | No | Yes | Yes | Yes | Yes | 45 | Yes | Yes | Yes | | `object-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `plugin-types` | 40-90 | 15-90 | No | No | 27-76 | 10 | Yes-90 | Yes-90 | No | Yes-64 | 9.3 | Yes-15.0 | | `prefetch-src` | No See [bug 801561](https://crbug.com/801561). | No See [bug 801561](https://crbug.com/801561). | No See [bug 1457204](https://bugzil.la/1457204). | No | No See [bug 801561](https://crbug.com/801561). | No See [bug 185070](https://webkit.org/b/185070). | No See [bug 801561](https://crbug.com/801561). | No See [bug 801561](https://crbug.com/801561). | No See [bug 1457204](https://bugzil.la/1457204). | No See [bug 801561](https://crbug.com/801561). | No See [bug 185070](https://webkit.org/b/185070). | No See [bug 801561](https://crbug.com/801561). | | `referrer` | 33-56 | No | 37-62 | No | 20-43 | No | 4.4.3-56 | 33-56 | 37-62 | 20-43 | No | 2.0-6.0 | | `report-sample` | 59 | ≤79 | No | No | 46 | 15.4 | 59 | 59 | No | 43 | 15.4 | 7.0 | | `report-to` | 70 | 79 | No | No | 57 | No | 70 | 70 | No | 49 | No | 10.0 | | `report-uri` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `require-sri-for` | 54 | 79 | No | No | 41 | No | 54 | 54 | No | 41 | No | 6.0 | | `require-trusted-types-for` | 83 | 83 | No | No | 69 | No | 83 | 83 | No | 59 | No | 13.0 | | `sandbox` | 25 | 14 | 50 | 10 | 15 | 7 | Yes | Yes | 50 | Yes | 7 | Yes | | `script-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `script-src-attr` | 75 | 79 | 105 preview | No | 62 | No | 75 | 75 | No | 54 | No | 11.0 | | `script-src-elem` | 75 | 79 | 105 preview | No | 62 | No | 75 | 75 | No | 54 | No | 11.0 | | `strict-dynamic` | 52 | 79 | 52 | No | 39 | 15.4 | 52 | 52 | No | 41 | 15.4 | 6.0 | | `style-src` | 25 | 14 | 23 | No | 15 | 7 | Yes | Yes | 23 | Yes | 7 | Yes | | `style-src-attr` | 75 | 79 | 105 preview | No | 62 | No | 75 | 75 | No | 54 | No | 11.0 | | `style-src-elem` | 75 | 79 | 105 preview | No | 62 | No | 75 | 75 | No | 54 | No | 11.0 | | `trusted-types` | 83 | 83 | No | No | 69 | No | 83 | 83 | No | No | No | 13.0 | | `unsafe-hashes` | 69 | 79 | No See [bug 1343950](https://bugzil.la/1343950). | No | 56 | 15.4 | 69 | 69 | No See [bug 1343950](https://bugzil.la/1343950). | 48 | 15.4 | 10.0 | | `upgrade-insecure-requests` | 43 | 17 | 42 | No | 30 | 10.1 | 43 | 43 | 42 | 30 | 10.3 | 4.0 | | `worker-src` | 59 Chrome 59 and higher skips the deprecated `child-src` directive. | 79 | 58 | No | 46 Opera 46 and higher skips the deprecated `child-src` directive. | 15.5 | 59 Chrome 59 and higher skips the deprecated `child-src` directive. | 59 Chrome 59 and higher skips the deprecated `child-src` directive. | 58 | 43 Opera 43 and higher skips the deprecated `child-src` directive. | 15.5 | 7.0 | | `worker_support` | Yes | ≤79 | 50 | No | Yes | 10 | Yes | Yes | 50 | Yes | 10 | Yes | See also -------- * [`Content-Security-Policy-Report-Only`](content-security-policy-report-only) * [Learn about: Content Security Policy](../csp) * [Content Security in WebExtensions](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy) * [Adopting a strict policy](https://csp.withgoogle.com/docs/strict-csp.html) * [CSP Evaluator](https://github.com/google/csp-evaluator) - Evaluate your Content Security Policy
programming_docs
http Sec-Fetch-Mode Sec-Fetch-Mode ============== Sec-Fetch-Mode ============== The `Sec-Fetch-Mode` [fetch metadata request header](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_metadata_request_header) indicates the [mode](https://developer.mozilla.org/en-US/docs/Web/API/Request/mode) of the request. Broadly speaking, this allows a server to distinguish between: requests originating from a user navigating between HTML pages, and requests to load images and other resources. For example, this header would contain `navigate` for top level navigation requests, while `no-cors` is used for loading an image. | | | | --- | --- | | Header type | [Fetch Metadata Request Header](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_metadata_request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes (prefix `Sec-`) | | [CORS-safelisted request header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header) | no | Syntax ------ ``` Sec-Fetch-Mode: cors Sec-Fetch-Mode: navigate Sec-Fetch-Mode: no-cors Sec-Fetch-Mode: same-origin Sec-Fetch-Mode: websocket ``` Servers should ignore this header if it contains any other value. Directives ---------- **Note:** These directives correspond to the values in [`Request.mode`](https://developer.mozilla.org/en-US/docs/Web/API/Request/mode#value). `cors` The request is a [CORS protocol](../cors) request. `navigate` The request is initiated by navigation between HTML documents. `no-cors` The request is a no-cors request (see [`Request.mode`](https://developer.mozilla.org/en-US/docs/Web/API/Request/mode#value)). `same-origin` The request is made from the same origin as the resource that is being requested. `websocket` The request is being made to establish a [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) connection. Examples -------- If a user clicks on a page link to another page on the same origin, the resulting request would have the following headers (note that the mode is `navigate`): ``` Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: same-origin Sec-Fetch-User: ?1 ``` A cross-site request generated by an [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) element would result in a request with the following HTTP request headers (note that the mode is `no-cors`): ``` Sec-Fetch-Dest: image Sec-Fetch-Mode: no-cors Sec-Fetch-Site: cross-site ``` Specifications -------------- | Specification | | --- | | [Fetch Metadata Request Headers # sec-fetch-mode-header](https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Sec-Fetch-Mode` | 76 | 79 | 90 | No | 63 | No | 76 | 76 | 90 | 54 | No | 12.0 | See also -------- * Related headers + [`Sec-Fetch-Dest`](sec-fetch-dest) + [`Sec-Fetch-Site`](sec-fetch-site) + [`Sec-Fetch-User`](sec-fetch-user) * [Protect your resources from web attacks with Fetch Metadata](https://web.dev/fetch-metadata/) (web.dev) * [Fetch Metadata Request Headers playground](https://secmetadata.appspot.com/) (secmetadata.appspot.com) http Sec-CH-UA-Full-Version-List Sec-CH-UA-Full-Version-List =========================== Sec-CH-UA-Full-Version-List =========================== **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). The `Sec-CH-UA-Full-Version-List` [user agent client hint](../client_hints#user-agent_client_hints) request header provides the user-agent's branding and full version information. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | The `Sec-CH-UA-Full-Version-List` header provides the brand and full version information for each brand associated with the browser, in a comma-separated list. A brand is a commercial name for the user agent like: Chromium, Opera, Google Chrome, Microsoft Edge, Firefox, and Safari. A user agent might have several associated brands. For example, Opera, Chrome, and Edge are all based on Chromium, and will provide both brands in the `Sec-CH-UA-Full-Version-List` header. The header therefore allows the server to customize its response based on both shared brands and on particular customizations in their specific respective builds. The header may include "fake" brands in any position and with any name. This is a feature designed to prevent servers from rejecting unknown user agents outright, forcing user agents to lie about their brand identity. **Note:** This is similar to [`Sec-CH-UA`](sec-ch-ua), but includes the full version number instead of the significant version number for each brand. Syntax ------ A comma separated list of brands in the user agent brand list, and their associated full version number. The syntax for a single entry has the following format: ``` Sec-CH-UA-Full-Version-List: "<brand>";v="<full version>", ... ``` ### Directives `<brand>` A brand associated with the user agent, like "Chromium", "Google Chrome". This may be an intentionally incorrect brand like `" Not A;Brand"` or `"(Not(A:Brand"` (the actual value is expected change over time and be unpredictable). `<full version>` A full version number, such as 98.0.4750.0. Examples -------- A server requests the `Sec-CH-UA-Full-Version-List` header by including the [`Accept-CH`](accept-ch) in a *response* to any request from the client, using the name of the desired header as a token: ``` HTTP/1.1 200 OK Accept-CH: Sec-CH-UA-Full-Version-List ``` The client may choose to provide the hint, and add the `Sec-CH-UA-Full-Version-List` header to subsequent requests, as shown below: ``` GET /my/page HTTP/1.1 Host: example.site Sec-CH-UA: " Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98" Sec-CH-UA-Mobile: ?0 Sec-CH-UA-Full-Version-List: " Not A;Brand";v="99.0.0.0", "Chromium";v="98.0.4750.0", "Google Chrome";v="98.0.4750.0" Sec-CH-UA-Platform: "Linux" ``` Specifications -------------- | Specification | | --- | | [User-Agent Client Hints # sec-ch-ua-full-version-list](https://wicg.github.io/ua-client-hints/#sec-ch-ua-full-version-list) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Sec-CH-UA-Full-Version-List` | 98 | 98 | No | No | 84 | No | 98 | 98 | No | No | No | 18.0 | See also -------- * [Client hints](../client_hints) * [User-Agent Client Hints API](https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API) * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) http Server-Timing Server-Timing ============= Server-Timing ============= The `Server-Timing` header communicates one or more metrics and descriptions for a given request-response cycle. It is used to surface any backend server timing metrics (e.g. database read/write, CPU time, file system access, etc.) in the developer tools in the user's browser or in the [`PerformanceServerTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceServerTiming) interface. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ The syntax of the `Server-Timing` header allows you to communicate metrics in different ways: server metric name only, metric with value, metric with value and description, and metric with description. The specification advises that names and descriptions should be kept as short as possible (use abbreviations and omit optional values where possible) to minimize the HTTP overhead. ``` // Single metric without value Server-Timing: missedCache // Single metric with value Server-Timing: cpu;dur=2.4 // Single metric with description and value Server-Timing: cache;desc="Cache Read";dur=23.2 // Two metrics with value Server-Timing: db;dur=53, app;dur=47.2 // Server-Timing as trailer Trailer: Server-Timing --- response body --- Server-Timing: total;dur=123.4 ``` Privacy and security -------------------- The `Server-Timing` header may expose potentially sensitive application and infrastructure information. Consider to control which metrics are returned when and to whom on the server side. For example, you could only show metrics to authenticated users and nothing to the public. PerformanceServerTiming interface --------------------------------- In addition to having `Server-Timing` header metrics appear in the developer tools of the browser, the [`PerformanceServerTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceServerTiming) interface enables tools to automatically collect and process metrics from JavaScript. This interface is restricted to the same origin, but you can use the [`Timing-Allow-Origin`](timing-allow-origin) header to specify the domains that are allowed to access the server metrics. The interface is only available in secure contexts (HTTPS) in some browsers. Specifications -------------- | Specification | | --- | | [Server Timing # the-server-timing-header-field](https://w3c.github.io/server-timing/#the-server-timing-header-field) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Server-Timing` | 65 | ≤79 | 61 | No | 52 | No | 65 | 65 | 61 | 47 | No | 9.0 | See also -------- * [`PerformanceServerTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceServerTiming) http Vary Vary ==== Vary ==== The `Vary` HTTP response header describes the parts of the request message aside from the method and URL that influenced the content of the response it occurs in. Most often, this is used to create a cache key when [content negotiation](../content_negotiation) is in use. The same `Vary` header value should be used on all responses for a given URL, including [`304`](../status/304) `Not Modified` responses and the "default" response. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Vary: \* Vary: <header-name>, <header-name>, ... ``` Directives ---------- \* Indicates that factors other than request headers influenced the generation of this response. Implies that the response is uncacheable. <header-name> A comma-separated list of request header names that could have influenced the generation of this response. Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.vary](https://httpwg.org/specs/rfc9110.html#field.vary) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Vary` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | ### Compatibility notes * [Vary with care – Vary header problems in IE6-9](https://docs.microsoft.com/archive/blogs/ieinternals/vary-with-care) See also -------- * [Understanding The Vary Header - Smashing Magazine](https://www.smashingmagazine.com/2017/11/understanding-vary-header/) * [Best Practices for Using the Vary Header – fastly.com](https://www.fastly.com/blog/best-practices-using-vary-header) * [Content negotiation](../content_negotiation) http Via Via === Via === The `Via` general header is added by proxies, both forward and reverse, and can appear in the request or response headers. It is used for tracking message forwards, avoiding request loops, and identifying the protocol capabilities of senders along the request/response chain. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Via: [ <protocol-name> "/" ] <protocol-version> <host> [ ":" <port> ] Via: [ <protocol-name> "/" ] <protocol-version> <pseudonym> ``` Directives ---------- <protocol-name> Optional. The name of the protocol used, such as "HTTP". <protocol-version> The version of the protocol used, such as "1.1". <host> and <port> Public proxy URL and port. <pseudonym> Name/alias of an internal proxy. Examples -------- ``` Via: 1.1 vegur Via: HTTP/1.1 GWA Via: 1.0 fred, 1.1 p.example.net ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.via](https://httpwg.org/specs/rfc9110.html#field.via) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Via` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`X-Forwarded-For`](x-forwarded-for) * [Heroku's proxy library Vegur](https://github.com/heroku/vegur) http Date Date ==== Date ==== The `Date` general HTTP header contains the date and time at which the message originated. **Warning:** `Date` is listed in the [forbidden header names](https://fetch.spec.whatwg.org/#forbidden-header-name) in the fetch spec, so this code will not send the `Date` header: ``` fetch('https://httpbin.org/get', { 'headers': { 'Date': (new Date()).toUTCString() } }) ``` | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Date: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT ``` Directives ---------- <day-name> One of "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", or "Sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". <month> One of "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" (case sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <hour> 2 digit hour number, e.g. "09" or "23". <minute> 2 digit minute number, e.g. "04" or "59". <second> 2 digit second number, e.g. "04" or "59". GMT Greenwich Mean Time. HTTP dates are always expressed in GMT, never in local time. Examples -------- ``` Date: Wed, 21 Oct 2015 07:28:00 GMT ``` ``` new Date().toUTCString() // "Mon, 09 Mar 2020 08:13:24 GMT" ``` Specifications -------------- | Specification | | --- | | [HTTP Semantics # field.date](https://httpwg.org/specs/rfc9110.html#field.date) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Date` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Age`](age) http SourceMap SourceMap ========= SourceMap ========= The `SourceMap` [HTTP](../index) response header links generated code to a [source map](https://firefox-source-docs.mozilla.org/devtools-user/debugger/how_to/use_a_source_map/index.html), enabling the browser to reconstruct the original source and present the reconstructed original in the debugger. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` SourceMap: <url> X-SourceMap: <url> (deprecated) ``` ### Directives <url> A relative (to the request URL) or absolute URL pointing to a source map file. Examples -------- ``` SourceMap: /path/to/file.js.map ``` Specifications -------------- | Specification | | --- | | [Source Map Revision 3 Proposal # h.lmz475t4mvbx](https://sourcemaps.info/spec.html#h.lmz475t4mvbx) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `SourceMap` | Yes Yes | ≤79 ≤79 | 55 27 | No | Yes Yes | Yes Yes | Yes Yes | Yes Yes | 55 27 | Yes Yes | Yes Yes | Yes Yes | See also -------- * [Firefox Developer Tools: using a source map](https://firefox-source-docs.mozilla.org/devtools-user/debugger/how_to/use_a_source_map/index.html) http Tk Tk == Tk == **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. The `Tk` response header indicates the tracking status that applied to the corresponding request. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Tk: ! (under construction) Tk: ? (dynamic) Tk: G (gateway or multiple parties) Tk: N (not tracking) Tk: T (tracking) Tk: C (tracking with consent) Tk: P (potential consent) Tk: D (disregarding DNT) Tk: U (updated) ``` ### Directives ! Under construction. The origin server is currently testing its communication of tracking status. ? Dynamic. The origin server needs more information to determine tracking status. G Gateway or multiple parties. The server is acting as a gateway to an exchange involving multiple parties. N Not tracking. T Tracking. C Tracking with consent. The origin server believes it has received prior consent for tracking this user, user agent, or device. P Potential consent. The origin server does not know, in real-time, whether it has received prior consent for tracking this user, user agent, or device, but promises not to use or share any `DNT:1` data until such consent has been determined, and further promises to delete or permanently de-identify within 48 hours any `DNT:1` data received for which such consent has not been received. D Disregarding DNT. The origin server is unable or unwilling to respect a tracking preference received from the requesting user agent. U Updated. The request resulted in a potential change to the tracking status applicable to this user, user agent, or device. Examples -------- A `Tk` header for a resource that claims not to be tracking would look like: ``` Tk: N ``` Specifications -------------- | Specification | | --- | | [Tracking Preference Expression (DNT) # Tk-header-defn](https://www.w3.org/TR/tracking-dnt/#Tk-header-defn) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Tk` | No | No | No | No | No | No | No | No | No | No | No | No | See also -------- * [`DNT`](dnt) header * [`Navigator.doNotTrack`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/doNotTrack)
programming_docs
http Cross-Origin-Opener-Policy Cross-Origin-Opener-Policy ========================== Cross-Origin-Opener-Policy ========================== The HTTP `Cross-Origin-Opener-Policy` (COOP) response header allows you to ensure a top-level document does not share a browsing context group with cross-origin documents. COOP will process-isolate your document and potential attackers can't access your global object if they were to open it in a popup, preventing a set of cross-origin attacks dubbed [XS-Leaks](https://github.com/xsleaks/xsleaks). If a cross-origin document with COOP is opened in a new window, the opening document will not have a reference to it, and the [`window.opener`](https://developer.mozilla.org/en-US/docs/Web/API/Window/opener) property of the new window will be `null`. This allows you to have more control over references to a window than [`rel=noopener`](https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types/noopener), which only affects outgoing navigations. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Cross-Origin-Opener-Policy: unsafe-none Cross-Origin-Opener-Policy: same-origin-allow-popups Cross-Origin-Opener-Policy: same-origin ``` ### Directives `unsafe-none` This is the default value. Allows the document to be added to its opener's browsing context group unless the opener itself has a COOP of `same-origin` or `same-origin-allow-popups`. `same-origin-allow-popups` Retains references to newly opened windows or tabs that either don't set COOP or that opt out of isolation by setting a COOP of `unsafe-none`. `same-origin` Isolates the browsing context exclusively to same-origin documents. Cross-origin documents are not loaded in the same browsing context. Examples -------- ### Certain features depend on cross-origin isolation Certain features like [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) objects or [`Performance.now()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now) with unthrottled timers are only available if your document has a COOP header with the value `same-origin` value set. ``` Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp ``` See also the [`Cross-Origin-Embedder-Policy`](cross-origin-embedder-policy) header which you'll need to set as well. To check if cross-origin isolation has been successful, you can test against the [`crossOriginIsolated`](https://developer.mozilla.org/en-US/docs/Web/API/crossOriginIsolated) property available to window and worker contexts: ``` if (crossOriginIsolated) { // Post SharedArrayBuffer } else { // Do something else } ``` Specifications -------------- | Specification | | --- | | [HTML Standard # the-coop-headers](https://html.spec.whatwg.org/multipage/origin.html#the-coop-headers) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Cross-Origin-Opener-Policy` | 83 | 83 | 79 | No | No | 15.2 | No | 83 | 79 | No | 15.2 | 13.0 | See also -------- * [`Cross-Origin-Embedder-Policy`](cross-origin-embedder-policy) http Access-Control-Expose-Headers Access-Control-Expose-Headers ============================= Access-Control-Expose-Headers ============================= The `Access-Control-Expose-Headers` response header allows a server to indicate which response headers should be made available to scripts running in the browser, in response to a cross-origin request. Only the [CORS-safelisted response headers](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header) are exposed by default. For clients to be able to access other headers, the server must list them using the `Access-Control-Expose-Headers` header. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Access-Control-Expose-Headers: [<header-name>[, <header-name>]\*] Access-Control-Expose-Headers: \* ``` Directives ---------- <header-name> A list of zero or more comma-separated [header names](../headers) that clients are allowed to access from a response. These are *in addition* to the [CORS-safelisted response headers](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header). `*` (wildcard) The value "`*`" only counts as a special wildcard value for requests without credentials (requests without [HTTP cookies](../cookies) or HTTP authentication information). In requests with credentials, it is treated as the literal header name "`*`" without special semantics. Examples -------- The [CORS-safelisted response headers](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header) are: [`Cache-Control`](cache-control), [`Content-Language`](content-language), [`Content-Length`](content-length), [`Content-Type`](content-type), [`Expires`](expires), [`Last-Modified`](last-modified), [`Pragma`](pragma). To expose a non-CORS-safelisted response header, you can specify: ``` Access-Control-Expose-Headers: Content-Encoding ``` To additionally expose a custom header, like `Kuma-Revision`, you can specify multiple headers separated by a comma: ``` Access-Control-Expose-Headers: Content-Encoding, Kuma-Revision ``` For requests without credentials, a server can also respond with a wildcard value: ``` Access-Control-Expose-Headers: \* ``` However, this won't wildcard the [`Authorization`](authorization) header, so if you need to expose that, you will need to list it explicitly: ``` Access-Control-Expose-Headers: \*, Authorization ``` Specifications -------------- | Specification | | --- | | [Fetch Standard # http-access-control-expose-headers](https://fetch.spec.whatwg.org/#http-access-control-expose-headers) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Access-Control-Expose-Headers` | 4 | 12 | 3.5 | 10 | 12 | 4 | 2 | Yes | 4 | 12 | 3.2 | Yes | | `wildcard` | 65 | 79 | 69 | No | 52 | No | 65 | 65 | No | 47 | No | 9.0 | See also -------- * [`Access-Control-Allow-Headers`](access-control-allow-headers) * [`Access-Control-Allow-Origin`](access-control-allow-origin) http Content-Disposition Content-Disposition =================== Content-Disposition =================== In a regular HTTP response, the `Content-Disposition` response header is a header indicating if the content is expected to be displayed *inline* in the browser, that is, as a Web page or as part of a Web page, or as an *attachment*, that is downloaded and saved locally. In a `multipart/form-data` body, the HTTP `Content-Disposition` general header is a header that must be used on each subpart of a multipart body to give information about the field it applies to. The subpart is delimited by the *boundary* defined in the [`Content-Type`](content-type) header. Used on the body itself, `Content-Disposition` has no effect. The `Content-Disposition` header is defined in the larger context of MIME messages for e-mail, but only a subset of the possible parameters apply to HTTP forms and [`POST`](../methods/post) requests. Only the value `form-data`, as well as the optional directive `name` and `filename`, can be used in the HTTP context. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) (for the main body),[Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) (for a subpart of a multipart body) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ### As a response header for the main body The first parameter in the HTTP context is either `inline` (default value, indicating it can be displayed inside the Web page, or as the Web page) or `attachment` (indicating it should be downloaded; most browsers presenting a 'Save as' dialog, prefilled with the value of the `filename` parameters if present). ``` Content-Disposition: inline Content-Disposition: attachment Content-Disposition: attachment; filename="filename.jpg" ``` **Note:** Chrome, and Firefox 82 and later, prioritize the HTML [<a> element's](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) `download` attribute over the `Content-Disposition` `inline` parameter (for [same-origin URLs](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy)). Earlier Firefox versions prioritize the header and will display the content inline. ### As a header for a multipart body A `multipart/form-data` body requires a `Content-Disposition` header to provide information for each subpart of the form (e.g. for every form field and any files that are part of field data). The first directive is always `form-data`, and the header *must* also include a `name` parameter to identify the relevant field. Additional directives are case-insensitive and have arguments that use quoted-string syntax after the `'='` sign. Multiple parameters are separated by a semicolon (`';'`). ``` Content-Disposition: form-data; name="fieldName" Content-Disposition: form-data; name="fieldName"; filename="filename.jpg" ``` ### Directives `name` Is followed by a string containing the name of the HTML field in the form that the content of this subpart refers to. When dealing with multiple files in the same field (for example, the [`multiple`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-multiple) attribute of an `[<input type="file">](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input)` element), there can be several subparts with the same name. A `name` with a value of `'_charset_'` indicates that the part is not an HTML field, but the default charset to use for parts without explicit charset information. `filename` Is followed by a string containing the original name of the file transmitted. The filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done. This parameter provides mostly indicative information. When used in combination with `Content-Disposition: attachment`, it is used as the default filename for an eventual "Save As" dialog presented to the user. `filename*` The parameters `filename` and `filename*` differ only in that `filename*` uses the encoding defined in [RFC 5987](https://datatracker.ietf.org/doc/html/rfc5987). When both `filename` and `filename*` are present in a single header field value, `filename*` is preferred over `filename` when both are understood. **Warning:** The string following `filename` should always be put into quotes; but, for compatibility reasons, many browsers try to parse unquoted names that contain spaces. Examples -------- A response triggering the "Save As" dialog: ``` 200 OK Content-Type: text/html; charset=utf-8 Content-Disposition: attachment; filename="cool.html" Content-Length: 21 <HTML>Save me!</HTML> ``` This simple HTML file will be saved as a regular download rather than displayed in the browser. Most browsers will propose to save it under the `cool.html` filename (by default). An example of an HTML form posted using the `multipart/form-data` format that makes use of the `Content-Disposition` header: ``` POST /test.html HTTP/1.1 Host: example.org Content-Type: multipart/form-data;boundary="boundary" --boundary Content-Disposition: form-data; name="field1" value1 --boundary Content-Disposition: form-data; name="field2"; filename="example.txt" value2 --boundary-- ``` Specifications -------------- | Specification | | --- | | [Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP) # header.field.definition](https://httpwg.org/specs/rfc6266.html#header.field.definition) | | [Returning Values from Forms: multipart/form-data # section-4.2](https://www.rfc-editor.org/rfc/rfc7578#section-4.2) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Content-Disposition` | Yes | 12 | Yes From version 82, if an `<a>` element's `download` attribute is set (for a same-origin URL) then the `inline` directive is ignored. Earlier versions did not match the specification and respected the header directive over the attribute. See [bug 1658877](https://bugzil.la/1658877). | Yes | Yes | Yes | Yes | Yes | Yes From version 82, if an `<a>` element's `download` attribute is set (for a same-origin URL) then the `inline` directive is ignored. Earlier versions did not match the specification and respected the header directive over the attribute. See [bug 1658877](https://bugzil.la/1658877). | Yes | Yes | Yes | ### Compatibility notes * Firefox 5 handles the `Content-Disposition` HTTP response header more effectively if both the `filename` and `filename*` parameters are provided; it looks through all provided names, using the `filename*` parameter if one is available, even if a `filename` parameter is included first. Previously, the first matching parameter would be used, thereby preventing a more appropriate name from being used. See [bug 588781](https://bugzilla.mozilla.org/show_bug.cgi?id=588781). * Firefox 82 (and later) and Chrome prioritize the HTML [<a> element's](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) `download` attribute over the `Content-Disposition` `inline` parameter (for [same-origin URLs](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy)). Earlier Firefox versions prioritize the header and will display the content inline. See also -------- * [HTML Forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) * The [`Content-Type`](content-type) defining the boundary of the multipart body. * The [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) interface used to manipulate form data for use in the [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) API. http Device-Memory Device-Memory ============= Device-Memory ============= **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). The `Device-Memory` [device client hint](../client_hints#device_client_hints) request header field indicates the approximate amount of available RAM on the client device. The header is part of the [Device Memory API](https://developer.mozilla.org/en-US/docs/Web/API/Device_Memory_API). | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | **Note:** * Client Hints are accessible only on secure origins (via TLS). * A server has to opt in to receive the `Device-Memory` header from the client, by sending the [`Accept-CH`](accept-ch) response header. * Servers that opt in to the `Device-Memory` client hint will typically also specify it in the [`Vary`](vary) header. This informs caches that the server may send different responses based on the header value in a request. Syntax ------ ``` Device-Memory: <number> ``` Directives ---------- `<number>` The approximate amount of device RAM. Possible values are: `0.25`, `0.5`, `1`, `2`, `4`, `8`. The amount of device RAM can be used as a fingerprinting variable, so values for the header are intentionally coarse to reduce the potential for its misuse. Examples -------- The server first needs to opt in to receive `Device-Memory` header by sending the response headers [`Accept-CH`](accept-ch) containing `Device-Memory`. ``` Accept-CH: Device-Memory ``` Then on subsequent requests the client might send `Device-Memory` header back: ``` Device-Memory: 1 ``` Specifications -------------- | Specification | | --- | | [Device Memory # iana-device-memory](https://www.w3.org/TR/device-memory/#iana-device-memory) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Device-Memory` | 61 | ≤79 | No | No | 48 | No | 61 | 61 | No | No | No | 8.0 | See also -------- * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * [Device Memory API](https://developer.mozilla.org/en-US/docs/Web/API/Device_Memory_API) * [`Navigator.deviceMemory`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/deviceMemory) * Device client hints + [`Content-DPR`](content-dpr) + [`DPR`](dpr) + [`Viewport-Width`](viewport-width) + [`Width`](width) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) http X-Content-Type-Options X-Content-Type-Options ====================== X-Content-Type-Options ====================== The `X-Content-Type-Options` response HTTP header is a marker used by the server to indicate that the [MIME types](../basics_of_http/mime_types) advertised in the [`Content-Type`](content-type) headers should be followed and not be changed. The header allows you to avoid [MIME type sniffing](../basics_of_http/mime_types#mime_sniffing) by saying that the MIME types are deliberately configured. This header was introduced by Microsoft in IE 8 as a way for webmasters to block content sniffing that was happening and could transform non-executable MIME types into executable MIME types. Since then, other browsers have introduced it, even if their MIME sniffing algorithms were less aggressive. Starting with Firefox 72, top-level documents also avoid MIME sniffing (if [`Content-type`](content-type) is provided). This can cause HTML web pages to be downloaded instead of being rendered when they are served with a MIME type other than `text/html`. Make sure to set both headers correctly. Site security testers usually expect this header to be set. **Note:** `X-Content-Type-Options` only apply [request-blocking due to `nosniff`](https://fetch.spec.whatwg.org/#should-response-to-request-be-blocked-due-to-nosniff?) for [request destinations](https://fetch.spec.whatwg.org/#concept-request-destination) of "`script`" and "`style`". However, it also [enables Cross-Origin Read Blocking (CORB)](https://chromium.googlesource.com/chromium/src/+/master/services/network/cross_origin_read_blocking_explainer.md#determining-whether-a-response-is-corb_protected) protection for HTML, TXT, JSON and XML files (excluding SVG `image/svg+xml`). | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` X-Content-Type-Options: nosniff ``` Directives ---------- `nosniff` Blocks a request if the request destination is of type `style` and the MIME type is not `text/css`, or of type `script` and the MIME type is not a [JavaScript MIME type](https://html.spec.whatwg.org/multipage/scripting.html#javascript-mime-type). Specifications -------------- | Specification | | --- | | [Fetch Standard # x-content-type-options-header](https://fetch.spec.whatwg.org/#x-content-type-options-header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `X-Content-Type-Options` | 64 1 Not supported for stylesheets. | 12 | 50 | 8 | Yes | 11 | 64 Yes Not supported for stylesheets. | 64 Yes Not supported for stylesheets. | 50 | Yes | 11 | 9.0 Yes Not supported for stylesheets. | ### Browser specific notes * Firefox 72 enables `X-Content-Type-Options: nosniff` for top-level documents See also -------- * [`Content-Type`](content-type) * The [original definition](https://docs.microsoft.com/archive/blogs/ie/ie8-security-part-vi-beta-2-update) of X-Content-Type-Options by Microsoft. * The [Mozilla Observatory](https://observatory.mozilla.org/) tool testing the configuration (including this header) of Web sites for safety and security * [Mitigating MIME Confusion Attacks in Firefox](https://blog.mozilla.org/security/2016/08/26/mitigating-mime-confusion-attacks-in-firefox/) * [Cross-Origin Read Blocking (CORB)](https://fetch.spec.whatwg.org/#corb) * [Google Docs CORB explainer](https://chromium.googlesource.com/chromium/src/+/master/services/network/cross_origin_read_blocking_explainer.md)
programming_docs
http Sec-CH-UA-Mobile Sec-CH-UA-Mobile ================ Sec-CH-UA-Mobile ================ **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). The `Sec-CH-UA-Mobile` [user agent client hint](../client_hints#user-agent_client_hints) request header indicates whether the browser is on a mobile device. It can also be used by a desktop browser to indicate a preference for a "mobile" user experience. `Sec-CH-UA-Mobile` is a [low entropy hint](../client_hints#low_entropy_hints). Unless blocked by a user agent permission policy, it is sent by default, without the server opting in by sending [`Accept-CH`](accept-ch). | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Sec-CH-UA-Mobile: <boolean> ``` ### Directives `<boolean>` `?1` indicates that the user-agent prefers a mobile experience (true). `?0` indicates that user-agent does not prefer a mobile experience (false). Examples -------- As `Sec-CH-UA-Mobile` is a [low entropy hint](../client_hints#low_entropy_hints) it is typically sent in all requests. A desktop browser would usually send requests with the following header: ``` Sec-CH-UA-Mobile: ?0 ``` A browser on a mobile device would usually send requests with the following header: ``` Sec-CH-UA-Mobile: ?1 ``` Specifications -------------- | Specification | | --- | | [User-Agent Client Hints # sec-ch-ua-mobile](https://wicg.github.io/ua-client-hints/#sec-ch-ua-mobile) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Sec-CH-UA-Mobile` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | See also -------- * [Client hints](../client_hints) * [User-Agent Client Hints API](https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API) * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) http Sec-Fetch-User Sec-Fetch-User ============== Sec-Fetch-User ============== The `Sec-Fetch-User` [fetch metadata request header](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_metadata_request_header) is only sent for requests initiated by user activation, and its value will always be `?1`. A server can use this header to identify whether a navigation request from a document, iframe, etc., was originated by the user. | | | | --- | --- | | Header type | [Fetch Metadata Request Header](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_metadata_request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes (prefix `Sec-`) | | [CORS-safelisted request header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header) | no | Syntax ------ ``` Sec-Fetch-User: ?1 ``` Directives ---------- The value will always be `?1`. When a request is triggered by something other than a user activation, the spec requires browsers to omit the header completely. Examples -------- If a user clicks on a page link to another page on the same origin, the resulting request would have the following headers: ``` Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: same-origin Sec-Fetch-User: ?1 ``` Specifications -------------- | Specification | | --- | | [Fetch Metadata Request Headers # sec-fetch-user-header](https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Sec-Fetch-User` | 76 | 79 | 90 | No | 63 | No | 76 | 76 | 90 | 54 | No | 12.0 | See also -------- * Related headers + [`Sec-Fetch-Dest`](sec-fetch-dest) + [`Sec-Fetch-Mode`](sec-fetch-mode) + [`Sec-Fetch-Site`](sec-fetch-site) * [Protect your resources from web attacks with Fetch Metadata](https://web.dev/fetch-metadata/) (web.dev) * [Fetch Metadata Request Headers playground](https://secmetadata.appspot.com/) (secmetadata.appspot.com) http DPR DPR === DPR === **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). **Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The `DPR` [device client hint](../client_hints) request header provides the client device pixel ratio. This ratio is the number of physical device pixels corresponding to every [CSS pixel](https://developer.mozilla.org/en-US/docs/Glossary/CSS_pixel). | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | The hint is useful when selecting image sources that best correspond to a screen's pixel density. This is similar to the role played by `x` descriptors in the `<img>` [`srcset`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-srcset) attribute to allow user agents to select a preferred image. If a server uses the `DPR` hint to choose which resource is sent in a response, the response must include the [`Content-DPR`](content-dpr) header. The client must use the value in `Content-DPR` for layout if it differs from the value in the request's `DPR` header. If the `DPR` header appears more than once in a message the last occurrence is used. **Note:** * Client Hints are accessible only on secure origins (via TLS). * A server has to opt in to receive the `DPR` header from the client, by sending the [`Accept-CH`](accept-ch) response header. * Servers that opt in to the `DPR` client hint will typically also specify it in the [`Vary`](vary) header. This informs caches that the server may send different responses based on the header value in a request. * `DPR` was removed from the client hints specification in [draft-ietf-httpbis-client-hints-07](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-client-hints-07). The proposed replacement is [`Sec-CH-DPR`](https://wicg.github.io/responsive-image-client-hints/#sec-ch-dpr) (Responsive Image Client Hints). Syntax ------ ``` DPR: <number> ``` Directives ---------- `<number>` The client device pixel ratio. Examples -------- A server must first opt in to receive the `DPR` header by sending the response header [`Accept-CH`](accept-ch) containing the directive `DPR`. ``` Accept-CH: DPR ``` Then on subsequent requests the client might send `DPR` header to the server: ``` DPR: 2.0 ``` If a request with the `DPR` header (as shown above) is for an image resource, then the server response must include the [`Content-DPR`](content-dpr) header: ``` Content-DPR: 2.0 ``` Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `DPR` | 46 | ≤79 | No | No | 33 | No | 46 | 46 | No | 33 | No | 5.0 | See also -------- * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * Device client hints + [`Content-DPR`](content-dpr) + [`Device-Memory`](device-memory) + [`Viewport-Width`](viewport-width) + [`Width`](width) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) http Width Width ===== Width ===== **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). **Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The `Width` [device client hint](../client_hints#device_client_hints) request header field indicates the desired resource width in physical pixels — the intrinsic size of an image. The provided pixel value is a number rounded to the smallest following integer (i.e. ceiling value). | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | The hint is particularly useful because it allows the client to request a resource that is optimal for both the screen and the layout: taking into account both the density-corrected width of the screen and the image's extrinsic size within the layout. If the desired resource width is not known at the time of the request or the resource does not have a display width, the `Width` header field can be omitted. If the `Width` header appears more than once in a message the last occurrence is used. **Note:** * Client Hints are accessible only on secure origins (via TLS). * A server has to opt in to receive the `Width` header from the client, by sending the [`Accept-CH`](accept-ch) response header. * Servers that opt in to the `Width` client hint will typically also specify it in the [`Vary`](vary) header. This informs caches that the server may send different responses based on the header value in a request. * `Width` was removed from the client hints specification in [draft-ietf-httpbis-client-hints-07](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-client-hints-07). The proposed replacement is [`Sec-CH-Width`](https://wicg.github.io/responsive-image-client-hints/#sec-ch-width) (Responsive Image Client Hints). Syntax ------ ``` Width: <number> ``` Directives ---------- <number> The width of the resource in physical pixels, rounded up to the nearest integer. Examples -------- The server first needs to opt in to receive the `Width` header by sending the response headers [`Accept-CH`](accept-ch) containing `Width`. ``` Accept-CH: Width ``` Then on subsequent requests the client might send `Width` header back: ``` Width: 1920 ``` Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Width` | 46 | ≤79 | No | No | 33 | No | 46 | 46 | No | 33 | No | 5.0 | See also -------- * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * Device client hints + [`Content-DPR`](content-dpr) + [`Device-Memory`](device-memory) + [`DPR`](dpr) + [`Viewport-Width`](viewport-width) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) http X-Frame-Options X-Frame-Options =============== X-Frame-Options =============== The `X-Frame-Options` [HTTP](../index) response header can be used to indicate whether or not a browser should be allowed to render a page in a [`<frame>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frame), [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe), [`<embed>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed) or [`<object>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object). Sites can use this to avoid [click-jacking](https://developer.mozilla.org/en-US/docs/Web/Security/Types_of_attacks#click-jacking) attacks, by ensuring that their content is not embedded into other sites. The added security is provided only if the user accessing the document is using a browser that supports `X-Frame-Options`. **Note:** The [`Content-Security-Policy`](content-security-policy) HTTP header has a [`frame-ancestors`](content-security-policy/frame-ancestors) directive which [obsoletes](https://w3c.github.io/webappsec-csp/#frame-ancestors-and-frame-options) this header for supporting browsers. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ There are two possible directives for `X-Frame-Options`: ``` X-Frame-Options: DENY X-Frame-Options: SAMEORIGIN ``` ### Directives If you specify `DENY`, not only will the browser attempt to load the page in a frame fail when loaded from other sites, attempts to do so will fail when loaded from the same site. On the other hand, if you specify `SAMEORIGIN`, you can still use the page in a frame as long as the site including it in a frame is the same as the one serving the page. `DENY` The page cannot be displayed in a frame, regardless of the site attempting to do so. `SAMEORIGIN` The page can only be displayed if all ancestor frames are same origin to the page itself. `ALLOW-FROM=url` Deprecated This is an obsolete directive that no longer works in modern browsers. (Using it will give the same behavior as omitting the header.) Don't use it. The [`Content-Security-Policy`](content-security-policy) HTTP header has a [`frame-ancestors`](content-security-policy/frame-ancestors) directive which you can use instead. Examples -------- **Note:** Setting X-Frame-Options inside the [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) element is useless! For instance, `<meta http-equiv="X-Frame-Options" content="deny">` has no effect. Do not use it! `X-Frame-Options` works only by setting through the HTTP header, as in the examples below. ### Configuring Apache To configure Apache to send the `X-Frame-Options` header for all pages, add this to your site's configuration: ``` Header always set X-Frame-Options "SAMEORIGIN" ``` To configure Apache to set the `X-Frame-Options` DENY, add this to your site's configuration: ``` Header set X-Frame-Options "DENY" ``` ### Configuring Nginx To configure Nginx to send the `X-Frame-Options` header, add this either to your http, server or location configuration: ``` add_header X-Frame-Options SAMEORIGIN always; ``` ### Configuring IIS To configure IIS to send the `X-Frame-Options` header, add this to your site's `Web.config` file: ``` <system.webServer> … <httpProtocol> <customHeaders> <add name="X-Frame-Options" value="SAMEORIGIN" /> </customHeaders> </httpProtocol> … </system.webServer> ``` Or see this [Microsoft support article on setting this configuration using the IIS Manager](https://support.microsoft.com/en-US/office/mitigating-framesniffing-with-the-x-frame-options-header-1911411b-b51e-49fd-9441-e8301dcdcd79) user interface. ### Configuring HAProxy To configure HAProxy to send the `X-Frame-Options` header, add this to your front-end, listen, or backend configuration: ``` rspadd X-Frame-Options:\ SAMEORIGIN ``` Alternatively, in newer versions: ``` http-response set-header X-Frame-Options SAMEORIGIN ``` ### Configuring Express To configure Express to send the `X-Frame-Options` header, you can use [helmet](https://helmetjs.github.io/) which uses [frameguard](https://helmetjs.github.io/docs/frameguard/) to set the header. Add this to your server configuration: ``` const helmet = require('helmet'); const app = express(); app.use(helmet.frameguard({ action: 'SAMEORIGIN' })); ``` Alternatively, you can use frameguard directly: ``` const frameguard = require('frameguard') app.use(frameguard({ action: 'SAMEORIGIN' })) ``` Specifications -------------- | Specification | | --- | | [HTML Standard # the-x-frame-options-header](https://html.spec.whatwg.org/multipage/browsing-the-web.html#the-x-frame-options-header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `ALLOW-FROM` | No | 12-79 | 18-70 | 8 | No | No | No | No | 18 | No | No | No | | `SAMEORIGIN` | Yes Starting in Chrome 61, this applies to all of a frame's ancestors. | 12 | Yes Starting in Firefox 59, this applies to all of a frame's ancestors. | 8 | Yes Starting in Opera 48, this applies to all of a frame's ancestors. | Yes | Yes Starting in Chrome 61, this applies to all of a frame's ancestors. | Yes Starting in Chrome 61, this applies to all of a frame's ancestors. | Yes Starting in Firefox 59, this applies to all of a frame's ancestors. | Yes Starting in Opera 48, this applies to all of a frame's ancestors. | No | Yes | | `X-Frame-Options` | 4 | 12 | 4 | 8 | 10.5 | 4 | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Content-Security-Policy`](content-security-policy) directive [`frame-ancestors`](content-security-policy/frame-ancestors) * [ClickJacking Defenses - IEBlog](https://docs.microsoft.com/archive/blogs/ie/ie8-security-part-vii-clickjacking-defenses) * [Combating ClickJacking with X-Frame-Options - IEInternals](https://docs.microsoft.com/archive/blogs/ieinternals/combating-clickjacking-with-x-frame-options) http Accept-CH Accept-CH ========= Accept-CH ========= **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). The `Accept-CH` header may be set by a server to specify which [client hints](../client_hints) headers a client should include in subsequent requests. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [CORS-safelisted response header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header) | no | **Note:** Client hints are accessible only on secure origins (via TLS). `Accept-CH` (and `Accept-CH-Lifetime`) headers should be persisted for all secure requests to ensure client hints are sent reliably. Syntax ------ ``` Accept-CH: <comma separated list of client hint headers> ``` Examples -------- ``` Accept-CH: Viewport-Width, Width Vary: Viewport-Width, Width ``` **Note:** Remember to [vary the response](../client_hints#varying_client_hints) based on the accepted client hints. Specifications -------------- | Specification | | --- | | [HTTP Client Hints # section-3.1](https://www.rfc-editor.org/rfc/rfc8942#section-3.1) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Content-DPR` | 46 | ≤79 | No | No | 33 | No | 46 | 46 | No | 33 | No | 5.0 | | `DPR` | 46 | ≤79 | No | No | 33 | No | 46 | 46 | No | 33 | No | 5.0 | | `Device-Memory` | 61 | ≤79 | No | No | 48 | No | 61 | 61 | No | No | No | 8.0 | | `Sec-CH-UA` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | | `Sec-CH-UA-Arch` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | | `Sec-CH-UA-Full-Version` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | | `Sec-CH-UA-Mobile` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | | `Sec-CH-UA-Model` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | | `Sec-CH-UA-Platform` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | | `Sec-CH-UA-Platform-Version` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | | `Viewport-Width` | 46 | ≤79 | No | No | 33 | No | 46 | 46 | No | 33 | No | 5.0 | | `Width` | 46 | ≤79 | No | No | 33 | No | 46 | 46 | No | 33 | No | 5.0 | | `Accept-CH` | 46 | ≤79 | No | No | 33 | No | 46 | 46 | No | 33 | No | 5.0 | See also -------- * [`Vary`](vary)
programming_docs
http Expires Expires ======= Expires ======= The `Expires` HTTP header contains the date/time after which the response is considered expired. Invalid expiration dates with value 0 represent a date in the past and mean that the resource is already expired. **Note:** If there is a [`Cache-Control`](cache-control) header with the `max-age` or `s-maxage` directive in the response, the `Expires` header is ignored. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | | [CORS-safelisted response header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header) | yes | Syntax ------ ``` Expires: <http-date> ``` Directives ---------- <http-date> An HTTP-date timestamp. Examples -------- ``` Expires: Wed, 21 Oct 2015 07:28:00 GMT ``` Specifications -------------- | Specification | | --- | | [HTTP Caching # field.expires](https://httpwg.org/specs/rfc9111.html#field.expires) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Expires` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Cache-Control`](cache-control) * [`Age`](age) http Sec-Fetch-Dest Sec-Fetch-Dest ============== Sec-Fetch-Dest ============== The `Sec-Fetch-Dest` [fetch metadata request header](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_metadata_request_header) indicates the request's *destination*. That is the initiator of the original fetch request, which is where (and how) the fetched data will be used. This allows servers determine whether to service a request based on whether it is appropriate for how it is *expected* to be used. For example, a request with an `audio` destination should request audio data, not some other type of resource (for example, a document that includes sensitive user information). | | | | --- | --- | | Header type | [Fetch Metadata Request Header](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_metadata_request_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes (prefix `Sec-`) | | [CORS-safelisted request header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header) | no | Syntax ------ ``` Sec-Fetch-Dest: audio Sec-Fetch-Dest: audioworklet Sec-Fetch-Dest: document Sec-Fetch-Dest: embed Sec-Fetch-Dest: empty Sec-Fetch-Dest: font Sec-Fetch-Dest: frame Sec-Fetch-Dest: iframe Sec-Fetch-Dest: image Sec-Fetch-Dest: manifest Sec-Fetch-Dest: object Sec-Fetch-Dest: paintworklet Sec-Fetch-Dest: report Sec-Fetch-Dest: script Sec-Fetch-Dest: serviceworker Sec-Fetch-Dest: sharedworker Sec-Fetch-Dest: style Sec-Fetch-Dest: track Sec-Fetch-Dest: video Sec-Fetch-Dest: worker Sec-Fetch-Dest: xslt ``` Servers should ignore this header if it contains any other value. Directives ---------- **Note:** These directives correspond to the values returned by [`Request.destination`](https://developer.mozilla.org/en-US/docs/Web/API/Request/destination). `audio` The destination is audio data. This might originate from an HTML [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) tag. `audioworklet` The destination is data being fetched for use by an audio worklet. This might originate from a call to [`audioWorklet.addModule()`](https://developer.mozilla.org/en-US/docs/Web/API/Worklet/addModule). `document` The destination is a document (HTML or XML), and the request is the result of a user-initiated top-level navigation (e.g. resulting from a user clicking a link). `embed` The destination is embedded content. This might originate from an HTML [`<embed>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed) tag. `empty` The destination is the empty string. This is used for destinations that do not have their own value. For example `fetch()`, [`navigator.sendBeacon()`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon), [`EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource), [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket), etc. `font` The destination is a font. This might originate from CSS [`@font-face`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face). `frame` The destination is a frame. This might originate from an HTML [`<frame>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frame) tag. `iframe` The destination is an iframe. This might originate from an HTML [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) tag. `image` The destination is an image. This might originate from an HTML [`<image>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/image), SVG [`<image>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image), CSS [`background-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-image), CSS [`cursor`](https://developer.mozilla.org/en-US/docs/Web/CSS/cursor), CSS [`list-style-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-image), etc. `manifest` The destination is a manifest. This might originate from an HTML [<link rel=manifest>](https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types/manifest). `object` The destination is an object. This might originate from an HTML [`<object>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object) tag. `paintworklet` The destination is a paint worklet. This might originate from a call to [`CSS.PaintWorklet.addModule()`](https://developer.mozilla.org/en-US/docs/Web/API/Worklet/addModule). `report` The destination is a report (for example, a content security policy report). `script` The destination is a script. This might originate from an HTML [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) tag or a call to [`WorkerGlobalScope.importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts). `serviceworker` The destination is a service worker. This might originate from a call to [`navigator.serviceWorker.register()`](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register). `sharedworker` The destination is a shared worker. This might originate from a [`SharedWorker`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker). `style` The destination is a style. This might originate from an HTML [<link rel=stylesheet>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) or a CSS [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import). `track` The destination is an HTML text track. This might originate from an HTML [`<track>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track) tag. `video` The destination is video data. This might originate from an HTML [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) tag. `worker` The destination is a [`Worker`](https://developer.mozilla.org/en-US/docs/Web/API/Worker). `xslt` The destination is an XSLT transform. Examples -------- A cross-site request generated by an [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) element would result in a request with the following HTTP request headers (note that the destination is `image`): ``` Sec-Fetch-Dest: image Sec-Fetch-Mode: no-cors Sec-Fetch-Site: cross-site ``` Specifications -------------- | Specification | | --- | | [Fetch Metadata Request Headers # sec-fetch-dest-header](https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Sec-Fetch-Dest` | 80 | 80 | 90 | No | 67 | No | 80 | 80 | 90 | No | No | 13.0 | See also -------- * Related headers + [`Sec-Fetch-Mode`](sec-fetch-mode) + [`Sec-Fetch-Site`](sec-fetch-site) + [`Sec-Fetch-User`](sec-fetch-user) * [Protect your resources from web attacks with Fetch Metadata](https://web.dev/fetch-metadata/) (web.dev) * [Fetch Metadata Request Headers playground](https://secmetadata.appspot.com/) (secmetadata.appspot.com) http ECT ECT === ECT === **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. The `ECT` [Client hint](../client_hints) request header field indicates the [effective connection type](https://developer.mozilla.org/en-US/docs/Glossary/Effective_connection_type): `slow-2g`, `2g`, `3g`, `4g`. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Client hint](../client_hints) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | The value represents the "network profile" that best matches the connection's latency and bandwidth, rather than the actual mechanisms used for transferring the data. For example, `2g` might be used to represent a slow Wi-Fi connection with high latency and low bandwidth, while `4g` might be used to represent a fast fibre-based broadband network. The hint allows a server to choose what information is sent based on the broad characteristics of the network. For example, a server might choose to send smaller versions of images and other resources on less capable connections. The value might also be used as a starting point for determining what information is sent, which is further refined using information in [`RTT`](rtt) and [`Downlink`](downlink) hints. **Note:** A server that specifies [`ECT`](ect) in [`Accept-CH`](accept-ch) may also specify it in [`Vary`](vary) to indicate that responses should be cached for different ECT values. Syntax ------ ``` ECT: <value> ``` Directives ---------- <value> A value indicating [effective connection type](https://developer.mozilla.org/en-US/docs/Glossary/Effective_connection_type). This is one of: `slow-2g`, `2g`, `3g`, or `4g`. Examples -------- A server first needs to opt in to receive the `ECT` header by sending the [`Accept-CH`](accept-ch) response header containing `ECT`. ``` Accept-CH: ECT ``` Then on subsequent requests the client might send an `ECT` header back: ``` ECT: 2g ``` Specifications -------------- | Specification | | --- | | [Network Information API # ect-request-header-field](https://wicg.github.io/netinfo/#ect-request-header-field) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `ECT` | 67 | ≤79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 | See also -------- * [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/) (web.dev) * Network client hints + [`Downlink`](downlink) + [`RTT`](rtt) + [`Save-Data`](save-data) * [`Accept-CH`](accept-ch) * [HTTP Caching > Varying responses](../caching#varying_responses) and [`Vary`](vary) * [`NetworkInformation.effectiveType`](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/effectiveType) http Keep-Alive Keep-Alive ========== Keep-Alive ========== The `Keep-Alive` general header allows the sender to hint about how the connection may be used to set a timeout and a maximum amount of requests. **Note:** Set the [`Connection`](connection) header to "keep-alive" for this header to have any effect. **Warning:** Connection-specific header fields such as [`Connection`](connection) and [`Keep-Alive`](keep-alive) are prohibited in [HTTP/2](https://httpwg.org/specs/rfc9113.html#ConnectionSpecific) and [HTTP/3](https://httpwg.org/specs/rfc9114.html#header-formatting). Chrome and Firefox ignore them in HTTP/2 responses, but Safari conforms to the HTTP/2 specification requirements and does not load any response that contains them. | | | | --- | --- | | Header type | [Request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header), [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | yes | Syntax ------ ``` Keep-Alive: parameters ``` Directives ---------- `parameters` A comma-separated list of parameters, each consisting of an identifier and a value separated by the equal sign (`'='`). The following identifiers are possible: * `timeout`: An integer that is the time in seconds that the host will allow an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host. A host may keep an idle connection open for longer than `timeout` seconds, but the host should attempt to retain a connection for at least `timeout` seconds. * `max`: An integer that is the maximum number of requests that can be sent on this connection before closing it. Unless `0`, this value is ignored for non-pipelined connections as another request will be sent in the next response. An HTTP pipeline can use it to limit the pipelining. Examples -------- A response containing a `Keep-Alive` header: ``` HTTP/1.1 200 OK Connection: Keep-Alive Content-Encoding: gzip Content-Type: text/html; charset=utf-8 Date: Thu, 11 Aug 2016 15:23:13 GMT Keep-Alive: timeout=5, max=1000 Last-Modified: Mon, 25 Jul 2016 04:32:39 GMT Server: Apache (body) ``` Specifications -------------- | Specification | | --- | | [HTTP/1.1 # compatibility.with.http.1.0.persistent.connections](https://httpwg.org/specs/rfc9112.html#compatibility.with.http.1.0.persistent.connections) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Keep-Alive` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`Connection`](connection) * [Connection management in HTTP/1.x](../connection_management_in_http_1.x) * [Keep-Alive Header](https://datatracker.ietf.org/doc/html/draft-thomson-hybi-http-timeout-03#section-2) IETF Internet Draft http Strict-Transport-Security Strict-Transport-Security ========================= Strict-Transport-Security ========================= The HTTP `Strict-Transport-Security` response header (often abbreviated as [HSTS](https://developer.mozilla.org/en-US/docs/Glossary/HSTS)) informs browsers that the site should only be accessed using HTTPS, and that any future attempts to access it using HTTP should automatically be converted to HTTPS. **Note:** This is more secure than simply configuring a HTTP to HTTPS (301) redirect on your server, where the initial HTTP connection is still vulnerable to a man-in-the-middle attack. | | | | --- | --- | | Header type | [Response header](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) | | [Forbidden header name](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) | no | Syntax ------ ``` Strict-Transport-Security: max-age=<expire-time> Strict-Transport-Security: max-age=<expire-time>; includeSubDomains Strict-Transport-Security: max-age=<expire-time>; includeSubDomains; preload ``` Directives ---------- `max-age=<expire-time>` The time, in seconds, that the browser should remember that a site is only to be accessed using HTTPS. `includeSubDomains` Optional If this optional parameter is specified, this rule applies to all of the site's subdomains as well. `preload` Optional Non-standard See [Preloading Strict Transport Security](#preloading_strict_transport_security) for details. When using `preload`, the `max-age` directive must be at least `31536000` (1 year), and the `includeSubDomains` directive must be present. Not part of the specification. Description ----------- If a website accepts a connection through HTTP and redirects to HTTPS, visitors may initially communicate with the non-encrypted version of the site before being redirected, if, for example, the visitor types `http://www.foo.com/` or even just foo.com. This creates an opportunity for a man-in-the-middle attack. The redirect could be exploited to direct visitors to a malicious site instead of the secure version of the original site. The HTTP Strict Transport Security header informs the browser that it should never load a site using HTTP and should automatically convert all attempts to access the site using HTTP to HTTPS requests instead. **Note:** The `Strict-Transport-Security` header is *ignored* by the browser when your site has only been accessed using HTTP. Once your site is accessed over HTTPS with no certificate errors, the browser knows your site is HTTPS capable and will honor the `Strict-Transport-Security` header. Browsers do this as attackers may intercept HTTP connections to the site and inject or remove the header. ### An example scenario You log into a free Wi-Fi access point at an airport and start surfing the web, visiting your online banking service to check your balance and pay a couple of bills. Unfortunately, the access point you're using is actually a hacker's laptop, and they're intercepting your original HTTP request and redirecting you to a clone of your bank's site instead of the real thing. Now your private data is exposed to the hacker. Strict Transport Security resolves this problem; as long as you've accessed your bank's website once using HTTPS, and the bank's web site uses Strict Transport Security, your browser will know to automatically use only HTTPS, which prevents hackers from performing this sort of man-in-the-middle attack. ### How the browser handles it The first time your site is accessed using HTTPS and it returns the `Strict-Transport-Security` header, the browser records this information, so that future attempts to load the site using HTTP will automatically use HTTPS instead. When the expiration time specified by the `Strict-Transport-Security` header elapses, the next attempt to load the site via HTTP will proceed as normal instead of automatically using HTTPS. Whenever the Strict-Transport-Security header is delivered to the browser, it will update the expiration time for that site, so sites can refresh this information and prevent the timeout from expiring. Should it be necessary to disable Strict Transport Security, setting the `max-age` to 0 (over an https connection) will immediately expire the `Strict-Transport-Security` header, allowing access via http. Preloading Strict Transport Security ------------------------------------ Google maintains [an HSTS preload service](https://hstspreload.org/). By following the guidelines and successfully submitting your domain, you can ensure that browsers will connect to your domain only via secure connections. While the service is hosted by Google, all browsers are using this preload list. However, it is not part of the HSTS specification and should not be treated as official. * Information regarding the HSTS preload list in Chrome : <https://www.chromium.org/hsts> * Consultation of the Firefox HSTS preload list : [nsSTSPreloadList.inc](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/manager/ssl/nsSTSPreloadList.inc) Examples -------- All present and future subdomains will be HTTPS for a `max-age` of 1 year. This blocks access to pages or subdomains that can only be served over HTTP. ``` Strict-Transport-Security: max-age=31536000; includeSubDomains ``` If a `max-age` of 1 year is acceptable for a domain, however, two years is the recommended value as explained on <https://hstspreload.org>. In the following example, `max-age` is set to 2 years, and is suffixed with `preload`, which is necessary for inclusion in all major web browsers' HSTS preload lists, like Chromium, Edge, and Firefox. ``` Strict-Transport-Security: max-age=63072000; includeSubDomains; preload ``` Specifications -------------- | Specification | | --- | | [HTTP Strict Transport Security (HSTS) # section-6.1](https://www.rfc-editor.org/rfc/rfc6797#section-6.1) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Strict-Transport-Security` | 4 | 12 | 4 | 11 | 12 | 7 | 4.4 | 18 | Yes | No | 7 | 1.0 | See also -------- * Blog post: [HTTP Strict Transport Security has landed!](https://blog.sidstamm.com/2010/08/http-strict-transport-security-has.html) * Blog post: [HTTP Strict Transport Security (force HTTPS)](https://hacks.mozilla.org/2010/08/firefox-4-http-strict-transport-security-force-https/) * OWASP Article: [HTTP Strict Transport Security](https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Strict_Transport_Security_Cheat_Sheet.html) * Wikipedia: [HTTP Strict Transport Security](https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) * [HSTS preload service](https://hstspreload.org/) * [Features restricted to secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts/features_restricted_to_secure_contexts)
programming_docs
http Set-Cookie: SameSite Set-Cookie: SameSite ==================== SameSite cookies ================ **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility). The `SameSite` attribute of the [`Set-Cookie`](../set-cookie) HTTP response header allows you to declare if your cookie should be restricted to a [first-party](../../cookies#third-party_cookies) or same-site context. **Note:** Standards related to the Cookie `SameSite` attribute recently changed such that: * The cookie-sending behavior if `SameSite` is not specified is `SameSite=Lax`. Previously the default was that cookies were sent for all requests. * Cookies with `SameSite=None` must now also specify the `Secure` attribute (they require a secure context/HTTPS). * Cookies from the same domain are no longer considered to be from the same site if sent using a different scheme (`http:` or `https:`). This article documents the new standard. See [Browser Compatibility](#browser_compatibility) below for information about specific versions where the behavior changed. Values ------ The `SameSite` attribute accepts three values: ### `Lax` Cookies are not sent on normal cross-site subrequests (for example to load images or frames into a third party site), but are sent when a user is *navigating to* the origin site (i.e., when following a link). This is the default cookie value if `SameSite` has not been explicitly specified in recent browser versions (see the "SameSite: Defaults to Lax" feature in the Browser Compatibility). **Note:** `Lax` replaced `None` as the default value in order to ensure that users have reasonably robust defense against some classes of cross-site request forgery ([CSRF](https://developer.mozilla.org/en-US/docs/Glossary/CSRF)) attacks. In order to mitigate breakage due to the new default value, browsers may implement a ["Lax-Allowing-Unsafe"](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-10#section-5.4.7.2) enforcement mode such that cookies can be sent with top-level cross-site unsafe requests if they are less than 2 minutes old. The [Chrome implementation](https://www.chromium.org/updates/same-site#20191101) and [Firefox implementation](https://phabricator.services.mozilla.com/D63081) of that "Lax-Allowing-Unsafe" enforcement mode should be considered a temporary, transitional measure only. ### `Strict` Cookies will only be sent in a first-party context and not be sent along with requests initiated by third party websites. ### `None` Cookies will be sent in all contexts, i.e. in responses to both first-party and cross-site requests. If `SameSite=None` is set, the cookie [`Secure`](../set-cookie#secure) attribute must also be set (or the cookie will be blocked). Fixing common warnings ---------------------- ### `SameSite=None` requires `Secure` Warnings like the ones below might appear in your console: ``` Cookie "myCookie" rejected because it has the "SameSite=None" attribute but is missing the "secure" attribute. This Set-Cookie was blocked because it had the "SameSite=None" attribute but did not have the "Secure" attribute, which is required in order to use "SameSite=None". ``` The warning appears because any cookie that requests `SameSite=None` but is not marked `Secure` will be rejected. ``` Set-Cookie: flavor=choco; SameSite=None ``` To fix this, you will have to add the `Secure` attribute to your `SameSite=None` cookies. ``` Set-Cookie: flavor=choco; SameSite=None; Secure ``` A [`Secure`](#secure) cookie is only sent to the server with an encrypted request over the HTTPS protocol. Note that insecure sites (`http:`) can't set cookies with the `Secure` directive. **Note:** On older browser versions you might get a warning that the cookie will be blocked in future. For example: Cookie `myCookie` will be soon rejected because it has the `SameSite` attribute set to `None` or an invalid value, without the `secure` attribute. ### Cookies without `SameSite` default to `SameSite=Lax` Recent versions of modern browsers provide a more secure default for `SameSite` to your cookies and so the following message might appear in your console: ``` Cookie "myCookie" has "SameSite" policy set to "Lax" because it is missing a "SameSite" attribute, and "SameSite=Lax" is the default value for this attribute. ``` The warning appears because the `SameSite` policy for a cookie was not explicitly specified: ``` Set-Cookie: flavor=choco ``` You should explicitly communicate the intended `SameSite` policy for your cookie (rather than relying on browsers to apply `SameSite=Lax` automatically). This will also improve the experience across browsers as not all of them default to `Lax` yet. ``` Set-Cookie: flavor=choco; SameSite=Lax ``` Example ------- ``` RewriteEngine on RewriteBase "/" RewriteCond "%{HTTP_HOST}" "^example\.org$" [NC] RewriteRule "^(.*)" "https://www.example.org/index.html" [R=301,L,QSA] RewriteRule "^(.*)\.ht$" "index.php?nav=$1 [NC,L,QSA,CO=RewriteRule;01;https://www.example.org;30/;SameSite=None;Secure] RewriteRule "^(.*)\.htm$" "index.php?nav=$1 [NC,L,QSA,CO=RewriteRule;02;https://www.example.org;30/;SameSite=None;Secure] RewriteRule "^(.*)\.html$" "index.php?nav=$1 [NC,L,QSA,CO=RewriteRule;03;https://www.example.org;30/;SameSite=None;Secure] [...] RewriteRule "^admin/(.*)\.html$" "admin/index.php?nav=$1 [NC,L,QSA,CO=RewriteRule;09;https://www.example.org:30/;SameSite=Strict;Secure] ``` Specifications -------------- | Specification | | --- | | [HTTP State Management Mechanism # sane-set-cookie](https://httpwg.org/specs/rfc6265.html#sane-set-cookie) | | [Cookies: HTTP State Management Mechanism # name-the-samesite-attribute](https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html#name-the-samesite-attribute) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `Lax` | 51 | 16 | 60 | 11 | 39 | 12 | 51 | 51 | 60 | 41 | 12.2 | 5.0 | | `Lax_default` | 80 | 86 | 69 | No | 71 | No | 80 | 80 | No | 60 | No | 13.0 | | `None` | 67 51-67 Rejects cookies with `SameSite=None`. See [SameSite=None: Known Incompatible Clients](https://www.chromium.org/updates/same-site/incompatible-clients). | 16 | 60 | 11 | 54 51-54 Rejects cookies with `SameSite=None`. See [SameSite=None: Known Incompatible Clients](https://www.chromium.org/updates/same-site/incompatible-clients). | 13 Not supported before macOS version 10.15 (Catalina). | 67 51-67 Rejects cookies with `SameSite=None`. See [SameSite=None: Known Incompatible Clients](https://www.chromium.org/updates/same-site/incompatible-clients). | 67 51-67 Rejects cookies with `SameSite=None`. See [SameSite=None: Known Incompatible Clients](https://www.chromium.org/updates/same-site/incompatible-clients). | 60 | 48 41-48 Rejects cookies with `SameSite=None`. See [SameSite=None: Known Incompatible Clients](https://www.chromium.org/updates/same-site/incompatible-clients). | 13 | 9.4 5.4-9.4 Rejects cookies with `SameSite=None`. See [SameSite=None: Known Incompatible Clients](https://www.chromium.org/updates/same-site/incompatible-clients). | | `Strict` | 51 | 16 | 60 | 11 | 39 | 12 | 51 | 51 | 60 | 41 | 12.2 | 5.0 | | `SameSite` | 51 | 16 | 60 | 11 | 39 | 13 Safari 13 on macOS 10.14 (Mojave), treats `SameSite=None` and invalid values as `Strict`. This is fixed in version 10.15 (Catalina) and later. 12 Treats `SameSite=None` and invalid values as `Strict` in macOS before 10.15 Catalina. See [bug 198181](https://webkit.org/b/198181). | 51 | 51 | 60 | 41 | 13 12.2 Treats `SameSite=None` and invalid values as `Strict` in iOS before 13. See [bug 198181](https://webkit.org/b/198181). | 5.0 | | `schemeful` | 89 | 89 | 79 | No | 75 | No | No | 89 | No | 63 | No | 15.0 | | `secure_context_required` | 80 | 86 | 69 | No | 71 | No | 80 | 80 | No | 60 | No | 13.0 | See also -------- * [HTTP cookies](../../cookies) * [`Cookie`](../cookie) * [`Document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) * [Samesite cookies explained](https://web.dev/samesite-cookies-explained/) (web.dev blog) http User-Agent: Firefox User-Agent: Firefox =================== Firefox user agent string reference =================================== This document describes the user agent string used in Firefox 4 and later and applications based on Gecko 2.0 and later. For a breakdown of changes to the string in Gecko 2.0, see [Final User Agent string for Firefox 4](https://hacks.mozilla.org/2010/09/final-user-agent-string-for-firefox-4/) (blog post). See also this document on [user agent sniffing](../../browser_detection_using_the_user_agent) and this [Hacks blog post](https://hacks.mozilla.org/2013/09/user-agent-detection-history-and-checklist/). General form ------------ The UA string of Firefox itself is broken down into four components: `Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail Firefox/firefoxversion` * `Mozilla/5.0` is the general token that says the browser is Mozilla compatible, and is common to almost every browser today. * `platform` describes the native platform the browser is running on (e.g. Windows, Mac, Linux or Android), and whether or not it's a mobile phone. Firefox OS phones say "`Mobile`"; the web is the platform. Note that `platform` can consist of multiple "; "-separated tokens. See below for further details and examples. **Note:** Though fixed in Firefox 69, previous 32-bit versions of Firefox running on 64-bit processors would report that the system is using a 32-bit CPU. * `rv:geckoversion` indicates the release version of Gecko (such as "`17.0`"). In recent browsers, `geckoversion` is the same as `firefoxversion`. * `Gecko/geckotrail` indicates that the browser is based on Gecko. * On Desktop, `geckotrail` is the fixed string "`20100101`" * `Firefox/firefoxversion` indicates the browser is Firefox, and provides the version (such as "`17.0`"). * From Firefox 10 on mobile, `geckotrail` is the same as `firefoxversion`. **Note:** The recommended way of sniffing for Gecko-based browsers (if you *have to* sniff for the browser engine instead of using feature detection) is by the presence of the "`Gecko`" and "`rv:`" strings, since some other browsers include a "`like Gecko`" token. For other products based on Gecko, the string can take one of two forms, where the tokens have the same meaning except those noted below: `Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail appname/appversion` `Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail Firefox/firefoxversion appname/appversion` * `appname/appversion` indicates the application name and version. For instance, this could be "`Camino/2.1.1`", or "`SeaMonkey/2.7.1`". * `Firefox/firefoxversion` is an optional compatibility token that some Gecko-based browsers may choose to incorporate, to achieve maximum compatibility with websites that expect Firefox. `firefoxversion` will generally represent the equivalent Firefox release corresponding to the given Gecko version. Some Gecko-based browsers may not opt into using this token; for this reason, sniffers should be looking for Gecko — not Firefox! Prior to Firefox 4 and Gecko 2.0, it was possible for extensions and plug-ins to add user agent parts, but that has not been possible since [bug 581008](https://bugzilla.mozilla.org/show_bug.cgi?id=581008). Mobile and Tablet indicators ---------------------------- **Note:** Only from Firefox 11 to 68. The `platform` part of the UA string indicates if Firefox is running on a phone-sized or tablet device. When Firefox runs on a device that has the phone form factor, there is a `Mobile;` token in the `platform` part of the UA string. When Firefox runs on a tablet device, there is a `Tablet;` token in the `platform` part of the UA string instead. For example: ``` Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0 Mozilla/5.0 (Android 4.4; Tablet; rv:41.0) Gecko/41.0 Firefox/41.0 ``` **Note:** The version numbers are not relevant. Avoid inferring materials based on these. The preferred way to target content to a device form factor is to use CSS Media Queries. However, if you use UA sniffing to target content to a device form factor, please look for **Mobi** (to include Opera Mobile, which uses "Mobi") for the phone form factor and do **not** assume any correlation between "Android" and the device form factor. This way, your code will work if/when Firefox ships on other phone/tablet operating systems or Android is used for laptops. Also, please use touch detection to find touch devices rather than looking for "Mobi" or "Tablet", since there may be touch devices which are not tablets. **Note:** Firefox OS devices identify themselves without any operating system indication; for example: "Mozilla/5.0 (Mobile; rv:15.0) Gecko/15.0 Firefox/15.0". The web is the platform. Windows ------- Windows user agents have the following variations, where *x.y* is the Windows NT version (for instance, Windows NT 6.1). | Windows version | Gecko user agent string | | --- | --- | | Windows NT on x86 or aarch64 CPU | Mozilla/5.0 (Windows NT *x*.*y*; rv:10.0) Gecko/20100101 Firefox/10.0 | | Windows NT on x64 CPU | Mozilla/5.0 (Windows NT *x*.*y*; Win64; x64; rv:10.0) Gecko/20100101 Firefox/10.0 | Macintosh --------- Here, *x.y* is the version of Mac OS X (for instance, Mac OS X 10.15). Starting in Firefox 87, Firefox caps the reported Mac OS X version number to 10.15, so macOS 11.0 Big Sur and later will be reported as "10.15" in the User-Agent string. Note that [Firefox no longer officially supports Mac OS X on PowerPC](https://support.mozilla.org/kb/firefox-no-longer-works-mac-os-10-4-or-powerpc). | Mac OS X version | Gecko user agent string | | --- | --- | | Mac OS X on x86, x86\_64, or aarch64 | Mozilla/5.0 (Macintosh; Intel Mac OS X *x.y*; rv:10.0) Gecko/20100101 Firefox/10.0 | | Mac OS X on PowerPC | Mozilla/5.0 (Macintosh; PPC Mac OS X *x.y*; rv:10.0) Gecko/20100101 Firefox/10.0 | Linux ----- Linux is a more diverse platform. Your distribution of Linux might include an extension that changes your user-agent. A few common examples are given below. | Linux version | Gecko user agent string | | --- | --- | | Linux desktop on i686 CPU | Mozilla/5.0 (X11; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 | | Linux desktop on x86\_64 CPU | Mozilla/5.0 (X11; Linux x86\_64; rv:10.0) Gecko/20100101 Firefox/10.0 | | Nokia N900 Linux mobile, on the Fennec browser | Mozilla/5.0 (Maemo; Linux armv7l; rv:10.0) Gecko/20100101 Firefox/10.0 Fennec/10.0 | Android (version 40 and below) ------------------------------ | Form factor | Gecko user agent string | | --- | --- | | Phone | Mozilla/5.0 (Android; Mobile; rv:40.0) Gecko/40.0 Firefox/40.0 | | Tablet | Mozilla/5.0 (Android; Tablet; rv:40.0) Gecko/40.0 Firefox/40.0 | Android (version 41 and above) ------------------------------ Beginning in version 41, Firefox for Android will contain the Android version as part of the *platform* token. For increased interoperability, if the browser is running on a version below 4 it will report 4.4. Android versions 4 and above will report the version accurately. Note that the same Gecko—with the same capabilities—is shipped to all versions of Android. | Form factor | Gecko user agent string | | --- | --- | | Phone | Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0 | | Tablet | Mozilla/5.0 (Android 4.4; Tablet; rv:41.0) Gecko/41.0 Firefox/41.0 | Focus for Android ----------------- From version 1, Focus is powered by Android WebView and uses the following user agent string format: ``` Mozilla/5.0 (Linux; <Android Version> <Build Tag etc.>) AppleWebKit/<WebKit Rev> (KHTML, like Gecko) Version/4.0 Focus/<focusversion> Chrome/<Chrome Rev> Mobile Safari/<WebKit Rev> ``` Tablet versions on WebView mirror mobile, but do not contain a `Mobile` token. Starting in Version 6, users can opt into using a GeckoView-based Focus for Android with a hidden preference: it uses a GeckoView UA string to advertise Gecko compatibility. | Focus Version (Rendering Engine) | User Agent string | | --- | --- | | 1.0 (WebView Mobile) | Mozilla/5.0 (Linux; Android 7.0) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Focus/1.0 Chrome/59.0.3029.83 Mobile Safari/537.36 | | 1.0 (WebView Tablet) | Mozilla/5.0 (Linux; Android 7.0) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Focus/1.0 Chrome/59.0.3029.83 Safari/537.36 | | 6.0 (GeckoView) | Mozilla/5.0 (Android 7.0; Mobile; rv:62.0) Gecko/62.0 Firefox/62.0 | Klar for Android ---------------- Since version 4.1, Klar for Android uses the same UA string as [Focus for Android](#focus_for_android). Before version 4.1, it sent a *Klar/<version>* *product/version* token. | Klar Version (Rendering Engine) | User Agent string | | --- | --- | | 1.0 (WebView) | Mozilla/5.0 (Linux; Android 7.0) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Klar/1.0 Chrome/58.0.3029.83 Mobile Safari/537.36 | | 4.1+ (WebView) | Mozilla/5.0 (Linux; Android 7.0) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Focus/4.1 Chrome/62.0.3029.83 Mobile Safari/537.36 | | 6.0+ (GeckoView) | Mozilla/5.0 (Android 7.0; Mobile; rv:62.0) Gecko/62.0 Firefox/62.0 | Focus for iOS ------------- Version 7 of Focus for iOS uses a user agent string with the following format: ``` Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/7.0.4 Mobile/16B91 Safari/605.1.15 ``` Note: this user agent was retrieved from an iPhone XR simulator and may be different on device. Firefox for Fire TV ------------------- Version 3 (and probably earlier) of Firefox for Fire TV use a user agent string with the following format: ``` Mozilla/5.0 (Linux; <Android version>) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Focus/<firefoxversion> Chrome/<Chrome Rev> Safari/<WebKit Rev> ``` | Firefox TV version | User Agent string | | --- | --- | | v3.0 | Mozilla/5.0 (Linux; Android 7.1.2) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Focus/3.0 Chrome/59.0.3017.125 Safari/537.36 | Firefox for Echo Show --------------------- From version 1.1, Firefox for Echo Show uses a user agent string with the following format: ``` Mozilla/5.0 (Linux; <Android version>) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Focus/<firefoxversion> Chrome/<Chrome Rev> Safari/<WebKit Rev> ``` | Firefox for Echo Show version | User agent string | | --- | --- | | v1.1 | Mozilla/5.0 (Linux; Android 5.1.1) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Focus/1.1 Chrome/59.0.3017.125 Safari/537.36 | Firefox OS ---------- | Form factor | Gecko user agent string | | --- | --- | | Phone | Mozilla/5.0 (Mobile; rv:26.0) Gecko/26.0 Firefox/26.0 | | Tablet | Mozilla/5.0 (Tablet; rv:26.0) Gecko/26.0 Firefox/26.0 | | TV | Mozilla/5.0 (TV; rv:44.0) Gecko/44.0 Firefox/44.0 | | Device-specific | Mozilla/5.0 (Mobile; ***nnnn;*** rv:26.0) Gecko/26.0 Firefox/26.0 | ### Device-specific user agent strings Although it is **strongly discouraged** by Mozilla, some handset manufacturers unfortunately include a token in their device's UA string that represents their device id. If this is the case, the Firefox OS UA string will look like the device-specific string in the table above, where ***nnnn;*** is the manufacturer's code for the device (see [Guidelines](https://wiki.mozilla.org/B2G/User_Agent/Device_Model_Inclusion_Requirements)). Some of them we have noticed are of the form "**NexusOne;**", "**ZTEOpen;**", or "**Open C;**" (note that putting space is also discouraged). We provide this information to assist with your UA detection logic, but Mozilla discourages the detection of a device id in UA strings. Here is a JavaScript regular expression that will detect all mobile devices, including devices with a device id in their UA string: ``` /mobi/i ``` The `i` makes it case-insensitive, and `mobi` matches all mobile browsers. ### Firefox OS version number While the version number for Firefox OS is not included in the UA string, it is possible to infer version information from the Gecko version number present in the UA string. | Firefox OS version number | Gecko version number | | --- | --- | | 1.0.1 | 18.0 | | 1.1 | 18.1 | | 1.2 | 26.0 | | 1.3 | 28.0 | | 1.4 | 30.0 | | 2.0 | 32.0 | | 2.1 | 34.0 | | 2.2 | 37 | | 2.5 | 44 | **Note:** It's easy to find the correspondences by looking at the [Mercurial repository names](https://hg.mozilla.org/releases): repositories starting by `mozilla-b2g` are the release repositories for Firefox OS, and have both Firefox OS and Gecko versions in their names. Firefox OS has a four-digit version number: `X.X.X.Y`. The first two digits are owned by the Mozilla product team and denote versions with new features (eg: v1.1, 1.2, etc.). The third digit is incremented with regular version tags (about every 6 weeks) for security updates, and the fourth is owned by the OEM. Firefox for iOS --------------- Firefox for iOS uses the default Mobile Safari UA string, with an additional **FxiOS/<version>** token on iPod and iPhone, similar to how [Chrome for iOS identifies itself](https://developer.chrome.com/docs/multidevice/user-agent/#chrome_for_ios_user_agent). | Form factor | Firefox for iOS user agent string | | --- | --- | | iPod | Mozilla/5.0 (iPod touch; CPU iPhone OS 8\_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) **FxiOS/1.0** Mobile/12F69 Safari/600.1.4 | | iPhone | Mozilla/5.0 (iPhone; CPU iPhone OS 8\_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) **FxiOS/1.0** Mobile/12F69 Safari/600.1.4 | | iPad | Mozilla/5.0 (Macintosh; Intel Mac OS X 10\_15\_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15 | Regarding the deviation on iPad form factor, see this [issue](https://github.com/mozilla-mobile/firefox-ios/issues/6620). Other Gecko-based browsers -------------------------- These are some sample UA strings from other Gecko-based browsers on various platforms. Note that many of these have not yet been released on Gecko 2.0! | Browser | Gecko user agent string | | --- | --- | | Firefox for Maemo (Nokia N900) | Mozilla/5.0 (Maemo; Linux armv7l; rv:10.0.1) Gecko/20100101 Firefox/10.0.1 Fennec/10.0.1 | | Camino on Mac | Mozilla/5.0 (Macintosh; Intel Mac OS X 10.5; rv:2.0.1) Gecko/20100101 Firefox/4.0.1 Camino/2.2.1 | | SeaMonkey on Windows | Mozilla/5.0 (Windows NT 5.2; rv:10.0.1) Gecko/20100101 Firefox/10.0.1 SeaMonkey/2.7.1 | | SeaMonkey on Mac | Mozilla/5.0 (Macintosh; Intel Mac OS X 10.5; rv:10.0.1) Gecko/20100101 Firefox/10.0.1 SeaMonkey/2.7.1 | | SeaMonkey on Linux | Mozilla/5.0 (X11; Linux i686; rv:10.0.1) Gecko/20100101 Firefox/10.0.1 SeaMonkey/2.7.1 | See also -------- * [Firefox OS User Agent String](https://lawrencemandel.com/2012/07/27/decision-made-firefox-os-user-agent-string/) (blog post w/[bug 777710](https://bugzilla.mozilla.org/show_bug.cgi?id=777710) reference) * [Final User Agent string for Firefox 4](https://hacks.mozilla.org/2010/09/final-user-agent-string-for-firefox-4/) (blog post) * Recommendations on [sniffing the UA string for cross-browser support](https://developer.mozilla.org/en-US/docs/Browser_Detection_and_Cross_Browser_Support) * [window.navigator.userAgent](https://developer.mozilla.org/en-US/docs/Web/API/Window/navigator) * [Add Android version to Fennec UA String (bug 1169772)](https://bugzilla.mozilla.org/show_bug.cgi?id=1169772)
programming_docs