nginx - 此代码如何产生字符串 "nginx"?

标签 nginx hex huffman-code

我已经尝试研究 nginx 源代码有一段时间了。最近,Nginx 1.9.12 发布了,他们实现了“HTTP/2 中响应头的霍夫曼编码”。

在此版本中,我无法理解这一行,

static const u_char nginx[5] = "\x84\xaa\x63\x55\xe7";

或者,您可以在此处浏览源代码:https://trac.nginx.org/nginx/browser/nginx/src/http/v2/ngx_http_v2_filter_module.c#L146

这一行是 Nginx 用于插入 header “Server: nginx”的内容。

如果我想将其更改为“Apache”怎么办?我尝试将字符串“apache”转换为十六进制,然后用\xhh 表示法替换文件中生成的十六进制,并将 nginx[5] 更改为 nginx[6],因为字符串 apache 的长度为 6 个字符。

但是输出似乎不可预测。在在这里问这个问题之前我已经搜索了很多。

有人可以帮我看看这段代码是如何工作的以及如何替换文本吗?有任何脚本或在线网络应用程序可以使它更容易吗?

最佳答案

我编写了简单的 Go 脚本来转换 HPACK 压缩字符串:

package main

// ////////////////////////////////////////////////////////////////////////////////// //

import (
    "fmt"
    "golang.org/x/net/http2/hpack"
)

// ////////////////////////////////////////////////////////////////////////////////// //

func main() {
    fmt.Println("nginx", "→", Encode("nginx"))
    fmt.Println("apache", "→", Encode("apache"))
    fmt.Println("-----")
    fmt.Println("\\x84\\xaa\\x63\\x55\\xe7", "→", Decode("\x84\xaa\x63\x55\xe7"))
    fmt.Println("\\x84\\x1d\\x63\\x24\\xe5", "→", Decode("\x84\x1d\x63\x24\xe5"))
}

func Encode(s string) string {
    var result string

    hd := hpack.AppendHuffmanString(nil, s)
    hl := hpack.HuffmanEncodeLength(s) | 0x80

    result += RenderByte(byte(hl))

    for _, b := range hd {
        result += RenderByte(b)
    }

    return result
}

func Decode(s string) string {
    data := []byte(s)
    result, _ := hpack.HuffmanDecodeToString(data[1:])
    return result
}

func RenderByte(b byte) string {
    return fmt.Sprintf("\\x%x", b)
}

// ////////////////////////////////////////////////////////////////////////////////// //

关于nginx - 此代码如何产生字符串 "nginx"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35655448/

相关文章:

javascript - 如何将 html 实体的十六进制代码解码为 javascript 中的文本?

javascript - 使用 NodeJS 缓冲区

c - 近似保序霍夫曼代码

sql - 有没有一种简单的方法使用 sql server/TSQL 进行十六进制算术?

c++ - 霍夫曼解码压缩文件

c++ - 如何从霍夫曼树生成霍夫曼码

ssl - Nginx 反向代理到 Heroku 的 SSL 握手失败

python - Djangocollectstatics仅收集管理静态文件

nginx - Nginx 日志中出现警告,需要对请求进行解释

configuration - nginx catchallconf 文件未捕获所有内容