标签:字符串搜索

共 1 篇相关文章

IT 累计浏览 2,955

Linux 内核中的 KMP 实现

Linux 内核中存在字符串搜索需求,因而在 lib/ts_kmp.c 实现了 KMP 算法,主要被三处使用:iptables string match 模块(通过字符串匹配包并做处理,比如用 `-m string --string "domain.com" --algo kmp -j DROP` 阻止对指定服务器的 HTTP 请求)、iptables conntrack amanda 模块,以及 ematch qdisc(同样基于字符串匹配对包做 QoS,如 `text(kmp foobar from 0 to 200)`)。

实现的核心仍是 prefix(即 next 数组)的计算:当 pattern[i] 匹配失败后从 pattern[next[i]] 继续匹配,从而达到 O(n) 的时间复杂度。内核的写法比网上常见版本更易懂,因为它在匹配开始之前就调用 compute_prefix_tbl 把 prefix 表一次性算好,主函数 kmp_find 再据此进行匹配;两者都支持通过 TS_IGNORECASE 标志做忽略大小写(toupper)处理,kmp_find 还支持通过 get_next_block 分块读取文本,匹配成功则返回偏移位置,未命中返回 UINT_MAX。

需要注意的是,内核对 KMP 做了接口封装,不能直接调用。内核模块若要使用,可参考 lib/textsearch.c 中的示例:用 textsearch_prepare("kmp", pattern, ...) 准备 ts_config,再用 textsearch_find_continuous 做连续匹配,最后 textsearch_destroy 释放资源。