CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/postgres/binary_reader.rb
Views: 1904
1
# -*- coding: binary -*-
2
require 'postgres_msf'
3
require 'postgres/byteorder'
4
5
# Namespace for Metasploit branch.
6
module Msf
7
module Db
8
9
# This mixin solely depends on method read(n), which must be defined
10
# in the class/module where you mixin this module.
11
module BinaryReaderMixin
12
13
# == 8 bit
14
15
# no byteorder for 8 bit!
16
17
def read_word8
18
ru(1, 'C')
19
end
20
21
def read_int8
22
ru(1, 'c')
23
end
24
25
alias read_byte read_word8
26
27
# == 16 bit
28
29
# === Unsigned
30
31
def read_word16_native
32
ru(2, 'S')
33
end
34
35
def read_word16_little
36
ru(2, 'v')
37
end
38
39
def read_word16_big
40
ru(2, 'n')
41
end
42
43
# === Signed
44
45
def read_int16_native
46
ru(2, 's')
47
end
48
49
def read_int16_little
50
# swap bytes if native=big (but we want little)
51
ru_swap(2, 's', ByteOrder::Big)
52
end
53
54
def read_int16_big
55
# swap bytes if native=little (but we want big)
56
ru_swap(2, 's', ByteOrder::Little)
57
end
58
59
# == 32 bit
60
61
# === Unsigned
62
63
def read_word32_native
64
ru(4, 'L')
65
end
66
67
def read_word32_little
68
ru(4, 'V')
69
end
70
71
def read_word32_big
72
ru(4, 'N')
73
end
74
75
# === Signed
76
77
def read_int32_native
78
ru(4, 'l')
79
end
80
81
def read_int32_little
82
# swap bytes if native=big (but we want little)
83
ru_swap(4, 'l', ByteOrder::Big)
84
end
85
86
def read_int32_big
87
# swap bytes if native=little (but we want big)
88
ru_swap(4, 'l', ByteOrder::Little)
89
end
90
91
# == Aliases
92
93
alias read_uint8 read_word8
94
95
# add some short-cut functions
96
%w(word16 int16 word32 int32).each do |typ|
97
alias_method "read_#{typ}_network", "read_#{typ}_big"
98
end
99
100
{:word16 => :uint16, :word32 => :uint32}.each do |old, new|
101
['_native', '_little', '_big', '_network'].each do |bo|
102
alias_method "read_#{new}#{bo}", "read_#{old}#{bo}"
103
end
104
end
105
106
# read exactly n characters, otherwise raise an exception.
107
def readn(n)
108
str = read(n)
109
raise "couldn't read #{n} characters" if str.nil? or str.size != n
110
str
111
end
112
113
private
114
115
# shortcut method for readn+unpack
116
def ru(size, template)
117
readn(size).unpack(template).first
118
end
119
120
# same as method +ru+, but swap bytes if native byteorder == _byteorder_
121
def ru_swap(size, template, byteorder)
122
str = readn(size)
123
str.reverse! if ByteOrder.byteorder == byteorder
124
str.unpack(template).first
125
end
126
end
127
128
end
129
end
130
131