http/internal/MessageHead.protos

Repository
guillermomolina/protos
Commit
2723a55555e7beecee0816bf99d16e3c8c1ae635
Tree
c36054e4e5abd7fc29a039b4e096cac2e8706492
Blob
9d9210b243caf01f2a3f5d90597d4e0670d2798e
Source
View exact source on GitHub
// THE LICENSED WORK IS PROVIDED UNDER THE TERMS OF THE ADAPTIVE PUBLIC LICENSE
// ("LICENSE") AS FIRST COMPLETED BY: Guillermo Adrián Molina. ANY USE, PUBLIC
// DISPLAY, PUBLIC PERFORMANCE, REPRODUCTION OR DISTRIBUTION OF, OR PREPARATION OF
// DERIVATIVE WORKS BASED ON, THE LICENSED WORK CONSTITUTES RECIPIENT'S ACCEPTANCE
// OF THIS LICENSE AND ITS TERMS, WHETHER OR NOT SUCH RECIPIENT READS THE TERMS OF
// THE LICENSE. "LICENSED WORK" AND "RECIPIENT" ARE DEFINED IN THE LICENSE. A COPY
// OF THE LICENSE IS LOCATED IN THE TEXT FILE ENTITLED "LICENSE.TXT" ACCOMPANYING
// THE CONTENTS OF THIS FILE. IF A COPY OF THE LICENSE DOES NOT ACCOMPANY THIS
// FILE, A COPY OF THE LICENSE MAY ALSO BE OBTAINED AT THE FOLLOWING WEB SITE:
// https://github.com/guillermomolina/protos
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
// the specific language governing rights and limitations under the License.

//! Internal HTTP/1.1 wire helpers for the future std:http/server driver (D215,
//! LIB025-A). This module is an unpublished implementation artifact, not an
//! approved Standard Library API. It performs no I/O and owns no authority.
//! Directional server rules live here; the generic byte, token, field-line,
//! Host, and URI syntax is shared through MessageSyntax.

MessageSyntax: import("./MessageSyntax.protos")

