CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/postgres/buffer.rb
Views: 11766
1
# -*- coding: binary -*-
2
require 'postgres_msf'
3
require 'postgres/binary_writer'
4
require 'postgres/binary_reader'
5
6
# Namespace for Metasploit branch.
7
module Msf
8
module Db
9
10
# Fixed size buffer.
11
class Buffer
12
13
class Error < RuntimeError; end
14
class EOF < Error; end
15
16
def self.from_string(str)
17
new(str)
18
end
19
20
def self.of_size(size)
21
raise ArgumentError if size < 0
22
new('#' * size)
23
end
24
25
def initialize(content)
26
@size = content.size
27
@content = content
28
@position = 0
29
end
30
31
def size
32
@size
33
end
34
35
def position
36
@position
37
end
38
39
def peek
40
@content[@position]
41
end
42
43
def position=(new_pos)
44
raise ArgumentError if new_pos < 0 or new_pos > @size
45
@position = new_pos
46
end
47
48
def at_end?
49
@position == @size
50
end
51
52
def content
53
@content
54
end
55
56
def read(n)
57
raise EOF, 'cannot read beyond the end of buffer' if @position + n > @size
58
str = @content[@position, n]
59
@position += n
60
str
61
end
62
63
def write(str)
64
sz = str.size
65
raise EOF, 'cannot write beyond the end of buffer' if @position + sz > @size
66
@content[@position, sz] = str
67
@position += sz
68
self
69
end
70
71
def copy_from_stream(stream, n)
72
raise ArgumentError if n < 0
73
while n > 0
74
str = stream.read(n)
75
write(str)
76
n -= str.size
77
end
78
raise if n < 0
79
end
80
81
NUL = "\000"
82
83
def write_cstring(cstr)
84
raise ArgumentError, "Invalid Ruby/cstring" if cstr.include?(NUL)
85
write(cstr)
86
write(NUL)
87
end
88
89
# returns a Ruby string without the trailing NUL character
90
def read_cstring
91
nul_pos = @content.index(NUL, @position)
92
raise Error, "no cstring found!" unless nul_pos
93
94
sz = nul_pos - @position
95
str = @content[@position, sz]
96
@position += sz + 1
97
return str
98
end
99
100
# read till the end of the buffer
101
def read_rest
102
read(self.size-@position)
103
end
104
105
include BinaryWriterMixin
106
include BinaryReaderMixin
107
end
108
109
end
110
end
111
112