1#!/usr/bin/env bcc-lua 2--[[ 3Copyright 2016 Marek Vavrusa <mvavrusa@cloudflare.com> 4 5Licensed under the Apache License, Version 2.0 (the "License"); 6you may not use this file except in compliance with the License. 7You may obtain a copy of the License at 8 9http://www.apache.org/licenses/LICENSE-2.0 10 11Unless required by applicable law or agreed to in writing, software 12distributed under the License is distributed on an "AS IS" BASIS, 13WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14See the License for the specific language governing permissions and 15limitations under the License. 16]] 17-- Simple parsing example of TCP/HTTP that counts frequency of types of requests 18-- and shows more complicated pattern matching constructions and slices. 19-- Rewrite of a BCC example: 20-- https://github.com/iovisor/bcc/blob/master/examples/networking/http_filter/http-parse-simple.c 21local ffi = require("ffi") 22local bpf = require("bpf") 23local S = require("syscall") 24 25-- Shared part of the program 26local map = bpf.map('hash', 64) 27-- Kernel-space part of the program 28local prog = bpf.socket('lo', function (skb) 29 -- Only ingress so we don't count twice on loopback 30 if skb.ingress_ifindex == 0 then return end 31 local data = pkt.ip.tcp.data -- Get TCP protocol dissector 32 -- Continue only if we have 7 bytes of TCP data 33 if data + 7 > skb.len then return end 34 -- Fetch 4 bytes of TCP data and compare 35 local h = data(0, 4) 36 if h == 'HTTP' or h == 'GET ' or 37 h == 'POST' or h == 'PUT ' or 38 h == 'HEAD' or h == 'DELE' then 39 -- If hash key doesn't exist, create it 40 -- otherwise increment counter 41 local v = map[h] 42 if not v then map[h] = 1 43 else xadd(map[h], 1) 44 end 45 end 46end) 47-- User-space part of the program 48for _ = 1, 10 do 49 local strkey = ffi.new('uint32_t [1]') 50 local s = '' 51 for k,v in map.pairs,map,0 do 52 strkey[0] = bpf.ntoh(k) 53 s = s..string.format('%s %d ', ffi.string(strkey, 4):match '^%s*(.-)%s*$', tonumber(v)) 54 end 55 if #s > 0 then print(s..'messages') end 56 S.sleep(1) 57end