pcaprub-0.13.3/ 0000755 0000041 0000041 00000000000 14666442051 013272 5 ustar www-data www-data pcaprub-0.13.3/USAGE.rdoc 0000644 0000041 0000041 00000005635 14666442051 015020 0 ustar www-data www-data = Usage of Pcaprub
Pcaprub is a ruby wrapper to the libpcap libary. It provides a common method to access the c bindings defined in libpcap.
Many of the methods require the Pcap instance to be "ready".
- "Ready" is defined as being initiated with open_live open_dead or open_offline.
== Basics of Pcaprub
require "rubygems"
require "pcaprub"
mypcap = PCAPRUB::Pcap.new
== Backwards Compatibility
Pcaprub is included automatically upon load. This mixes in ::Pcap for backwards compatibility.
require "rubygems"
require "pcaprub"
mypcap = ::Pcap.new
== Setting up a live Capture
dev = PCAPRUB::Pcap.lookupdev
snaplength = 65535
promiscous_mode = true
timeout = 0
system("ifconfig", dev, "up")
capture = ::Pcap.open_live(dev, snaplength, promiscous_mode, timeout)
== Open an existing pcap file
pcapfile = File.dirname(__FILE__) + "/foo.pcap"
if(not File.exists?(pcapfile))
raise RuntimeError, "The PCAP file #{pcapfile} could not be found"
end
capture = ::Pcap.open_offline(pcapfile)
== Setting a BPF Filter
bpf = "ip and not net 10.0.0.0/8"
capture.setfilter(bpf)
== Reading Capture Statistics
Packets Received
capture.stats['recv']
Packets Dropped
capture.stats['drop']
Packets Dropped by Interface
capture.stats['ifdrop']
== Running the Capture
Sniffing a set number of packets and also letting the user Interrupt Early
capture_packets = 100
begin
capture.each do |packet|
p packet
# Handling the number of packets to process
capture_packets -= 1
if capture_packets == 0
break
end
end
# ^C to stop sniffing
rescue Interrupt
puts "\nPacket Capture stopped by interrupt signal."
rescue Exception => e
puts "\nERROR: #{e}"
retry
end
== Examining the DataLink
Ethernet or Linux loopback
if capture.datalink == PCAPRUB::Pcap::DLT_EN10MB
puts "Ethernet 10MB Link detected"
end
== Examining Packet Internals
Sniffing and yielding Packet Objects using "each_packet"
require 'pcaprub'
SNAPLENGTH = 65535
capture = PCAPRUB::Pcap.open_live('wlan0', SNAPLENGTH, true, 0)
capture.setfilter('port 80')
capture_packets = 10
capture.each_packet do |packet|
puts packet.class
puts Time.at(packet.time)
puts "micro => #{packet.microsec}"
puts "Packet Length => #{packet.length}"
p packet.data
capture_packets -= 1
if capture_packets == 0
break
end
end
== Using the Packet Dump Capabilities
Write to file Example.pcap the first 10 packets on eth0.
require 'pcaprub'
SNAPLENGTH = 65535
capture = PCAPRUB::Pcap.open_live('eth0', SNAPLENGTH, true, 0)
dumper = capture.dump_open('./Example.pcap')
capture_packets = 10
capture.each do |packet|
capture.dump(packet.length, packet.length, packet)
capture_packets -= 1
if capture_packets == 0
break
end
end
capture.dump_close
pcaprub-0.13.3/FAQ.rdoc 0000644 0000041 0000041 00000002777 14666442051 014567 0 ustar www-data www-data = FAQ
Enough already! How does this work by example!?
#!/usr/bin/env ruby
require "rubygems"
require "pcaprub"
class CaptureExample
def initialize()
#interface configuration
@dev = ::Pcap.lookupdev
#promiscous_mode = true
@promiscous_mode = false
@timeout = 0
#packet information
@capture_packets = 100
@snaplength = 65535
@bpf = "ip and not dst net 110.0.0.0/8"
end
def getpackets
system("ifconfig", @dev, "up")
capture = ::Pcap.open_live(@dev, @snaplength, @promiscous_mode, @timeout)
capture.setfilter(@bpf)
begin
puts "Started capture..(#{@dev} => \"#{@bpf}\")"
capture.each do |packet|
# Handling the number of packets to process
@capture_packets -= 1
if @capture_packets == 0
break
end
end
# ^C to stop sniffing
rescue Interrupt
puts "\nPacket Capture stopped by interrupt signal."
rescue Exception => e
puts "\nERROR: #{e}"
retry
end
puts "Captured #{100 - @capture_packets} packets"
return capture
end
end
mycapture = CaptureExample.new()
packet_capture = mycapture.getpackets
puts "capture.stats['recv'] = #{packet_capture.stats['recv']}"
puts "capture.stats['drop'] = #{packet_capture.stats['drop']}"
pcaprub-0.13.3/README.rdoc 0000644 0000041 0000041 00000007736 14666442051 015115 0 ustar www-data www-data = pcaprub
{
}[https://gitter.im/pcaprub/pcaprub?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge]
{
}[https://ci.appveyor.com/project/shadowbq/pcaprub]
{
}[https://codeclimate.com/github/pcaprub/pcaprub]
{
}[http://badge.fury.io/rb/pcaprub]
{
}[https://gemnasium.com/pcaprub/pcaprub]
This goal of this project is to provide a consistent interface
to LBL's libpcap packet capture library.
== Limitations
This does not provide packet processing functionality, it simply provides
the interface for capturing packets, and passing yielding those packets.
For packet processing capability look at ruby gems PCAPFU, PCAPLET, etc..
== Requirements
MRI POSIX Ruby (Native compilation) [Travis-CI Tested]
~> Ruby 2.4
libpcap - http://www.tcpdump.org
Ruby with DevKit(32bit) on Windows [AppVeyor Tested]
Ruby 1.9.3
~> Ruby 2.x
WinPcap Developer's Pack - http://www.winpcap.org
== Installation
gem install pcaprub
Advanced options in a Windows ENV
gem install pcaprub --no-ri --no-rdoc -- --with-pcap-dir="c:/dev/src/WpdPack"
== Usage
require 'rubygems'
require 'pcaprub'
cap = PCAPRUB::Pcap.new
== Current Repository for Gemcutter source
The Git Repo on Github @pcaprub is forked from the Metasploit SVN repo
git clone git://github.com/pcaprub/pcaprub.git
== Additionals
=== Notes on 0.11.x series and beyond.
The gem is now a module. The module is autoincluded, but this helps with name collisions and additional growth.
Some of the Error handling and basic intensive code is moving out the C base-extension (ext) and into native Ruby.
The file handling in dumper is now attached to the Capture Class and not the Module as an additional singleton.
capture = PCAPRUB::Pcap.open_live('eth0', SNAPLENGTH, true, 0)
capture.dump_open('./Example.pcap')
{ ... }
capture.dump_close
=== Timstamps from the PCAP Header
Timestamps are now available when yeilding packets instead of strings
capture = PCAPRUB::Pcap.open_live('eth0', SNAPLENGTH, true, 0)
capture.each_packet do |packet|
puts Time.at(packet.time)
puts "micro => #{packet.microsec}"
end
=== Ruby 1.8.7 & WinPcap
On Ruby 1.8 with winpcap, rb_thread_polling pauses for 100 milliseconds between reads. This may mean some packets are missed.
== LICENSE
GNU Lesser General Public License v2.1 (LGPL-2.1)
https://www.tldrlegal.com/l/lgpl2
See LICENCE for details
Copyright © 2010 - 2014
=== Notes on other repositories in compliance with LGPL-2.1
All original code maintains its copyright from its original authors and licensing.
On March 2014 this project was migrated to https://github.com/pcaprub/pcaprub from https://github.com/shadowbq/pcaprub
The Git Repo on Github @pcaprub is a forked merge from the Metasploit SVN repo
git clone git://github.com/shadowbq/pcaprub.git (moved)
The Metasploit Project also provides a Subversion repository: (0.9-dev)
svn checkout http://metasploit.com/svn/framework3/trunk/external/pcaprub/
Packetfu Project also provides a listing (0.9-dev)
http://code.google.com/p/packetfu/source/browse/#svn/trunk/pcaprub_linux
The Marshall Beddoe's Outdate RubyForge svn version can be obtained from Subversion: (0.7-dev)
svn checkout http://pcaprub.rubyforge.org/svn/trunk/
http download Public Rubyforge (0.6)
https://github.com/unmarshal/pcaprub
SourceForge Masaki Fukushima 2000 (0.6) -- Object Creation Heavy Implementation (PCAPLET integrated)
http://sourceforge.net/apps/trac/rubypcap/
Additonal Github Repos
https://github.com/dxoigmn/pcaprub (0.8-dev)
https://github.com/spox /pcaprub-spox (0.8-dev+)
pcaprub-0.13.3/.document 0000644 0000041 0000041 00000000074 14666442051 015112 0 ustar www-data www-data README.rdoc
lib/**/*.rb
bin/*
features/**/*.feature
LICENSE
pcaprub-0.13.3/lib/ 0000755 0000041 0000041 00000000000 14666442051 014040 5 ustar www-data www-data pcaprub-0.13.3/lib/pcaprub/ 0000755 0000041 0000041 00000000000 14666442051 015474 5 ustar www-data www-data pcaprub-0.13.3/lib/pcaprub/common.rb 0000644 0000041 0000041 00000001023 14666442051 017305 0 ustar www-data www-data
module PCAPRUB
# The base exception for JSON errors.
class PCAPRUBError < StandardError; end
# This exception is raised, if a Device Binding error occurs.
class BindingError < PCAPRUBError; end
# This exception is raised, if the BPF Filter raises a fault
class BPFError < PCAPRUBError; end
# This exception is raised, if the libpcap Dumper raises a fault
# deep.
class DumperError < PCAPRUBError; end
# Raised if unable to set underlying capture link type
class LinkTypeError < PCAPRUBError; end
end
pcaprub-0.13.3/lib/pcaprub/ext.rb 0000644 0000041 0000041 00000000473 14666442051 016625 0 ustar www-data www-data begin
if RUBY_VERSION =~ /2.0/
require '2.0/pcaprub_c'
elsif RUBY_VERSION =~ /2.1/
require '2.1/pcaprub_c'
elsif RUBY_VERSION =~ /2.2/
require '2.2/pcaprub_c'
elsif RUBY_VERSION =~ /2.3/
require '2.3/pcaprub_c'
else
require 'pcaprub_c'
end
rescue Exception
require 'pcaprub_c'
end
pcaprub-0.13.3/lib/pcaprub/version.rb 0000644 0000041 0000041 00000000355 14666442051 017511 0 ustar www-data www-data module PCAPRUB #:nodoc:
module VERSION #:nodoc:
MAJOR = 0
MINOR = 13
TINY = 3
STRING = [MAJOR, MINOR, TINY].join('.')
end
class Pcap
def self.version
return PCAPRUB::VERSION::STRING
end
end
end
pcaprub-0.13.3/lib/pcaprub.rb 0000644 0000041 0000041 00000001406 14666442051 016022 0 ustar www-data www-data module PCAPRUB
$:.unshift(File.dirname(__FILE__))
require 'pcaprub/common'
require 'pcaprub/version'
add_dll_path = proc do |path, &block|
if RUBY_PLATFORM =~/(mswin|mingw)/i && path && File.exist?(path)
begin
require 'ruby_installer/runtime'
RubyInstaller::Runtime.add_dll_directory(path, &block)
rescue LoadError
old_path = ENV['PATH']
ENV['PATH'] = "#{path};#{old_path}"
begin
block.call
ensure
ENV['PATH'] = old_path
end
end
else
block.call
end
end
npcap_path = "C:\\Windows\\System32\\Npcap"
add_dll_path.call(npcap_path) do
require 'pcaprub/ext'
end
end
#Force Include to allow backwards compatibility to ::PCAP.new
include PCAPRUB
pcaprub-0.13.3/test/ 0000755 0000041 0000041 00000000000 14666442051 014251 5 ustar www-data www-data pcaprub-0.13.3/test/test_pcaprub_unit.rb 0000644 0000041 0000041 00000007717 14666442051 020344 0 ustar www-data www-data #!/usr/bin/env ruby
base = File.symlink?(__FILE__) ? File.readlink(__FILE__) : __FILE__
$:.unshift(File.join(File.dirname(base)))
require File.expand_path '../test_helper.rb', __FILE__
#
# Simple unit test, requires r00t.
#
class Pcap::UnitTest < Test::Unit::TestCase
def test_version
assert_equal(String, Pcap.version.class)
# puts "Pcaprub version: #{Pcap.version}"
end
def test_lookupdev
assert_equal(String, Pcap.lookupdev.class)
# puts "Pcaprub default device: #{Pcap.lookupdev}"
end
def test_lookupnet
dev = Pcap.lookupdev
assert_equal(Array, Pcap.lookupnet(dev).class)
net = Pcap.lookupnet(dev)
assert net
# puts "Pcaprub net (#{dev}): #{net[0]} #{[net[1]].pack("N").unpack("H*")[0]}"
end
def test_pcap_new
o = Pcap.new
assert_equal(Pcap, o.class)
end
def test_pcap_setfilter_bad
e = nil
o = Pcap.new
begin
o.setfilter("not ip")
rescue ::Exception => e
end
assert_equal(e.class, PCAPRUB::PCAPRUBError)
end
def test_pcap_setfilter
d = Pcap.lookupdev
o = Pcap.open_live(d, 65535, true, 1)
r = o.setfilter("not ip")
assert_equal(Pcap, r.class)
end
def test_pcap_inject
d = Pcap.lookupdev
o = Pcap.open_live(d, 65535, true, 1)
r = o.inject("X" * 512)
assert_equal(512, r)
# UPDATE: TRAVIS CI is now on a new hardware platform.
# Travis CI's virtual network interface does not support injection
#if ENV['CI']
# assert_equal(-1,r)
#else
# assert_equal(512, r)
#end
end
def test_pcap_datalink
d = Pcap.lookupdev
o = Pcap.open_live(d, 65535, true, 1)
r = o.datalink
assert_equal(Integer, r.class)
end
def test_pcap_snapshot
d = Pcap.lookupdev
o = Pcap.open_live(d, 1344, true, 1)
r = o.snapshot
assert_equal(1344, r)
end
def test_pcap_stats
d = Pcap.lookupdev
o = Pcap.open_live(d, 1344, true, 1)
r = o.stats
assert_equal(Hash, r.class)
end
def test_pcap_next
d = Pcap.lookupdev
o = Pcap.open_live(d, 1344, true, 1)
@c = 0
t = Thread.new { while(true); @c += 1; select(nil, nil, nil, 0.10); end; }
pkt_count = 0
require 'timeout'
begin
Timeout.timeout(10) do
o.each do |pkt|
pkt_count += 1
end
end
rescue ::Timeout::Error
end
t.kill
# puts "Background thread ticked #{@c} times while capture was running"
# puts "Captured #{pkt_count} packets"
assert(0 < @c, "Background thread failed to tick while capture was running");
true
end
def test_create_from_primitives
d = Pcap.lookupdev
o = Pcap.create(d).setsnaplen(65535).settimeout(100).setpromisc(true)
assert_equal(o, o.activate)
o.close
end
def test_set_datalink
d = Pcap.lookupdev
o = Pcap.open_live(d, 65535, true, 1)
dls = o.listdatalinks
begin
assert_equal(o,o.setdatalink(dls.values.first))
rescue PCAPRUB::LinkTypeError
print "#{dls} - Data LinkType Binding issue in the environment (Skipping)"
assert_equal(o,o)
end
end
def test_monitor
return if RUBY_PLATFORM =~ /mingw/
d = Pcap.lookupdev
o = Pcap.create(d)
assert_equal(o, o.setmonitor(true))
end
def test_open_dead
# No applied filters on OPEN_DEAD just compile checking
o = Pcap.open_dead(Pcap::DLT_NULL, 65535)
assert_nothing_raised do
o.compile("ip host 1.2.3.4")
end
assert_raise PCAPRUB::BPFError do
o.setfilter("ip host 1.2.3.5")
end
end
def test_filter
d = Pcap.lookupdev
o = Pcap.create(d)
o.activate
assert_nothing_raised do
o.compile("ip host 1.2.3.4")
end
assert_raise PCAPRUB::BPFError do
o.compile("A non working filter")
end
end
def test_lib_version
v = Pcap.lib_version.split
if RUBY_PLATFORM =~ /mingw/
winpcap = 'WinPcap' == v[0]
npcap = 'Npcap' == v[0]
assert winpcap || npcap
else
assert_equal "libpcap", v[0]
end
assert_equal "version", v[1]
end
end
pcaprub-0.13.3/test/test_helper.rb 0000644 0000041 0000041 00000000401 14666442051 017107 0 ustar www-data www-data require 'rubygems'
require 'bundler/setup'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require "minitest/autorun"
require 'test/unit'
require 'pcaprub'
require 'coveralls'
Coveralls.wear!
pcaprub-0.13.3/Rakefile 0000644 0000041 0000041 00000006705 14666442051 014747 0 ustar www-data www-data #require "bundler/gem_tasks"
require './lib/pcaprub/version.rb'
def java?
/java/ === RUBY_PLATFORM
end
ENV['LANG'] = "en_US.UTF-8"
@gemspec = Gem::Specification.new do |spec|
spec.name = "pcaprub"
spec.version = PCAPRUB::Pcap.version
spec.authors = ["shadowbq", "crondaemon", "jmcavinee", "unmarshal"]
spec.email = "shadowbq@gmail.com"
spec.description = "libpcap bindings for Ruby 2.x"
spec.summary = "libpcap bindings for ruby"
spec.homepage = "https://github.com/pcaprub/pcaprub"
spec.requirements = "libpcap"
spec.license = "LGPL-2.1"
spec.required_ruby_version = '>= 2.0'
spec.files = [
".document",
"FAQ.rdoc",
"Gemfile",
"LICENSE",
"README.rdoc",
"Rakefile",
"USAGE.rdoc",
"examples/dead_cap.rb",
"examples/file_cap.rb",
"examples/simple_cap.rb",
"examples/telnet-raw.pcap",
"ext/pcaprub_c/extconf.rb",
"ext/pcaprub_c/pcaprub.c",
"lib/pcaprub.rb",
"lib/pcaprub/common.rb",
"lib/pcaprub/ext.rb",
"lib/pcaprub/version.rb",
"test/test_helper.rb",
"test/test_pcaprub_unit.rb"
]
spec.extra_rdoc_files = [
"FAQ.rdoc",
"LICENSE",
"README.rdoc",
"USAGE.rdoc",
"ext/pcaprub_c/pcaprub.c"
]
spec.extensions = FileList["ext/**/extconf.rb"]
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake", '~> 0.9', '>= 0.9.2'
spec.add_development_dependency "rake-compiler", '~> 0.6', '>= 0.6.0'
spec.add_development_dependency "shoulda-context", '~> 1.1', '~> 1.1.6'
spec.add_development_dependency "minitest", '~> 4.7', '>= 4.7.0'
end
require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.libs << 'lib' << 'test'
test.test_files = FileList['test/test_pcaprub_unit.rb']
test.verbose = true
end
task :test
require 'rubygems/package_task'
Gem::PackageTask.new(@gemspec) do |pkg|
pkg.need_zip = false
pkg.need_tar = false
end
# prepend DevKit into compilation phase
if RUBY_PLATFORM =~ /mingw/
task :compile => [:devkit]
task :native => [:devkit]
end
task :devkit do
begin
require "devkit"
rescue LoadError => e
abort "Failed to activate RubyInstaller's DevKit required for compilation."
end
end
require 'rake/extensiontask'
Rake::ExtensionTask.new('pcaprub_c', @gemspec)
task :default => [:compile, :test]
require 'rdoc/task'
RDoc::Task.new do |rdoc|
version = PCAPRUB::VERSION::STRING
rdoc.rdoc_dir = 'rdoc'
rdoc.title = "pcaprub #{version}"
rdoc.rdoc_files.include('README*')
rdoc.rdoc_files.include('FAQ*')
rdoc.rdoc_files.include('LICENSE*')
rdoc.rdoc_files.include('lib/**/*.rb')
rdoc.rdoc_files.include('ext/**/*.c')
end
require 'rubygems/tasks'
Gem::Tasks.new
# Override standard release task
require 'git'
Rake::Task["release"].clear
desc 'Release the gem (create tag, build, publish)'
task :release do
version = "#{PCAPRUB::VERSION::STRING}"
remote = 'origin'
puts "Creating tag v#{version}"
git = Git.open(".")
git.add_tag("v#{version}")
puts "Pushing tag to #{remote}"
git.push(remote, 'master', true)
Rake::Task['clobber'].invoke
Rake::Task['compile'].invoke
Rake::Task['gem'].invoke
gemtask = Gem::Tasks::Push.new
gemtask.push("pkg/pcaprub-#{version}.gem")
end
pcaprub-0.13.3/pcaprub.gemspec 0000644 0000041 0000041 00000005155 14666442051 016301 0 ustar www-data www-data #########################################################
# This file has been automatically generated by gem2tgz #
#########################################################
# -*- encoding: utf-8 -*-
# stub: pcaprub 0.13.3 ruby lib
# stub: ext/pcaprub_c/extconf.rb
Gem::Specification.new do |s|
s.name = "pcaprub".freeze
s.version = "0.13.3"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["shadowbq".freeze, "crondaemon".freeze, "jmcavinee".freeze, "unmarshal".freeze]
s.date = "2024-07-29"
s.description = "libpcap bindings for Ruby 2.x".freeze
s.email = "shadowbq@gmail.com".freeze
s.extensions = ["ext/pcaprub_c/extconf.rb".freeze]
s.extra_rdoc_files = ["FAQ.rdoc".freeze, "LICENSE".freeze, "README.rdoc".freeze, "USAGE.rdoc".freeze, "ext/pcaprub_c/pcaprub.c".freeze]
s.files = [".document".freeze, "FAQ.rdoc".freeze, "Gemfile".freeze, "LICENSE".freeze, "README.rdoc".freeze, "Rakefile".freeze, "USAGE.rdoc".freeze, "examples/dead_cap.rb".freeze, "examples/file_cap.rb".freeze, "examples/simple_cap.rb".freeze, "examples/telnet-raw.pcap".freeze, "ext/pcaprub_c/extconf.rb".freeze, "ext/pcaprub_c/pcaprub.c".freeze, "lib/pcaprub.rb".freeze, "lib/pcaprub/common.rb".freeze, "lib/pcaprub/ext.rb".freeze, "lib/pcaprub/version.rb".freeze, "test/test_helper.rb".freeze, "test/test_pcaprub_unit.rb".freeze]
s.homepage = "https://github.com/pcaprub/pcaprub".freeze
s.licenses = ["LGPL-2.1".freeze]
s.required_ruby_version = Gem::Requirement.new(">= 2.0".freeze)
s.requirements = ["libpcap".freeze]
s.rubygems_version = "3.3.15".freeze
s.summary = "libpcap bindings for ruby".freeze
s.test_files = ["test/test_helper.rb".freeze, "test/test_pcaprub_unit.rb".freeze]
if s.respond_to? :specification_version then
s.specification_version = 4
end
if s.respond_to? :add_runtime_dependency then
s.add_development_dependency(%q.freeze, ["~> 1.3"])
s.add_development_dependency(%q.freeze, ["~> 4.7", ">= 4.7.0"])
s.add_development_dependency(%q.freeze, ["~> 0.9", ">= 0.9.2"])
s.add_development_dependency(%q.freeze, ["~> 0.6", ">= 0.6.0"])
s.add_development_dependency(%q.freeze, ["~> 1.1", "~> 1.1.6"])
else
s.add_dependency(%q.freeze, ["~> 1.3"])
s.add_dependency(%q.freeze, ["~> 4.7", ">= 4.7.0"])
s.add_dependency(%q.freeze, ["~> 0.9", ">= 0.9.2"])
s.add_dependency(%q.freeze, ["~> 0.6", ">= 0.6.0"])
s.add_dependency(%q.freeze, ["~> 1.1", "~> 1.1.6"])
end
end
pcaprub-0.13.3/Gemfile 0000644 0000041 0000041 00000000741 14666442051 014567 0 ustar www-data www-data source 'https://rubygems.org'
group :development, :test do
# Prevent occasions where minitest is not bundled in packaged versions of ruby (see #3826)
gem 'minitest', '~> 4.7.0'
gem 'shoulda-context', '~> 1.1.6'
gem 'test-unit'
gem 'coveralls', :require => false
end
gem 'rake-compiler', '>= 0.6.0'
gem 'rubygems-tasks'
if Bundler.current_ruby.mri? || Bundler.current_ruby.mingw? || Bundler.current_ruby.x64_mingw?
gem 'rake', '>= 0.9.2'
gem 'git', '~> 1.13.0'
end
pcaprub-0.13.3/LICENSE 0000644 0000041 0000041 00000057506 14666442051 014314 0 ustar www-data www-data GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
pcaprub-0.13.3/ext/ 0000755 0000041 0000041 00000000000 14666442051 014072 5 ustar www-data www-data pcaprub-0.13.3/ext/pcaprub_c/ 0000755 0000041 0000041 00000000000 14666442051 016030 5 ustar www-data www-data pcaprub-0.13.3/ext/pcaprub_c/pcaprub.c 0000644 0000041 0000041 00000102167 14666442051 017637 0 ustar www-data www-data #include "ruby.h"
#ifdef HAVE_RUBY_THREAD_H
#include "ruby/thread.h"
#endif
#ifdef MAKE_TRAP
#include "rubysig.h"
#endif
#include
// Win32-Extensions only exist in winpcap not npcap
#if defined(WIN32)
#ifdef HAVE_WIN32_EXTENSIONS_H
#include
#endif
#endif
#if !defined(WIN32)
#include
#include
#include
#endif
static VALUE mPCAP;
static VALUE rb_cPcap, rb_cPkt;
static VALUE ePCAPRUBError, eDumperError, eBindingError, eBPFilterError, eLinkTypeError;
#if defined(WIN32)
static VALUE rbpcap_thread_wait_handle(HANDLE fno);
#endif
// Now defined in Native Ruby
// #define PCAPRUB_VERSION "*.*.*"
#define OFFLINE 1
#define LIVE 2
#define DEAD 3
#if !defined(PCAP_NETMASK_UNKNOWN)
/*
* Version of libpcap < 1.1
* Value to pass to pcap_compile() as the netmask if you dont know what the netmask is.
*/
#define PCAP_NETMASK_UNKNOWN 0xffffffff
#endif
typedef struct rbpcap {
pcap_t *pd;
pcap_dumper_t *pdt;
char iface[256];
char type;
} rbpcap_t;
typedef struct rbpcapjob {
struct pcap_pkthdr hdr;
unsigned char *pkt;
int wtf;
} rbpcapjob_t;
typedef struct rbpacket {
struct pcap_pkthdr hdr;
u_char* pkt;
} rbpacket_t;
/*
* Return the pcap version
*/
static VALUE
rbpcap_s_lib_version(VALUE self)
{
return rb_str_new2(pcap_lib_version());
}
/*
* Return the name of a network device on the system.
*
* The pcap_lookupdev subroutine gets a network device suitable for use with the pcap_open_live and the pcap_lookupnet subroutines. If no interface can be found, or none are configured to be up, Null is returned. In the case of multiple network devices attached to the system, the pcap_lookupdev subroutine returns the first one it finds to be up, other than the loopback interface. (Loopback is always ignored.)
*/
static VALUE
rbpcap_s_lookupdev(VALUE self)
{
char *dev = NULL;
char eb[PCAP_ERRBUF_SIZE];
VALUE ret_dev; /* device string to return */
pcap_if_t *alldevs;
pcap_if_t *d;
/* Retrieve the device list from the local machine */
if (pcap_findalldevs(&alldevs,eb) == -1) {
rb_raise(eBindingError,"%s",eb);
}
/* Find the first interface with an address and not loopback */
for(d = alldevs; d != NULL; d= d->next) {
if(d->name && d->addresses && !(d->flags & PCAP_IF_LOOPBACK)) {
dev=d->name;
break;
}
}
if (dev == NULL) {
rb_raise(eBindingError,"%s","No valid interfaces found, Make sure WinPcap is installed.\n");
}
ret_dev = rb_str_new2(dev);
/* We don't need any more the device list. Free it */
pcap_freealldevs(alldevs);
return ret_dev;
}
/*
* Returns the network address and subnet mask for a network device.
*/
static VALUE
rbpcap_s_lookupnet(VALUE self, VALUE dev)
{
bpf_u_int32 net, mask, m;
struct in_addr addr;
char eb[PCAP_ERRBUF_SIZE];
VALUE list;
Check_Type(dev, T_STRING);
if (pcap_lookupnet(StringValuePtr(dev), &net, &mask, eb) == -1) {
rb_raise(rb_eRuntimeError, "%s", eb);
}
addr.s_addr = net;
m = ntohl(mask);
list = rb_ary_new();
rb_ary_push(list, rb_str_new2((char *) inet_ntoa(addr)));
rb_ary_push(list, UINT2NUM(m));
return(list);
}
/*
* Check if PCAP file or device is bound and loaded
*/
static int rbpcap_ready(rbpcap_t *rbp) {
if(! rbp->pd) {
rb_raise(ePCAPRUBError, "a device or pcap file must be opened first");
return 0;
}
return 1;
}
/*
* Automated Garbage Collection for Pcap Class
*/
static void rbpcap_free(rbpcap_t *rbp) {
if (rbp->pd)
pcap_close(rbp->pd);
if (rbp->pdt)
pcap_dump_close(rbp->pdt);
rbp->pd = NULL;
rbp->pdt = NULL;
free(rbp);
}
/*
* Automated Garbage Collection for Packet Class
*/
static void rbpacket_free(rbpacket_t *rbpacket)
{
if(rbpacket->pkt != NULL) {
rbpacket->pkt = NULL;
}
free(rbpacket);
}
/*
* Creates a new Pcap instance and returns the object itself.
*/
static VALUE
rbpcap_new_s(VALUE class)
{
VALUE self;
rbpcap_t *rbp;
// need to make destructor do a pcap_close later
self = Data_Make_Struct(class, rbpcap_t, 0, rbpcap_free, rbp);
rb_obj_call_init(self, 0, 0);
memset(rbp, 0, sizeof(rbpcap_t));
return self;
}
/*
* Creates a new Packet instance and returns the object itself.
*/
static VALUE
rbpacket_new_s(VALUE class)
{
VALUE self;
rbpacket_t *rbpacket;
// need to make destructor do a pcap_close later
self = Data_Make_Struct(class, rbpacket_t, 0, rbpacket_free, rbpacket);
rb_obj_call_init(self, 0, 0);
memset(rbpacket, 0, sizeof(rbpacket_t));
return self;
}
/*
* call-seq:
* setmonitor(true)
*
* Set monitor mode for the capture.
*
* Returns the object itself.
*/
static VALUE
rbpcap_setmonitor(VALUE self, VALUE mode)
{
rbpcap_t *rbp;
int rfmon_mode = 0;
Data_Get_Struct(self, rbpcap_t, rbp);
if (mode == Qtrue) {
rfmon_mode = 1;
} else if (mode == Qfalse) {
rfmon_mode = 0;
} else {
rb_raise(rb_eArgError, "Monitor mode must be a boolean");
}
#if defined(WIN32)
// monitor mode support was disabled in WinPcap 4.0.2
rb_raise(ePCAPRUBError, "set monitor mode not supported in WinPcap");
#else
if (pcap_set_rfmon(rbp->pd, rfmon_mode) == 0) {
return self;
} else {
rb_raise(ePCAPRUBError, "unable to set monitor mode");
}
#endif
}
/*
* call-seq:
* settimeout(1234)
*
* Set timeout for the capture.
*
* Returns the object itself.
*/
static VALUE
rbpcap_settimeout(VALUE self, VALUE timeout)
{
rbpcap_t *rbp;
Data_Get_Struct(self, rbpcap_t, rbp);
if(TYPE(timeout) != T_FIXNUM)
rb_raise(rb_eArgError, "timeout must be a fixnum");
if (pcap_set_timeout(rbp->pd, NUM2INT(timeout)) == 0) {
return self;
} else {
rb_raise(ePCAPRUBError, "unable to set timeout");
}
}
/*
* call-seq:
* listdatalinks()
*
* Get supported datalinks for this interface
*
* Returns an array of supported datalinks.
*/
static VALUE
rbpcap_listdatalinks(VALUE self)
{
rbpcap_t *rbp;
int *links, numlinks;
int i;
Data_Get_Struct(self, rbpcap_t, rbp);
numlinks = pcap_list_datalinks(rbp->pd, &links);
if (numlinks > 0) {
VALUE hash = rb_hash_new();
for (i = 0; i < numlinks; i++) {
const char *name = pcap_datalink_val_to_name(links[i]);
if (name != NULL) {
VALUE namestring = rb_str_new2(name);
rb_hash_aset(hash, INT2NUM(links[i]), namestring);
}
}
pcap_free_datalinks(links);
return hash;
} else {
rb_raise(eLinkTypeError, "unable to get datalinks (%d): %s", numlinks, pcap_geterr(rbp->pd));
}
}
/*
* call-seq:
* setdatalink(1234)
*
* Set datalink type for the capture.
*
* Returns the object itself.
*/
static VALUE
rbpcap_setdatalink(VALUE self, VALUE datalink)
{
rbpcap_t *rbp;
int linktype, errcode;
Data_Get_Struct(self, rbpcap_t, rbp);
if(TYPE(datalink) == T_FIXNUM ) {
linktype = NUM2INT(datalink);
} else if (TYPE(datalink) == T_STRING) {
linktype = pcap_datalink_name_to_val(RSTRING_PTR(datalink));
if (linktype < 0) {
rb_raise(eLinkTypeError, "invalid datalink name: %s", RSTRING_PTR(datalink));
}
} else {
rb_raise(rb_eArgError, "datalink type must be a string or fixnum");
}
errcode = pcap_set_datalink(rbp->pd, linktype);
if (errcode == 0) {
return self;
} else {
rb_raise(eLinkTypeError, "unable to set datalink (%d): %s", errcode, pcap_geterr(rbp->pd));
}
}
/*
* call-seq:
* setsnaplen(true)
*
* Set snap length for the capture.
*
* Returns the object itself.
*/
static VALUE
rbpcap_setsnaplen(VALUE self, VALUE snaplen)
{
rbpcap_t *rbp;
Data_Get_Struct(self, rbpcap_t, rbp);
if(TYPE(snaplen) != T_FIXNUM)
rb_raise(rb_eArgError, "snaplen must be a fixnum");
if (pcap_set_snaplen(rbp->pd, NUM2INT(snaplen)) == 0) {
return self;
} else {
rb_raise(ePCAPRUBError, "unable to set snap length");
}
}
/*
* call-seq:
* setpromisc(true)
*
* Set promiscuous mode for the capture.
*
* Returns the object itself.
*/
static VALUE
rbpcap_setpromisc(VALUE self, VALUE mode)
{
rbpcap_t *rbp;
int promisc_mode = 0;
Data_Get_Struct(self, rbpcap_t, rbp);
if (mode == Qtrue) {
promisc_mode = 1;
} else if (mode == Qfalse) {
promisc_mode = 0;
} else {
rb_raise(rb_eArgError, "Promisc mode must be a boolean");
}
if (pcap_set_promisc(rbp->pd, promisc_mode) == 0) {
return self;
} else {
rb_raise(ePCAPRUBError, "unable to set promiscuous mode");
}
}
/*
* call-seq:
* setfilter(filter)
*
* Provide a valid bpf-filter to apply to the packet capture
*
* # Show me all SYN packets:
* bpf-filter = "tcp[13] & 2 != 0"
* capture.setfilter(bpf-filter)
*
* Examples:
* * "net 10.0.0.0/8"
* * "not tcp and dst host 192.168.1.1"
*
* Returns the object itself.
*/
static VALUE
rbpcap_setfilter(VALUE self, VALUE filter)
{
char eb[PCAP_ERRBUF_SIZE];
rbpcap_t *rbp;
bpf_u_int32 mask = 0, netid = 0;
struct bpf_program bpf;
Data_Get_Struct(self, rbpcap_t, rbp);
if(TYPE(filter) != T_STRING)
rb_raise(eBPFilterError, "filter must be a string");
if(! rbpcap_ready(rbp)) return self;
if(rbp->type == DEAD) {
rb_raise(eBPFilterError, "unable to set bpf filter on OPEN_DEAD");
}
if(rbp->type == LIVE)
if(pcap_lookupnet(rbp->iface, &netid, &mask, eb) < 0) {
netid = 0;
mask = 0;
rb_warn("unable to get IP: %s", eb);
}
if(pcap_compile(rbp->pd, &bpf, RSTRING_PTR(filter), 0, mask) < 0) {
rb_raise(eBPFilterError, "invalid bpf filter: %s", pcap_geterr(rbp->pd));
}
if(pcap_setfilter(rbp->pd, &bpf) < 0) {
pcap_freecode(&bpf);
rb_raise(eBPFilterError, "unable to set bpf filter: %s", pcap_geterr(rbp->pd));
}
pcap_freecode(&bpf);
return self;
}
/*
* call-seq:
* compile(filter)
*
* Raises an exception if "filter" has a syntax error
*
* Returns self if the filter is valid
*/
static VALUE
rbpcap_compile(VALUE self, VALUE filter) {
struct bpf_program bpf;
bpf_u_int32 mask = 0;
rbpcap_t *rbp;
Data_Get_Struct(self, rbpcap_t, rbp);
if(pcap_compile(rbp->pd, &bpf, RSTRING_PTR(filter), 0, mask) < 0) {
rb_raise(eBPFilterError, "invalid bpf filter: %s", pcap_geterr(rbp->pd));
}
pcap_freecode(&bpf);
return self;
}
/*
* Activate the interface
*
* call-seq:
* activate() -> self
*
* Returns the object itself.
*/
static VALUE
rbpcap_activate(VALUE self)
{
rbpcap_t *rbp;
int errcode;
Data_Get_Struct(self, rbpcap_t, rbp);
if ((errcode = pcap_activate(rbp->pd)) == 0) {
return self;
} else {
rb_raise(ePCAPRUBError, "unable to activate interface: %d, %s", errcode, rbp->iface);
}
}
/*
* Close the interface
*
* call-seq:
* activate() -> self
*
* Returns the object itself.
*/
static VALUE
rbpcap_close(VALUE self)
{
rbpcap_t *rbp;
Data_Get_Struct(self, rbpcap_t, rbp);
pcap_close(rbp->pd);
rbp->pd = NULL;
return self;
}
static VALUE
rbpcap_create(VALUE self, VALUE iface)
{
rbpcap_t *rbp;
char eb[PCAP_ERRBUF_SIZE];
Data_Get_Struct(self, rbpcap_t, rbp);
rbp->type = LIVE;
memset(rbp->iface, 0, sizeof(rbp->iface));
strncpy(rbp->iface, RSTRING_PTR(iface), sizeof(rbp->iface) - 1);
if(rbp->pd) {
pcap_close(rbp->pd);
}
rbp->pd = pcap_create(
RSTRING_PTR(iface),
eb
);
if(!rbp->pd)
rb_raise(rb_eRuntimeError, "%s", eb);
return self;
}
/*
*
* call-seq:
* create(iface) -> self
*
* capture = ::Pcap.create(@dev)
*
* Returns the object itself.
*/
static VALUE
rbpcap_create_s(VALUE class, VALUE iface)
{
VALUE iPcap = rb_funcall(rb_cPcap, rb_intern("new"), 0);
return rbpcap_create(iPcap, iface);
}
// transparent method
static VALUE
rbpcap_open_live(VALUE self, VALUE iface,VALUE snaplen,VALUE promisc, VALUE timeout)
{
char eb[PCAP_ERRBUF_SIZE];
rbpcap_t *rbp;
int promisc_value = 0;
if(TYPE(iface) != T_STRING)
rb_raise(rb_eArgError, "interface must be a string");
if(TYPE(snaplen) != T_FIXNUM)
rb_raise(rb_eArgError, "snaplen must be a fixnum");
if(TYPE(timeout) != T_FIXNUM)
rb_raise(rb_eArgError, "timeout must be a fixnum");
switch(promisc) {
case Qtrue:
promisc_value = 1;
break;
case Qfalse:
promisc_value = 0;
break;
default:
rb_raise(ePCAPRUBError, "Promisc Argument not boolean");
}
Data_Get_Struct(self, rbpcap_t, rbp);
rbp->type = LIVE;
memset(rbp->iface, 0, sizeof(rbp->iface));
strncpy(rbp->iface, RSTRING_PTR(iface), sizeof(rbp->iface) - 1);
if(rbp->pd) {
pcap_close(rbp->pd);
}
rbp->pd = pcap_open_live(
RSTRING_PTR(iface),
NUM2INT(snaplen),
promisc_value,
NUM2INT(timeout),
eb
);
if(!rbp->pd)
rb_raise(rb_eRuntimeError, "%s", eb);
return self;
}
/*
*
* call-seq:
* open_live(iface, snaplen, promisc, timeout) -> self
*
* capture = ::Pcap.open_live(@dev, @snaplength, @promiscous_mode, @timeout)
*
* Returns the object itself.
*/
static VALUE
rbpcap_open_live_s(VALUE class, VALUE iface, VALUE snaplen, VALUE promisc, VALUE timeout)
{
VALUE iPcap = rb_funcall(rb_cPcap, rb_intern("new"), 0);
return rbpcap_open_live(iPcap, iface, snaplen, promisc, timeout);
}
// transparent method
static VALUE
rbpcap_open_offline(VALUE self, VALUE filename)
{
char eb[PCAP_ERRBUF_SIZE];
rbpcap_t *rbp;
if(TYPE(filename) != T_STRING)
rb_raise(rb_eArgError, "filename must be a string");
Data_Get_Struct(self, rbpcap_t, rbp);
memset(rbp->iface, 0, sizeof(rbp->iface));
rbp->type = OFFLINE;
rbp->pd = pcap_open_offline(
RSTRING_PTR(filename),
eb
);
if(!rbp->pd)
rb_raise(rb_eRuntimeError, "%s", eb);
return self;
}
/*
*
* call-seq:
* open_offline(filename) -> self
*
* capture = ::Pcap.open_offline(filename)
*
* Returns the object itself.
*/
static VALUE
rbpcap_open_offline_s(VALUE class, VALUE filename)
{
VALUE iPcap = rb_funcall(rb_cPcap, rb_intern("new"), 0);
return rbpcap_open_offline(iPcap, filename);
}
// transparent method
static VALUE
rbpcap_open_dead(VALUE self, VALUE linktype, VALUE snaplen)
{
rbpcap_t *rbp;
if(TYPE(linktype) != T_FIXNUM)
rb_raise(rb_eArgError, "linktype must be a fixnum");
if(TYPE(snaplen) != T_FIXNUM)
rb_raise(rb_eArgError, "snaplen must be a fixnum");
Data_Get_Struct(self, rbpcap_t, rbp);
memset(rbp->iface, 0, sizeof(rbp->iface));
rbp->type = DEAD;
rbp->pd = pcap_open_dead(
NUM2INT(linktype),
NUM2INT(snaplen)
);
return self;
}
/*
*
* call-seq:
* open_dead(linktype, snaplen) -> self
*
* open a fake Pcap for compiling filters or opening a capture for output
*
* ::Pcap.open_dead() is used for creating a pcap structure to use when
* calling the other functions like compiling BPF code.
*
* * linktype specifies the link-layer type
*
* * snaplen specifies the snapshot length
*
* Returns the object itself.
*/
static VALUE
rbpcap_open_dead_s(VALUE class, VALUE linktype, VALUE snaplen)
{
VALUE iPcap = rb_funcall(rb_cPcap, rb_intern("new"), 0);
return rbpcap_open_dead(iPcap, linktype, snaplen);
}
/*
* call-seq:
* dump_open(filename)
*
* dump_open() is called to open a "savefile" for writing
*/
static VALUE
rbpcap_dump_open(VALUE self, VALUE filename)
{
rbpcap_t *rbp;
if(TYPE(filename) != T_STRING)
rb_raise(rb_eArgError, "filename must be a string");
Data_Get_Struct(self, rbpcap_t, rbp);
if(! rbpcap_ready(rbp)) return self;
rbp->pdt = pcap_dump_open(
rbp->pd,
RSTRING_PTR(filename)
);
if(!rbp->pdt)
rb_raise(eDumperError, "Stream could not be initialized or opened.");
return self;
}
/*
* call-seq:
* dump_close()
*
* dump_close() is called to manually close a "savefile"
*/
static VALUE
rbpcap_dump_close(VALUE self)
{
rbpcap_t *rbp;
Data_Get_Struct(self, rbpcap_t, rbp);
if(! rbpcap_ready(rbp)) return self;
if(!rbp->pdt)
rb_raise(eDumperError, "Stream is already closed.");
if (rbp->pdt)
pcap_dump_close(rbp->pdt);
rbp->pdt = NULL;
return self;
}
/*
* call-seq:
* dump(caplen, pktlen, packet)
*
* not sure if this deviates too much from the way the rest of this class works?
*
* Writes packet capture date to a binary file assigned with dump_open().
*
* Returns the object itself.
*/
static VALUE
rbpcap_dump(VALUE self, VALUE caplen, VALUE pktlen, VALUE packet)
{
rbpcap_t *rbp;
struct pcap_pkthdr pcap_hdr;
if(TYPE(packet) != T_STRING)
rb_raise(rb_eArgError, "packet data must be a string");
if(TYPE(caplen) != T_FIXNUM)
rb_raise(rb_eArgError, "caplen must be a fixnum");
if(TYPE(pktlen) != T_FIXNUM)
rb_raise(rb_eArgError, "pktlen must be a fixnum");
Data_Get_Struct(self, rbpcap_t, rbp);
gettimeofday(&pcap_hdr.ts, NULL);
pcap_hdr.caplen = NUM2UINT(caplen);
pcap_hdr.len = NUM2UINT(pktlen);
if(!rbp->pdt) {
rb_raise(rb_eRuntimeError, "pcap_dumper not defined. You must open a dump file first");
}
//capture.next is yeilding an 8Bit ASCII string
// -> return rb_str_new((char *) job.pkt, job.hdr.caplen);
//Call dump such that capture.next{|pk| capture.dump(pk.length, pk.length, pk)}
pcap_dump(
(u_char*)rbp->pdt,
&pcap_hdr,
(unsigned char *)RSTRING_PTR(packet)
);
return self;
}
/*
* call-seq:
* inject(payload)
*
* inject() transmit a raw packet through the network interface
*
* Returns the number of bytes written on success else raise failure.
*/
static VALUE
rbpcap_inject(VALUE self, VALUE payload)
{
rbpcap_t *rbp;
if(TYPE(payload) != T_STRING)
rb_raise(rb_eArgError, "pupayload must be a string");
Data_Get_Struct(self, rbpcap_t, rbp);
if(! rbpcap_ready(rbp)) return self;
#if defined(WIN32)
/* WinPcap does not have a pcap_inject call we use pcap_sendpacket, if it suceedes
* we simply return the amount of packets request to inject, else we fail.
*/
if(pcap_sendpacket(rbp->pd, RSTRING_PTR(payload), RSTRING_LEN(payload)) != 0) {
rb_raise(rb_eRuntimeError, "%s", pcap_geterr(rbp->pd));
}
return INT2NUM(RSTRING_LEN(payload));
#else
return INT2NUM(pcap_inject(rbp->pd, RSTRING_PTR(payload), RSTRING_LEN(payload)));
#endif
}
/*
*
* Packet Job Call back from pcap_dispatch
*
*/
static void rbpcap_handler(rbpcapjob_t *job, struct pcap_pkthdr *hdr, u_char *pkt){
job->pkt = (unsigned char *)pkt;
job->hdr = *hdr;
}
/*
**
* Returns the next packet from the packet capture device.
*
* Returns a string with the packet data.
*
* If the next_data() is unsuccessful, Null is returned.
*/
static VALUE
rbpcap_next_data(VALUE self)
{
rbpcap_t *rbp;
rbpcapjob_t job;
char eb[PCAP_ERRBUF_SIZE];
int ret;
Data_Get_Struct(self, rbpcap_t, rbp);
if(! rbpcap_ready(rbp)) return self;
pcap_setnonblock(rbp->pd, 1, eb);
#ifdef MAKE_TRAP
TRAP_BEG;
#endif
// ret will contain the number of packets captured during the trap (ie one) since this is an iterator.
ret = pcap_dispatch(rbp->pd, 1, (pcap_handler) rbpcap_handler, (u_char *)&job);
#ifdef MAKE_TRAP
TRAP_END;
#endif
if(rbp->type == OFFLINE && ret <= 0)
return Qnil;
if(rbp->type == DEAD && ret <= 0)
return Qnil;
if(ret > 0 && job.hdr.caplen > 0)
return rb_str_new((char *) job.pkt, job.hdr.caplen);
return Qnil;
}
/*
*
* Returns the next packet from the packet capture device.
*
* Returns a string with the packet data.
*
* If the next_packet() is unsuccessful, Null is returned.
*/
static VALUE
rbpcap_next_packet(VALUE self)
{
rbpcap_t *rbp;
rbpcapjob_t job;
char eb[PCAP_ERRBUF_SIZE];
int ret;
rbpacket_t* rbpacket;
Data_Get_Struct(self, rbpcap_t, rbp);
if(! rbpcap_ready(rbp)) return self;
pcap_setnonblock(rbp->pd, 1, eb);
#ifdef MAKE_TRAP
TRAP_BEG;
#endif
ret = pcap_dispatch(rbp->pd, 1, (pcap_handler) rbpcap_handler, (u_char *)&job);
#ifdef MAKE_TRAP
TRAP_END;
#endif
if(rbp->type == OFFLINE && ret <= 0)
return Qnil;
if(rbp->type == DEAD && ret <= 0)
return Qnil;
if(ret > 0 && job.hdr.caplen > 0)
{
rbpacket = ALLOC(rbpacket_t);
rbpacket->hdr = job.hdr;
rbpacket->pkt = (u_char *)job.pkt;
return Data_Wrap_Struct(rb_cPkt, 0, rbpacket_free, rbpacket);
}
return Qnil;
}
/*
* call-seq:
* each_data() { |packet| ... }
*
* Yields each packet from the capture to the passed-in block in turn.
*
*/
static VALUE
rbpcap_each_data(VALUE self)
{
rbpcap_t *rbp;
#if defined(WIN32)
HANDLE fno;
#else
int fno = -1;
#endif
Data_Get_Struct(self, rbpcap_t, rbp);
if(! rbpcap_ready(rbp)) return self;
#if defined(WIN32)
fno = (HANDLE)pcap_getevent(rbp->pd);
#else
fno = pcap_get_selectable_fd(rbp->pd);
#endif
for(;;) {
VALUE packet = rbpcap_next_data(self);
if(packet == Qnil && rbp->type == OFFLINE) break;
if(packet == Qnil && rbp->type == DEAD) break;
#if defined(WIN32)
packet == Qnil ? rbpcap_thread_wait_handle(fno) : rb_yield(packet);
#else
packet == Qnil ? rb_thread_wait_fd(fno) : rb_yield(packet);
#endif
}
return self;
}
/*
* call-seq:
* each_packet() { |packet| ... }
*
* Yields a PCAP::Packet from the capture to the passed-in block in turn.
*
*/
static VALUE
rbpcap_each_packet(VALUE self)
{
rbpcap_t *rbp;
#if defined(WIN32)
HANDLE fno;
#else
int fno = -1;
#endif
Data_Get_Struct(self, rbpcap_t, rbp);
if(! rbpcap_ready(rbp)) return self;
#if defined(WIN32)
fno = (HANDLE)pcap_getevent(rbp->pd);
#else
fno = pcap_get_selectable_fd(rbp->pd);
#endif
for(;;) {
VALUE packet = rbpcap_next_packet(self);
if(packet == Qnil && rbp->type == OFFLINE) break;
if(packet == Qnil && rbp->type == DEAD) break;
#if defined(WIN32)
packet == Qnil ? rbpcap_thread_wait_handle(fno) : rb_yield(packet);
#else
packet == Qnil ? rb_thread_wait_fd(fno) : rb_yield(packet);
#endif
}
return self;
}
/*
* call-seq:
* datalink()
*
* Returns the integer datalink value unless capture
*
* foo.bar unless capture.datalink == Pcap::DLT_EN10MB
*/
static VALUE
rbpcap_datalink(VALUE self)
{
rbpcap_t *rbp;
Data_Get_Struct(self, rbpcap_t, rbp);
if(! rbpcap_ready(rbp)) return self;
return INT2NUM(pcap_datalink(rbp->pd));
}
/*
* call-seq:
* pcap_major_version()
*
* Returns the integer PCAP MAJOR LIBRARY value unless capture
*
*/
static VALUE
rbpcap_major_version(VALUE self)
{
rbpcap_t *rbp;
Data_Get_Struct(self, rbpcap_t, rbp);
if(! rbpcap_ready(rbp)) return self;
return INT2NUM(pcap_major_version(rbp->pd));
}
/*
* call-seq:
* pcap_minor_version()
*
* Returns the integer PCAP MINOR LIBRARY value unless capture
*
*/
static VALUE
rbpcap_minor_version(VALUE self)
{
rbpcap_t *rbp;
Data_Get_Struct(self, rbpcap_t, rbp);
if(! rbpcap_ready(rbp)) return self;
return INT2NUM(pcap_minor_version(rbp->pd));
}
/*
* call-seq:
* snapshot()
*
* Returns the snapshot length, which is the number of bytes to save for each packet captured.
*
*/
static VALUE
rbpcap_snapshot(VALUE self)
{
rbpcap_t *rbp;
Data_Get_Struct(self, rbpcap_t, rbp);
if(! rbpcap_ready(rbp)) return self;
return INT2NUM(pcap_snapshot(rbp->pd));
}
/*
* call-seq:
* stats()
*
* Returns a hash with statistics of the packet capture
*
* - ["recv"] # number of packets received
* - ["drop"] # number of packets dropped
* - ["idrop"] # number of packets dropped by interface
*
*/
static VALUE
rbpcap_stats(VALUE self)
{
rbpcap_t *rbp;
struct pcap_stat stat;
VALUE hash;
Data_Get_Struct(self, rbpcap_t, rbp);
if(! rbpcap_ready(rbp)) return self;
if (pcap_stats(rbp->pd, &stat) == -1)
return Qnil;
hash = rb_hash_new();
rb_hash_aset(hash, rb_str_new2("recv"), UINT2NUM(stat.ps_recv));
rb_hash_aset(hash, rb_str_new2("drop"), UINT2NUM(stat.ps_drop));
rb_hash_aset(hash, rb_str_new2("idrop"), UINT2NUM(stat.ps_ifdrop));
// drops by interface XXX not yet supported under pcap.h 2.4
//#if defined(WIN32)
// rb_hash_aset(hash, rb_str_new2("bs_capt"), UINT2NUM(stat.bs_capt));
//#endif
return hash;
}
/*
*
* Returns the EPOCH integer from the ts.tv_sec record in the PCAP::Packet header
*
*/
static VALUE
rbpacket_time(VALUE self)
{
rbpacket_t* rbpacket;
Data_Get_Struct(self, rbpacket_t, rbpacket);
return INT2NUM(rbpacket->hdr.ts.tv_sec);
}
/*
*
* Returns the tv_usec integer from the ts.tv_usec record in the PCAP::Packet header
* timestamp microseconds
* the microseconds when this packet was captured, as an offset to ts_sec.
* Beware: this value shouldn't reach 1 second (1 000 000), in this case ts_sec must be increased instead!
*
* Ruby Microsecond Handling
* Time.at(946684800.2).usec #=> 200000
* Time.now.usec
*/
static VALUE
rbpacket_microsec(VALUE self)
{
rbpacket_t* rbpacket;
Data_Get_Struct(self, rbpacket_t, rbpacket);
return INT2NUM(rbpacket->hdr.ts.tv_usec);
}
/*
*
* Returns the integer length of packet length field from the in the PCAP::Packet header
*
*/
static VALUE
rbpacket_length(VALUE self)
{
rbpacket_t* rbpacket;
Data_Get_Struct(self, rbpacket_t, rbpacket);
return INT2NUM(rbpacket->hdr.len);
}
/*
*
* Returns the integer length of capture len from the in the PCAP::Packet header
*
*/
static VALUE
rbpacket_caplen(VALUE self)
{
rbpacket_t* rbpacket;
Data_Get_Struct(self, rbpacket_t, rbpacket);
//test incorrect case
if (rbpacket->hdr.caplen > rbpacket->hdr.len)
return INT2NUM(rbpacket->hdr.len);
return INT2NUM(rbpacket->hdr.caplen);
}
/*
*
* Returns the integer PCAP MINOR LIBRARY value unless capture
*
*/
static VALUE
rbpacket_data(VALUE self)
{
rbpacket_t* rbpacket;
Data_Get_Struct(self, rbpacket_t, rbpacket);
if ((rbpacket->pkt == NULL) || (rbpacket->hdr.caplen > rbpacket->hdr.len))
return Qnil;
return rb_str_new((char *) rbpacket->pkt, rbpacket->hdr.caplen);
}
#if defined(WIN32)
static void *
rbpcap_thread_wait_handle_blocking(void *data)
{
VALUE result;
result = (VALUE)WaitForSingleObject(data, 100);
return (void *) result;
}
/*
*
* Waits for the HANDLE returned by pcap_getevent to have data
*
*/
static VALUE
rbpcap_thread_wait_handle(HANDLE fno)
{
VALUE result;
#if MAKE_TRAP
// Ruby 1.8 doesn't support rb_thread_blocking_region
result = rb_thread_polling();
#elif defined(HAVE_RB_THREAD_CALL_WITHOUT_GVL)
result = (VALUE)rb_thread_call_without_gvl(
rbpcap_thread_wait_handle_blocking,
fno, RUBY_UBF_IO, 0);
#else
result = (VALUE)rb_thread_blocking_region(
rbpcap_thread_wait_handle_blocking,
fno, RUBY_UBF_IO, 0);
#endif
return result;
}
#endif
void
Init_pcaprub_c()
{
/*
* Document-class: Pcap
*
* Main class defined by the pcaprub extension.
*/
mPCAP = rb_define_module("PCAPRUB");
rb_cPcap = rb_define_class_under(mPCAP,"Pcap", rb_cObject);
rb_cPkt = rb_define_class_under(mPCAP,"Packet", rb_cObject);
ePCAPRUBError = rb_path2class("PCAPRUB::PCAPRUBError");
eBindingError = rb_path2class("PCAPRUB::BindingError");
eBPFilterError = rb_path2class("PCAPRUB::BPFError");
eDumperError = rb_path2class("PCAPRUB::DumperError");
eLinkTypeError = rb_path2class("PCAPRUB::LinkTypeError");
rb_define_module_function(rb_cPcap, "lookupdev", rbpcap_s_lookupdev, 0);
rb_define_module_function(rb_cPcap, "lookupnet", rbpcap_s_lookupnet, 1);
rb_define_module_function(rb_cPcap, "lib_version", rbpcap_s_lib_version, 0);
rb_define_const(rb_cPcap, "DLT_NULL", INT2NUM(DLT_NULL));
rb_define_const(rb_cPcap, "DLT_EN10MB", INT2NUM(DLT_EN10MB));
rb_define_const(rb_cPcap, "DLT_EN3MB", INT2NUM(DLT_EN3MB));
rb_define_const(rb_cPcap, "DLT_AX25", INT2NUM(DLT_AX25));
rb_define_const(rb_cPcap, "DLT_PRONET", INT2NUM(DLT_PRONET));
rb_define_const(rb_cPcap, "DLT_CHAOS", INT2NUM(DLT_CHAOS));
rb_define_const(rb_cPcap, "DLT_IEEE802", INT2NUM(DLT_IEEE802));
rb_define_const(rb_cPcap, "DLT_ARCNET", INT2NUM(DLT_ARCNET));
rb_define_const(rb_cPcap, "DLT_SLIP", INT2NUM(DLT_SLIP));
rb_define_const(rb_cPcap, "DLT_PPP", INT2NUM(DLT_PPP));
rb_define_const(rb_cPcap, "DLT_FDDI", INT2NUM(DLT_FDDI));
rb_define_const(rb_cPcap, "DLT_ATM_RFC1483", INT2NUM(DLT_ATM_RFC1483));
rb_define_const(rb_cPcap, "DLT_RAW", INT2NUM(DLT_RAW));
rb_define_const(rb_cPcap, "DLT_SLIP_BSDOS", INT2NUM(DLT_SLIP_BSDOS));
rb_define_const(rb_cPcap, "DLT_PPP_BSDOS", INT2NUM(DLT_PPP_BSDOS));
rb_define_const(rb_cPcap, "DLT_IEEE802_11", INT2NUM(DLT_IEEE802_11));
rb_define_const(rb_cPcap, "DLT_IEEE802_11_RADIO", INT2NUM(DLT_IEEE802_11_RADIO));
#ifdef DLT_IEEE802_11_RADIO_AVS
rb_define_const(rb_cPcap, "DLT_IEEE802_11_RADIO_AVS", INT2NUM(DLT_IEEE802_11_RADIO_AVS));
#endif /* DLT_IEEE802_11_RADIO_AVS */
#ifdef DLT_LINUX_SLL
rb_define_const(rb_cPcap, "DLT_LINUX_SLL", INT2NUM(DLT_LINUX_SLL));
#endif /* DLT_LINUX_SLL */
#ifdef DLT_PRISM_HEADER
rb_define_const(rb_cPcap, "DLT_PRISM_HEADER", INT2NUM(DLT_PRISM_HEADER));
#endif /* DLT_PRISM_HEADER */
#ifdef DLT_AIRONET_HEADER
rb_define_const(rb_cPcap, "DLT_AIRONET_HEADER", INT2NUM(DLT_AIRONET_HEADER));
#endif /* DLT_AIRONET_HEADER */
#ifdef DLT_BLUETOOTH_HCI_H4
rb_define_const(rb_cPcap, "DLT_BLUETOOTH_HCI_H4", INT2NUM(DLT_BLUETOOTH_HCI_H4));
#endif
#ifdef DLT_BLUETOOTH_HCI_H4_WITH_PHDR
rb_define_const(rb_cPcap, "DLT_BLUETOOTH_HCI_H4_WITH_PHDR", INT2NUM(DLT_BLUETOOTH_HCI_H4_WITH_PHDR));
#endif
#ifdef DLT_IPFILTER
rb_define_const(rb_cPcap, "DLT_IPFILTER", INT2NUM(DLT_IPFILTER));
#endif
#ifdef DLT_LOOP
rb_define_const(rb_cPcap, "DLT_LOOP", INT2NUM(DLT_LOOP));
#endif
#ifdef DLT_USB
rb_define_const(rb_cPcap, "DLT_USB", INT2NUM(DLT_USB));
#endif
#ifdef DLT_USB_LINUX
rb_define_const(rb_cPcap, "DLT_USB_LINUX", INT2NUM(DLT_USB_LINUX));
#endif
#ifdef DLT_DOCSIS
rb_define_const(rb_cPcap, "DLT_DOCSIS", INT2NUM(DLT_DOCSIS));
#endif
/* Pcap Error Codes
* Error codes for the pcap API.
* These will all be negative, so you can check for the success or
* failure of a call that returns these codes by checking for a
* negative value.
*/
rb_define_const(rb_cPcap, "PCAP_ERROR", INT2NUM(PCAP_ERROR)); /* generic error code */
rb_define_const(rb_cPcap, "PCAP_ERROR_BREAK", INT2NUM(PCAP_ERROR_BREAK)); /* loop terminated by pcap_breakloop */
rb_define_const(rb_cPcap, "PCAP_ERROR_NOT_ACTIVATED", INT2NUM(PCAP_ERROR_NOT_ACTIVATED)); /* the capture needs to be activated */
rb_define_const(rb_cPcap, "PCAP_ERROR_ACTIVATED", INT2NUM(PCAP_ERROR_ACTIVATED)); /* the operation can't be performed on already activated captures */
rb_define_const(rb_cPcap, "PCAP_ERROR_NO_SUCH_DEVICE", INT2NUM(PCAP_ERROR_NO_SUCH_DEVICE)); /* no such device exists */
rb_define_const(rb_cPcap, "PCAP_ERROR_RFMON_NOTSUP", INT2NUM(PCAP_ERROR_RFMON_NOTSUP)); /* this device doesn't support rfmon (monitor) mode */
rb_define_const(rb_cPcap, "PCAP_ERROR_NOT_RFMON", INT2NUM(PCAP_ERROR_NOT_RFMON)); /* operation supported only in monitor mode */
rb_define_const(rb_cPcap, "PCAP_ERROR_PERM_DENIED", INT2NUM(PCAP_ERROR_PERM_DENIED)); /* no permission to open the device */
rb_define_const(rb_cPcap, "PCAP_ERROR_IFACE_NOT_UP", INT2NUM(PCAP_ERROR_IFACE_NOT_UP)); /* interface isn't up */
/*
* Warning codes for the pcap API.
* These will all be positive and non-zero, so they won't look like
* errors.
*/
rb_define_const(rb_cPcap, "PCAP_WARNING", INT2NUM(PCAP_WARNING)); /* generic warning code */
rb_define_const(rb_cPcap, "PCAP_WARNING_PROMISC_NOTSUP", INT2NUM(PCAP_WARNING_PROMISC_NOTSUP)); /* this device doesn't support promiscuous mode */
/*
* Value to pass to pcap_compile() as the netmask if you don't know what
* the netmask is.
*/
rb_define_const(rb_cPcap, "PCAP_NETMASK_UNKNOWN", INT2NUM(PCAP_NETMASK_UNKNOWN));
rb_define_singleton_method(rb_cPcap, "new", rbpcap_new_s, 0);
rb_define_singleton_method(rb_cPcap, "create", rbpcap_create_s, 1);
rb_define_singleton_method(rb_cPcap, "open_live", rbpcap_open_live_s, 4);
rb_define_singleton_method(rb_cPcap, "open_offline", rbpcap_open_offline_s, 1);
rb_define_singleton_method(rb_cPcap, "open_dead", rbpcap_open_dead_s, 2);
rb_define_method(rb_cPcap, "dump_open", rbpcap_dump_open, 1);
rb_define_method(rb_cPcap, "dump_close", rbpcap_dump_close, 0);
rb_define_method(rb_cPcap, "dump", rbpcap_dump, 3);
rb_define_method(rb_cPcap, "each_data", rbpcap_each_data, 0);
rb_define_method(rb_cPcap, "next_data", rbpcap_next_data, 0);
rb_define_method(rb_cPcap, "each_packet", rbpcap_each_packet, 0);
rb_define_method(rb_cPcap, "next_packet", rbpcap_next_packet, 0);
/*
* Document-method: each
* Alias of each_data
*/
rb_define_method(rb_cPcap, "each", rbpcap_each_data, 0);
/*
* Document-method: next
* Alias of next_data
*/
rb_define_method(rb_cPcap, "next", rbpcap_next_data, 0);
rb_define_method(rb_cPcap, "setfilter", rbpcap_setfilter, 1);
rb_define_method(rb_cPcap, "compile", rbpcap_compile, 1);
rb_define_method(rb_cPcap, "setmonitor", rbpcap_setmonitor, 1);
rb_define_method(rb_cPcap, "setsnaplen", rbpcap_setsnaplen, 1);
rb_define_method(rb_cPcap, "settimeout", rbpcap_settimeout, 1);
rb_define_method(rb_cPcap, "setpromisc", rbpcap_setpromisc, 1);
rb_define_method(rb_cPcap, "setdatalink", rbpcap_setdatalink, 1);
rb_define_method(rb_cPcap, "listdatalinks", rbpcap_listdatalinks, 0);
rb_define_method(rb_cPcap, "activate", rbpcap_activate, 0);
rb_define_method(rb_cPcap, "inject", rbpcap_inject, 1);
rb_define_method(rb_cPcap, "datalink", rbpcap_datalink, 0);
rb_define_method(rb_cPcap, "pcap_major_version", rbpcap_major_version, 0);
rb_define_method(rb_cPcap, "pcap_minor_version", rbpcap_minor_version, 0);
rb_define_method(rb_cPcap, "snapshot", rbpcap_snapshot, 0);
rb_define_method(rb_cPcap, "close", rbpcap_close, 0);
/*
* Document-method: snaplen
* Alias of snapshot
*/
rb_define_method(rb_cPcap, "snaplen", rbpcap_snapshot, 0);
rb_define_method(rb_cPcap, "stats", rbpcap_stats, 0);
rb_define_singleton_method(rb_cPkt, "new", rbpacket_new_s, 0);
rb_define_method(rb_cPkt, "time", rbpacket_time, 0);
rb_define_method(rb_cPkt, "microsec", rbpacket_microsec, 0);
rb_define_method(rb_cPkt, "length", rbpacket_length, 0);
rb_define_method(rb_cPkt, "caplen", rbpacket_caplen, 0);
rb_define_method(rb_cPkt, "data", rbpacket_data, 0);
/*
* Document-method: to_s
* Alias of data
*/
rb_define_method(rb_cPkt, "to_s", rbpacket_data, 0);
}
pcaprub-0.13.3/ext/pcaprub_c/extconf.rb 0000644 0000041 0000041 00000006470 14666442051 020032 0 ustar www-data www-data require 'mkmf'
extension_name = 'pcaprub_c'
puts "\n[*] Running checks for #{extension_name} code..."
puts("platform is #{RUBY_PLATFORM}")
default_npcap_sdk = 'C:/npcap-sdk'
default_winpcap_sdk = 'C:/WpdPack'
# Default to npcap if it exists, otherwise fallback to winpcap
default_pcap_sdk = File.directory?(default_npcap_sdk) ? default_npcap_sdk : default_winpcap_sdk
if /i386-mingw32/ =~ RUBY_PLATFORM || /x64-mingw32/ =~ RUBY_PLATFORM || /x64-mingw-ucrt/ =~ RUBY_PLATFORM
unless have_library("ws2_32" ) and
have_library("iphlpapi") and
have_header("windows.h") and
have_header("winsock2.h") and
have_header("iphlpapi.h")
puts "\nNot all dependencies are satisfied for #{RUBY_PLATFORM} platform requirements"
exit
end
pcap_dir = with_config("pcap-dir", default_pcap_sdk)
pcap_includedir = with_config("pcap-includedir", pcap_dir + "/include")
pcap_libdir = with_config("pcap-libdir", pcap_dir + "/lib")
if /x64-mingw32/ =~ RUBY_PLATFORM || /x64-mingw-ucrt/ =~ RUBY_PLATFORM
pcap_libdir += "/x64"
end
$CFLAGS = "-DWIN32 -I#{pcap_includedir}"
$CFLAGS += " -g" if with_config("debug")
$LDFLAGS = "-L#{pcap_libdir}"
$LDFLAGS += " -g" if with_config("debug")
have_header("ruby/thread.h")
if have_header(pcap_includedir + "/Win32-Extensions.h", pcap_includedir + "/pcap.h")
append_cflags("-DHAVE_WIN32_EXTENSIONS_H")
end
have_func("rb_thread_blocking_region") # Pre ruby 2.2
have_func("rb_thread_call_without_gvl") # Post ruby 2.2
have_library("wpcap", "pcap_open_live")
have_library("wpcap", "pcap_setnonblock")
elsif /i386-mswin32/ =~ RUBY_PLATFORM || /x64-mswin32/ =~ RUBY_PLATFORM
pcap_dir = with_config("pcap-dir", default_pcap_sdk)
pcap_includedir = with_config("pcap-includedir", pcap_dir + "\\include")
pcap_libdir = with_config("pcap-libdir", pcap_dir + "\\lib")
if /x64-mingw32/ =~ RUBY_PLATFORM
pcap_libdir += "\\x64"
end
$CFLAGS = "-DWIN32 -I#{pcap_includedir}"
$CFLAGS += " -g" if with_config("debug")
$LDFLAGS = "/link /LIBPATH:#{pcap_libdir}"
$LDFLAGS += " -g" if with_config("debug")
have_header("ruby/thread.h")
if have_header(pcap_includedir + "/Win32-Extensions.h", pcap_includedir + "/pcap.h")
append_cflags("-DHAVE_WIN32_EXTENSIONS_H")
end
have_func("rb_thread_blocking_region") # Pre ruby 2.2
have_func("rb_thread_call_without_gvl") # Post ruby 2.2
have_library("wpcap", "pcap_open_live")
have_library("wpcap", "pcap_setnonblock")
else
libdir = RbConfig::CONFIG['libdir']
includedir = RbConfig::CONFIG['includedir']
header_dirs = [
# macports
'/opt/local/include',
# source installations
'/usr/local/include',
# ruby install locations
includedir,
# finally fall back to usr
'/usr/include'
]
lib_dirs = [
# macports
'/opt/local/lib',
# source installations
'/usr/local/lib',
# ruby install locations
libdir,
# usr
'/usr/lib'
]
dir_config("pcap", header_dirs, lib_dirs)
have_header("ruby/thread.h")
have_func("rb_thread_blocking_region") # Pre ruby 2.2
have_func("rb_thread_call_without_gvl") # Post ruby 2.2
have_library("pcap", "pcap_open_live", ["pcap.h"])
have_library("pcap", "pcap_setnonblock", ["pcap.h"])
$CFLAGS = "-g" if with_config("debug")
$LDFLAGS = "-g" if with_config("debug")
end
create_makefile(extension_name)
pcaprub-0.13.3/examples/ 0000755 0000041 0000041 00000000000 14666442051 015110 5 ustar www-data www-data pcaprub-0.13.3/examples/telnet-raw.pcap 0000644 0000041 0000041 00000057431 14666442051 020051 0 ustar www-data www-data ò X:G8+ J J ; E <@ @ So }x]@
% X:G8 J J ; E