/// Answers a stateful parser whose feed(bytes, offset, length) consumes one
/// slice of a request head and answers {state, consumed, head, failure}. The
/// parser stops exactly after the CRLF that ends the header section, so body
/// octets are never consumed. Feeding a terminal parser signals an Error.
requestHeadParser: (limits) => {
    maxRequestLineBytes: limits.maxRequestLineBytes
    maxHeaderBytes: limits.maxHeaderBytes
    maxHeaderFields: limits.maxHeaderFields
    maxRequestBodyBytes: limits.maxRequestBodyBytes

    // Private rejection signal; only feed handles it.
    Rejection: Error {}
    rejectKind: null
    rejectStatus: 0

    reject: (kind, status) => {
        rejectKind = kind
        rejectStatus = status
        occurrence: Rejection {}
        occurrence.signal()
    }

    malformed: () => {
        reject("malformedRequest", 400)
    }

    validateTarget: (methodName, bytes, start, end) => {
        if(!MessageSyntax.isTargetOctets(bytes, start, end)) {
            malformed()
        }

        if(methodName == "CONNECT") {
            if(MessageSyntax.isHostPort(bytes, start, end, true)) {
                reject("unsupportedFeature", 501)
            }
            malformed()
        }

        if(((end - start) == 1) && (bytes[start] == 42)) {
            if(methodName != "OPTIONS") {
                malformed()
            }
        } else {
            if(bytes[start] == 47) {
                if(!MessageSyntax.isOriginForm(bytes, start, end)) {
                    malformed()
                }
            } else {
                // Authority-form outside CONNECT takes precedence over a
                // scheme-like reading of the same octets.
                if(MessageSyntax.isHostPort(bytes, start, end, true)) {
                    malformed()
                }
                if(!MessageSyntax.isAbsoluteForm(bytes, start, end)) {
                    malformed()
                }
            }
        }
    }

    // ------------------------------------------------------------ parser state

    phase: "REQUEST_LINE"
    line: Encoding.UTF8.encode("")
    pendingCr: false
    requestLineBytes: 0
    headerBytes: 0
    headerFields: 0
    requestMethod: null
    requestTarget: null
    fieldLines: []
    acceptedHead: null

    // HTTP-version = "HTTP" "/" DIGIT "." DIGIT
    isWellFormedVersion: (bytes, start, end) => {
        ((end - start) == 8) &&
            MessageSyntax.rangeEqualsAscii(bytes, start, start + 5, "HTTP/") &&
            MessageSyntax.isDigit(bytes[start + 5]) &&
            (bytes[start + 6] == 46) &&
            MessageSyntax.isDigit(bytes[start + 7])
    }

    parseRequestLine: () => {
        size: line.size()

        // The HTTP/2 preface takes precedence over method and target rules.
        if(MessageSyntax.rangeEqualsAscii(line, 0, size, "PRI * HTTP/2.0")) {
            reject("unsupportedFeature", 505)
        }

        firstSpace: MessageSyntax.indexOf(line, 0, size, 32)
        secondSpace: -1
        if(firstSpace >= 0) {
            secondSpace = MessageSyntax.indexOf(line, firstSpace + 1, size, 32)
        }
        if((firstSpace <= 0) || (secondSpace < 0) || (secondSpace == (firstSpace + 1))) {
            malformed()
        }
        if(MessageSyntax.indexOf(line, secondSpace + 1, size, 32) >= 0) {
            malformed()
        }
        if(!MessageSyntax.isToken(line, 0, firstSpace)) {
            malformed()
        }
        if(!isWellFormedVersion(line, secondSpace + 1, size)) {
            malformed()
        }
        if(!MessageSyntax.rangeEqualsAscii(line, secondSpace + 1, size, "HTTP/1.1")) {
            reject("unsupportedFeature", 505)
        }

        methodName: Encoding.Latin1.decode(MessageSyntax.copyRange(line, 0, firstSpace))
        validateTarget(methodName, line, firstSpace + 1, secondSpace)

        requestMethod = methodName
        requestTarget = MessageSyntax.copyRange(line, firstSpace + 1, secondSpace)
    }

    parseFieldLine: () => {
        pair: MessageSyntax.fieldLine(line)
        if(pair === null) {
            malformed()
        }
        fieldLines = Array(...fieldLines, pair)
    }

    finishHead: () => {
        hostCount: 0
        hostValue: null
        contentLengthCount: 0
        contentLengthValue: null
        transferEncodings: []
        expectContinue: false
        unsupportedExpect: false
        upgrade: false

        for(pair in fieldLines) {
            name: pair[0]
            value: pair[1]
            if(MessageSyntax.nameIs(name, "host")) {
                hostCount = hostCount + 1
                hostValue = value
            }
            if(MessageSyntax.nameIs(name, "content-length")) {
                contentLengthCount = contentLengthCount + 1
                contentLengthValue = value
            }
            if(MessageSyntax.nameIs(name, "transfer-encoding")) {
                transferEncodings = Array(...transferEncodings, value)
            }
            if(MessageSyntax.nameIs(name, "expect")) {
                if(MessageSyntax.bytesEqualIgnoringCase(value, "100-continue")) {
                    expectContinue = true
                } else {
                    unsupportedExpect = true
                }
            }
            if(MessageSyntax.nameIs(name, "upgrade")) {
                upgrade = true
            }
        }

        if(hostCount != 1) {
            malformed()
        }
        if(!MessageSyntax.isHostPort(hostValue, 0, hostValue.size(), false)) {
            malformed()
        }

        chunked: transferEncodings.size() > 0
        if(chunked && (contentLengthCount > 0)) {
            malformed()
        }
        if(contentLengthCount > 1) {
            malformed()
        }
        contentLength: null
        if(contentLengthCount == 1) {
            contentLength = MessageSyntax.parseContentLength(contentLengthValue)
            if(contentLength < 0) {
                malformed()
            }
        }
        if(chunked) {
            for(value in transferEncodings) {
                if(value.size() == 0) {
                    malformed()
                }
            }
            if(transferEncodings.size() != 1) {
                reject("unsupportedFeature", 501)
            }
            if(!MessageSyntax.bytesEqualIgnoringCase(transferEncodings[0], "chunked")) {
                reject("unsupportedFeature", 501)
            }
        }
        if(upgrade) {
            reject("unsupportedFeature", 501)
        }
        if(unsupportedExpect) {
            reject("unsupportedFeature", 417)
        }
        if((contentLength !== null) && (contentLength > maxRequestBodyBytes)) {
            reject("requestLimit", 413)
        }

        framing: "NONE"
        if(contentLength !== null) {
            framing = "CONTENT_LENGTH"
        }
        if(chunked) {
            framing = "CHUNKED"
        }

        acceptedHead = {
            method: requestMethod
            target: requestTarget
            version: "HTTP/1.1"
            headers: fieldLines
            framing: framing
            contentLength: contentLength
            expectContinue: expectContinue
        }
    }

    completeLine: () => {
        if(phase == "REQUEST_LINE") {
            parseRequestLine()
            phase = "HEADERS"
        } else {
            if(line.size() == 0) {
                finishHead()
            } else {
                headerFields = headerFields + 1
                if(headerFields > maxHeaderFields) {
                    reject("requestLimit", 431)
                }
                parseFieldLine()
            }
        }
        line = Encoding.UTF8.encode("")
    }

    consumeOctet: (octet) => {
        if(phase == "REQUEST_LINE") {
            requestLineBytes = requestLineBytes + 1
            if(requestLineBytes > maxRequestLineBytes) {
                reject("requestLimit", 414)
            }
        } else {
            headerBytes = headerBytes + 1
            if(headerBytes > maxHeaderBytes) {
                reject("requestLimit", 431)
            }
        }

        if(pendingCr) {
            if(octet != 10) {
                malformed()
            }
            pendingCr = false
            completeLine()
        } else {
            if(octet == 13) {
                pendingCr = true
            } else {
                if(octet == 10) {
                    malformed()
                }
                line.add(octet)
            }
        }
    }

    parser: null
    parser = {
        feed: (source, offset, length) => {
            if(phase == "TERMINAL") {
                Error().signal()
            }
            (Integer.recognizes(offset) && Integer.recognizes(length)).ifFalse(() => {
                Error().signal()
            })
            if(offset < 0) {
                Error().signal()
            }
            if(length < 0) {
                Error().signal()
            }
            // Bounds are established without computing offset + length.
            sourceSize: source.size()
            if(offset > sourceSize) {
                Error().signal()
            }
            if(length > (sourceSize - offset)) {
                Error().signal()
            }

            end: offset + length
            index: offset
            result: null

            Rejection.handle(
                () => {
                    while((acceptedHead === null) && (index < end)) {
                        octet: source[index]
                        index = index + 1
                        consumeOctet(octet)
                    }
                },
                (error) => {
                    phase = "TERMINAL"
                    line = null
                    fieldLines = []
                    result = {
                        state: "REJECTED"
                        consumed: index - offset
                        head: null
                        failure: {
                            kind: rejectKind
                            status: rejectStatus
                        }
                    }
                    error
                }
            )

            if((result === null) && (acceptedHead !== null)) {
                phase = "TERMINAL"
                line = null
                result = {
                    state: "ACCEPTED"
                    consumed: index - offset
                    head: acceptedHead
                    failure: null
                }
            }

            if(result === null) {
                result = {
                    state: "NEED_MORE"
                    consumed: length
                    head: null
                    failure: null
                }
            }

            result
        }
    }

    parser
}

