function _M.match_and_set()

in apisix/ssl/router/radixtree_sni.lua [148:222]


function _M.match_and_set(api_ctx, match_only, alt_sni)
    local err
    if not radixtree_router or
       radixtree_router_ver ~= ssl_certificates.conf_version then
        radixtree_router, err = create_router(ssl_certificates.values)
        if not radixtree_router then
            return false, "failed to create radixtree router: " .. err
        end
        radixtree_router_ver = ssl_certificates.conf_version
    end

    local sni = alt_sni
    if not sni then
        sni, err = apisix_ssl.server_name()
        if type(sni) ~= "string" then
            local advise = "please check if the client requests via IP or uses an outdated " ..
                           "protocol. If you need to report an issue, " ..
                           "provide a packet capture file of the TLS handshake."
            return false, "failed to find SNI: " .. (err or advise)
        end
    end

    core.log.debug("sni: ", sni)

    local sni_rev = sni:reverse()
    local ok = radixtree_router:dispatch(sni_rev, nil, api_ctx)
    if not ok then
        if not alt_sni then
            
            
            core.log.error("failed to find any SSL certificate by SNI: ", sni)
        end
        return false
    end


    if type(api_ctx.matched_sni) == "table" then
        local matched = false
        for _, msni in ipairs(api_ctx.matched_sni) do
            if sni_rev == msni or not str_find(sni_rev, ".", #msni) then
                matched = true
                break
            end
        end
        if not matched then
            local log_snis = core.json.encode(api_ctx.matched_sni, true)
            if log_snis ~= nil then
                log_snis = str_gsub(log_snis:reverse(), "%[", "%]")
                log_snis = str_gsub(log_snis, "%]", "%[", 1)
            end
            core.log.warn("failed to find any SSL certificate by SNI: ",
                          sni, " matched SNIs: ", log_snis)
            return false
        end
    else
        if str_find(sni_rev, ".", #api_ctx.matched_sni) then
            core.log.warn("failed to find any SSL certificate by SNI: ",
                          sni, " matched SNI: ", api_ctx.matched_sni:reverse())
            return false
        end
    end

    core.log.info("debug - matched: ", core.json.delay_encode(api_ctx.matched_ssl, true))

    if match_only then
        return true
    end

    ok, err = _M.set(api_ctx.matched_ssl, sni)
    if not ok then
        return false, err
    end

    return true
end