/// Validates a response head and prepares its exact wire octets without I/O.
/// Answers {outcome, prepared}; prepared is {headerBytes, emission,
/// capturedBodyBytes} for "PREPARED" and null for "INVALID_RESPONSE".
prepareResponseHead: (status, headers, bodyKind, bytesBody, headRequest) => {
    ((bodyKind == "NULL") || (bodyKind == "BYTES") || (bodyKind == "STREAM")).ifFalse(() => {
        Error().signal()
    })
    ((headRequest === true) || (headRequest === false)).ifFalse(() => {
        Error().signal()
    })
    if((bodyKind != "BYTES") && (bytesBody !== null)) {
        Error().signal()
    }

    reservedNames: [
        "content-length",
        "transfer-encoding",
        "connection",
        "upgrade",
        "trailer",
        "te",
        "keep-alive",
        "proxy-connection"
    ]

    invalid: false

    // Capture status, names, values, and body before any validation outcome
    // can depend on later caller mutation (HTTP.md §4.1).
    if(!Integer.recognizes(status)) {
        invalid = true
    }
    capturedFields: []
    if(Array.recognizes(headers)) {
        for(pair in Array(...headers)) {
            if(!invalid) {
                wellShaped: Array.recognizes(pair)
                if(wellShaped) {
                    wellShaped = pair.size() == 2
                }
                if(wellShaped) {
                    wellShaped = String.recognizes(pair[0])
                }
                if(wellShaped) {
                    nameBytes: Encoding.UTF8.encode(pair[0])
                    valueBytes: MessageSyntax.snapshotBytes(pair[1])
                    if(valueBytes === null) {
                        invalid = true
                    } else {
                        capturedFields = Array(...capturedFields, [nameBytes, valueBytes])
                    }
                } else {
                    invalid = true
                }
            }
        }
    } else {
        invalid = true
    }
    capturedBody: null
    if(bodyKind == "BYTES") {
        capturedBody = MessageSyntax.snapshotBytes(bytesBody)
        if(capturedBody === null) {
            invalid = true
        }
    }

    // Validation completes before any octet of the head is produced.
    if(!invalid) {
        if((status < 200) || (status > 599)) {
            invalid = true
        }
    }
    for(field in capturedFields) {
        nameBytes: field[0]
        valueBytes: field[1]
        if(nameBytes.size() == 0) {
            invalid = true
        }
        for(octet in nameBytes) {
            if(!MessageSyntax.isTchar(octet)) {
                invalid = true
            }
        }
        for(reserved in reservedNames) {
            if(MessageSyntax.bytesEqualIgnoringCase(nameBytes, reserved)) {
                invalid = true
            }
        }
        for(octet in valueBytes) {
            if(!MessageSyntax.isFieldValueOctet(octet)) {
                invalid = true
            }
        }
    }

    framingField: null
    emission: "NONE"
    if(!invalid) {
        if((status == 204) || (status == 205) || (status == 304)) {
            if(bodyKind == "STREAM") {
                invalid = true
            }
            if((capturedBody !== null) && (capturedBody.size() != 0)) {
                invalid = true
            }
            if(status == 205) {
                framingField = "Content-Length: 0"
            }
        } else {
            if(headRequest) {
                if(bodyKind == "NULL") {
                    framingField = "Content-Length: 0"
                }
                if(bodyKind == "BYTES") {
                    framingField = "Content-Length: "
                }
            } else {
                if(bodyKind == "NULL") {
                    framingField = "Content-Length: 0"
                }
                if(bodyKind == "BYTES") {
                    framingField = "Content-Length: "
                    emission = "FIXED"
                }
                if(bodyKind == "STREAM") {
                    framingField = "Transfer-Encoding: chunked"
                    emission = "CHUNKED"
                }
            }
        }
    }

    result: {
        outcome: "INVALID_RESPONSE"
        prepared: null
    }

    if(!invalid) {
        output: Encoding.UTF8.encode("")

        appendAscii: (text) => {
            for(octet in Encoding.Latin1.encode(text)) {
                output.add(octet)
            }
        }

        appendBytes: (bytes) => {
            for(octet in bytes) {
                output.add(octet)
            }
        }

        appendDecimal: null
        appendDecimal = (value) => {
            quotient: value.div(10)
            if(quotient > 0) {
                appendDecimal(quotient)
            }
            output.add(48 + value.mod(10))
        }

        appendAscii("HTTP/1.1 ")
        appendDecimal(status)
        appendAscii(" \r\n")
        for(field in capturedFields) {
            appendBytes(field[0])
            appendAscii(": ")
            appendBytes(field[1])
            appendAscii("\r\n")
        }
        if(framingField !== null) {
            appendAscii(framingField)
            if(framingField == "Content-Length: ") {
                appendDecimal(capturedBody.size())
            }
            appendAscii("\r\n")
        }
        appendAscii("Connection: close\r\n\r\n")

        // Only a FIXED emission retains the body snapshot.
        bodyForEmission: null
        if(emission == "FIXED") {
            bodyForEmission = capturedBody
        }

        result = {
            outcome: "PREPARED"
            prepared: {
                headerBytes: output
                emission: emission
                capturedBodyBytes: bodyForEmission
            }
        }
    }

    result
}