litebackup 1.3.0-aarch64-linux-gnu

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Litebackup
6
+ # Verifying Litebackup's signed package metadata, as
7
+ # https://litebackup.com/pkg/metadata serves it. The release is always read
8
+ # from its signed document, never from the unsigned listing. Needs Ruby's
9
+ # openssl, which is loaded on first use.
10
+ module Release
11
+ # Litebackup's Ed25519 release keys by key ID, base64url without padding,
12
+ # as the litebackup command checks them.
13
+ RELEASE_KEYS = {
14
+ "01a1ead6-4b94-79ca-81f4-3a67c112bc0b" => "t3C_3l71PimyhkPZOzJ_Xi4dOuHJ1CmSdDZ8lTm0vNI"
15
+ }.freeze
16
+ COMMAND_PACKAGE = "cli"
17
+ STABLE_CHANNEL = "stable"
18
+ SIGNATURE_CONTEXT = "clor-apps-v1\0"
19
+ SIGNATURE_SEPARATOR = "\0"
20
+ # The DER prefix of an Ed25519 public key's SubjectPublicKeyInfo, before its 32 bytes.
21
+ ED25519_PUBLIC_KEY_PREFIX = ["302a300506032b6570032100"].pack("H*").freeze
22
+
23
+ # A release whose signature does not match Litebackup's release keys.
24
+ class SignatureError < StandardError
25
+ def initialize(message = "the release signature does not match Litebackup's release keys")
26
+ super
27
+ end
28
+ end
29
+
30
+ # A package or release the metadata does not list.
31
+ class NotListed < StandardError; end
32
+
33
+ # One published file of a release.
34
+ ReleaseFile = Data.define(:name, :filename, :url, :sha256, :size, :os, :architecture)
35
+
36
+ # A package release read from its verified signed document.
37
+ PackageRelease = Data.define(:version, :channels, :files) do
38
+ def file(name)
39
+ files.find { |candidate| candidate.name == name } ||
40
+ raise(NotListed, "release #{version} has no file #{name}")
41
+ end
42
+ end
43
+
44
+ module_function
45
+
46
+ def base64url(text)
47
+ # base64 left Ruby's default gems in 3.4, so the gem decodes it with pack.
48
+ (text.tr("-_", "+/") + ("=" * (-text.length % 4))).unpack1("m0")
49
+ end
50
+
51
+ # The signed document, decoded, once its signature matches one of keys.
52
+ def verify(signed, keys)
53
+ require "openssl"
54
+ raise SignatureError unless signed.is_a?(Hash) && keys.key?(signed["key_id"])
55
+
56
+ begin
57
+ key = OpenSSL::PKey.read(ED25519_PUBLIC_KEY_PREFIX + base64url(keys.fetch(signed["key_id"])))
58
+ document = base64url(signed.fetch("document"))
59
+ message = SIGNATURE_CONTEXT.b + signed["key_id"].b + SIGNATURE_SEPARATOR.b + document.b
60
+ raise SignatureError unless key.verify(nil, base64url(signed.fetch("signature")), message)
61
+
62
+ decoded = JSON.parse(document)
63
+ rescue OpenSSL::PKey::PKeyError, ArgumentError, KeyError, TypeError, JSON::ParserError
64
+ raise SignatureError
65
+ end
66
+ raise SignatureError unless decoded.is_a?(Hash)
67
+
68
+ decoded
69
+ end
70
+
71
+ # Reads package metadata and returns the selected release from its signed
72
+ # document: the release with version, or else the newest on channel.
73
+ # Raises SignatureError when the signature does not verify or the signed
74
+ # version is not the listed one, and NotListed for a missing package or release.
75
+ def find_release(metadata, package: COMMAND_PACKAGE, version: nil, channel: STABLE_CHANNEL, keys: RELEASE_KEYS)
76
+ listing = metadata.is_a?(Hash) ? metadata : JSON.parse(metadata)
77
+ listed = Array(listing["packages"]).find { |candidate| candidate["slug"] == package }
78
+ raise NotListed, "no package #{package}" if listed.nil?
79
+
80
+ candidate = Array(listed["releases"]).find do |release|
81
+ version.nil? ? Array(release["channels"]).include?(channel) : release["version"] == version
82
+ end
83
+ if candidate.nil?
84
+ raise NotListed, "package #{package} has no release #{version.nil? ? "on #{channel}" : version}"
85
+ end
86
+
87
+ document = verify(candidate["signature"], keys)
88
+ raise SignatureError if document["version"] != candidate["version"]
89
+
90
+ files = Array(document["artifacts"]).map do |artifact|
91
+ ReleaseFile.new(name: artifact.fetch("name"), filename: artifact.fetch("filename"), url: artifact.fetch("url"),
92
+ sha256: artifact.fetch("sha256"), size: artifact.fetch("size"),
93
+ os: artifact.fetch("os", ""), architecture: artifact.fetch("architecture", ""))
94
+ end
95
+ PackageRelease.new(version: document.fetch("version"), channels: Array(candidate["channels"]), files: files)
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,352 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+
5
+ module Litebackup
6
+ # HTTP/1.1 over the daemon's unix socket, with a small keep-alive pool.
7
+ #
8
+ # Net::HTTP times each read on its own, so a daemon that trickles an answer
9
+ # could keep a call past its deadline; this reads with one monotonic
10
+ # deadline for the whole call, headers and every chunk, and none when the
11
+ # call has no timeout. One request uses a connection at a time. A GET that
12
+ # fails on a reused connection before any answer arrives is sent once more,
13
+ # on a new connection; nothing else is ever sent twice, and there is no
14
+ # proxy lookup.
15
+ class Transport
16
+ POOL_SIZE = 4
17
+ READ_SIZE = 65_536
18
+ # Limits the status line and headers of one answer.
19
+ HEADER_LIMIT = 64 << 10
20
+
21
+ # A whole answer read from the socket.
22
+ Answer = Data.define(:status, :client_version, :body)
23
+
24
+ # The call's deadline passed before the daemon answered.
25
+ class DeadlinePassed < StandardError; end
26
+
27
+ # The daemon closed the connection, or broke HTTP, before a whole answer.
28
+ class ConnectionBroken < StandardError; end
29
+
30
+ # One connection and the bytes read past the last answer.
31
+ class Connection
32
+ attr_reader :socket
33
+ attr_accessor :buffer
34
+
35
+ def initialize(socket)
36
+ @socket = socket
37
+ @buffer = +""
38
+ end
39
+
40
+ # An idle connection the daemon closed reads as ready.
41
+ def dropped?
42
+ !socket.wait_readable(0).nil?
43
+ rescue IOError, SystemCallError
44
+ true
45
+ end
46
+
47
+ def close
48
+ socket.close
49
+ rescue IOError, SystemCallError
50
+ nil
51
+ end
52
+ end
53
+
54
+ attr_reader :socket_path
55
+
56
+ def initialize(socket_path)
57
+ @socket_path = socket_path
58
+ @lock = Mutex.new
59
+ @idle = []
60
+ @active = []
61
+ @closed = false
62
+ @owner_pid = Process.pid
63
+ end
64
+
65
+ def closed?
66
+ @closed
67
+ end
68
+
69
+ # Sends one request and reads its whole answer. deadline_seconds bounds
70
+ # the whole call; nil waits as long as the daemon takes.
71
+ def request(http_method, target, body, deadline_seconds)
72
+ deadline = deadline_seconds.nil? ? nil : monotonic + deadline_seconds
73
+ retried = false
74
+ loop do
75
+ connection, reused = lend_connection(fresh: retried)
76
+ answer_started = false
77
+ reusable = false
78
+ begin
79
+ answer, reusable = exchange(connection, reused, http_method, target, body, deadline) { answer_started = true }
80
+ return answer
81
+ rescue DeadlinePassed
82
+ raise closed_error if @closed
83
+
84
+ raise Error.new(
85
+ ErrorCode::TIMEOUT,
86
+ "the daemon did not answer within the call's timeout; it may still finish the operation"
87
+ )
88
+ rescue ConnectionBroken, IOError, SystemCallError => e
89
+ raise closed_error if @closed
90
+
91
+ if reused && !retried && http_method == "GET" && !answer_started
92
+ retried = true
93
+ next
94
+ end
95
+ raise Error.new(ErrorCode::CONNECTION_FAILED, e.message.empty? ? e.class.name : e.message)
96
+ ensure
97
+ # Every way out, a killed thread's included, gives the connection
98
+ # back: to the idle pool only after a whole, framed answer.
99
+ return_connection(connection, reusable)
100
+ end
101
+ end
102
+ end
103
+
104
+ # Closes idle connections and ends the calls that are waiting. In a
105
+ # forked child it only closes the child's copies of the parent's
106
+ # connections: shutting them down would end the parent's calls.
107
+ def close
108
+ idle, active = @lock.synchronize do
109
+ @closed = true
110
+ [@idle.slice!(0..), @active.slice!(0..)]
111
+ end
112
+ idle.each(&:close)
113
+ unless Process.pid == @owner_pid
114
+ active.each(&:close)
115
+ return nil
116
+ end
117
+
118
+ active.each do |connection|
119
+ connection.socket.shutdown(Socket::SHUT_RDWR)
120
+ rescue IOError, SystemCallError
121
+ nil
122
+ end
123
+ end
124
+
125
+ private
126
+
127
+ def closed_error
128
+ Error.new(ErrorCode::CLOSED, "the client is closed")
129
+ end
130
+
131
+ def monotonic
132
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
133
+ end
134
+
135
+ # A pooled idle connection, or a new one registered before it connects,
136
+ # so close sees it; with fresh, always a new one. A forked child drops the
137
+ # parent's idle connections without shutting them down.
138
+ def lend_connection(fresh:)
139
+ @lock.synchronize do
140
+ raise closed_error if @closed
141
+
142
+ if Process.pid != @owner_pid
143
+ @idle.each(&:close)
144
+ @idle.clear
145
+ @active.clear
146
+ @owner_pid = Process.pid
147
+ end
148
+ until fresh || @idle.empty?
149
+ connection = @idle.pop
150
+ if connection.dropped?
151
+ connection.close
152
+ next
153
+ end
154
+ @active << connection
155
+ return [connection, true]
156
+ end
157
+ connection = Connection.new(Socket.new(Socket::AF_UNIX, Socket::SOCK_STREAM))
158
+ @active << connection
159
+ [connection, false]
160
+ end
161
+ end
162
+
163
+ def return_connection(connection, reusable)
164
+ @lock.synchronize do
165
+ @active.delete(connection)
166
+ if reusable && !@closed && @idle.length < POOL_SIZE && Process.pid == @owner_pid
167
+ @idle << connection
168
+ return
169
+ end
170
+ end
171
+ connection.close
172
+ end
173
+
174
+ def remaining(deadline)
175
+ return nil if deadline.nil?
176
+
177
+ left = deadline - monotonic
178
+ raise DeadlinePassed, "the call's deadline passed" if left <= 0
179
+
180
+ left
181
+ end
182
+
183
+ def wait(socket, direction, deadline)
184
+ readable = direction == :read ? [socket] : nil
185
+ writable = direction == :write ? [socket] : nil
186
+ raise DeadlinePassed, "the call's deadline passed" if IO.select(readable, writable, nil, remaining(deadline)).nil?
187
+ end
188
+
189
+ def connect(socket, deadline)
190
+ address = Socket.pack_sockaddr_un(socket_path)
191
+ begin
192
+ socket.connect_nonblock(address)
193
+ rescue IO::WaitWritable
194
+ wait(socket, :write, deadline)
195
+ begin
196
+ socket.connect_nonblock(address)
197
+ rescue Errno::EISCONN
198
+ nil
199
+ end
200
+ end
201
+ raise closed_error if @closed
202
+ end
203
+
204
+ def request_bytes(http_method, target, body)
205
+ lines = ["#{http_method} #{target} HTTP/1.1", "Host: litebackup", "#{Wire::SDK_VERSION_HEADER}: #{Wire::SDK_VERSION_VALUE}"]
206
+ lines += ["Content-Type: application/json", "Content-Length: #{body.bytesize}"] unless body.nil?
207
+ head = "#{lines.join("\r\n")}\r\n\r\n"
208
+ body.nil? ? head : head.b + body.b
209
+ end
210
+
211
+ def write_all(socket, bytes, deadline)
212
+ until bytes.empty?
213
+ remaining(deadline)
214
+ written = socket.write_nonblock(bytes, exception: false)
215
+ if written == :wait_writable
216
+ wait(socket, :write, deadline)
217
+ next
218
+ end
219
+ bytes = bytes.byteslice(written..)
220
+ end
221
+ end
222
+
223
+ # Reads more bytes into the connection's buffer; raises ConnectionBroken at the end of the stream.
224
+ def fill(connection, deadline, started)
225
+ loop do
226
+ # Checked before every read, so an answer that keeps arriving still
227
+ # ends at the deadline.
228
+ remaining(deadline)
229
+ chunk = connection.socket.read_nonblock(READ_SIZE, exception: false)
230
+ case chunk
231
+ when :wait_readable then wait(connection.socket, :read, deadline)
232
+ when nil then raise ConnectionBroken, "the daemon closed the connection before answering"
233
+ else
234
+ started.call
235
+ connection.buffer << chunk
236
+ return
237
+ end
238
+ end
239
+ end
240
+
241
+ def read_line(connection, deadline, started)
242
+ loop do
243
+ line_end = connection.buffer.index("\r\n")
244
+ unless line_end.nil?
245
+ line = connection.buffer.byteslice(0, line_end)
246
+ connection.buffer = connection.buffer.byteslice((line_end + 2)..)
247
+ return line
248
+ end
249
+ if connection.buffer.bytesize > HEADER_LIMIT
250
+ raise ConnectionBroken,
251
+ "the daemon's answer has a header line that is too long"
252
+ end
253
+
254
+ fill(connection, deadline, started)
255
+ end
256
+ end
257
+
258
+ def read_bytes(connection, count, deadline, started)
259
+ fill(connection, deadline, started) while connection.buffer.bytesize < count
260
+ bytes = connection.buffer.byteslice(0, count)
261
+ connection.buffer = connection.buffer.byteslice(count..)
262
+ bytes
263
+ end
264
+
265
+ def exchange(connection, reused, http_method, target, body, deadline, &started)
266
+ connection.buffer = +"".b
267
+ remaining(deadline)
268
+ connect(connection.socket, deadline) unless reused
269
+ write_all(connection.socket, request_bytes(http_method, target, body), deadline)
270
+ loop do
271
+ status, headers, version = read_head(connection, deadline, started)
272
+ # An informational answer, such as 100 Continue, precedes the real one.
273
+ next if status.between?(100, 199)
274
+
275
+ answer_body, framed = read_body(connection, headers, deadline, started)
276
+ reusable = framed && version == "HTTP/1.1" && headers["connection"].to_s.downcase != "close"
277
+ return [
278
+ Answer.new(status: status, client_version: headers[Wire::CLIENT_VERSION_HEADER].to_s,
279
+ body: answer_body), reusable
280
+ ]
281
+ end
282
+ end
283
+
284
+ def read_head(connection, deadline, started)
285
+ status_line = read_line(connection, deadline, started)
286
+ match = %r{\A(HTTP/1\.[01]) (\d{3})}.match(status_line)
287
+ raise ConnectionBroken, "the daemon answered with #{status_line[0, 40].inspect}, not HTTP" if match.nil?
288
+
289
+ headers = {}
290
+ size = status_line.bytesize
291
+ loop do
292
+ line = read_line(connection, deadline, started)
293
+ break if line.empty?
294
+
295
+ size += line.bytesize
296
+ raise ConnectionBroken, "the daemon's answer has too many headers" if size > HEADER_LIMIT
297
+
298
+ header_name, header_value = line.split(":", 2)
299
+ headers[header_name.strip.downcase] = header_value.strip unless header_value.nil?
300
+ end
301
+ [match[2].to_i, headers, match[1]]
302
+ end
303
+
304
+ def check_size(size)
305
+ raise Error.new(ErrorCode::INVALID_RESPONSE, "the daemon's answer is too large") if size > Wire::RESPONSE_LIMIT
306
+ end
307
+
308
+ # The body and whether its length was framed, so the connection can carry another request.
309
+ def read_body(connection, headers, deadline, started)
310
+ if headers["transfer-encoding"].to_s.downcase.include?("chunked")
311
+ [read_chunked(connection, deadline, started), true]
312
+ elsif headers.key?("content-length")
313
+ length = Integer(headers["content-length"], 10, exception: false)
314
+ raise ConnectionBroken, "the daemon's answer has a bad Content-Length" if length.nil? || length.negative?
315
+
316
+ check_size(length)
317
+ [read_bytes(connection, length, deadline, started), true]
318
+ else
319
+ [read_to_end(connection, deadline, started), false]
320
+ end
321
+ end
322
+
323
+ def read_chunked(connection, deadline, started)
324
+ body = +"".b
325
+ loop do
326
+ size_line = read_line(connection, deadline, started)
327
+ size = Integer(size_line.split(";", 2).first.to_s.strip, 16, exception: false)
328
+ raise ConnectionBroken, "the daemon's answer has a bad chunk size" if size.nil? || size.negative?
329
+
330
+ if size.zero?
331
+ # Trailers, up to the blank line.
332
+ nil until read_line(connection, deadline, started).empty?
333
+ return body
334
+ end
335
+ check_size(body.bytesize + size)
336
+ body << read_bytes(connection, size, deadline, started)
337
+ raise ConnectionBroken, "the daemon's answer has a bad chunk end" unless read_line(connection, deadline,
338
+ started).empty?
339
+ end
340
+ end
341
+
342
+ def read_to_end(connection, deadline, started)
343
+ body = connection.buffer
344
+ loop do
345
+ check_size(body.bytesize)
346
+ fill(connection, deadline, started)
347
+ end
348
+ rescue ConnectionBroken
349
+ body
350
+ end
351
+ end
352
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Litebackup
4
+ # The caller's file mode creation mask, which acquire and restore send.
5
+ module Umask
6
+ # Keeps two threads of this gem from setting the umask at once.
7
+ LOCK = Mutex.new
8
+
9
+ module_function
10
+
11
+ # This process's umask, so a file the daemon creates gets the bits a file
12
+ # this process created would. On Linux it reads the Umask line of
13
+ # /proc/self/status, which leaves the mask alone; elsewhere, as on macOS,
14
+ # it sets the mask and puts it back at once, so a file another thread
15
+ # creates in that moment could get the mask 0.
16
+ def current_umask
17
+ mask = status_umask("/proc/self/status")
18
+ return mask unless mask.nil?
19
+
20
+ LOCK.synchronize do
21
+ previous = File.umask(0)
22
+ File.umask(previous)
23
+ previous
24
+ end
25
+ end
26
+
27
+ # Reads the octal Umask line of a /proc status file, nil when it has none.
28
+ def status_umask(path)
29
+ # Read as bytes: the process name on the Name line need not be UTF-8.
30
+ lines = File.binread(path).lines
31
+ line = lines.find { |candidate| candidate.start_with?("Umask:") }
32
+ return nil if line.nil?
33
+
34
+ text = line.delete_prefix("Umask:").strip
35
+ return nil unless text.match?(/\A[0-7]+\z/)
36
+
37
+ mask = text.to_i(8)
38
+ mask.between?(0, 0o777) ? mask : nil
39
+ rescue SystemCallError, IOError
40
+ nil
41
+ end
42
+
43
+ # The umask a request sends: the one passed in, checked, or this process's.
44
+ def request_umask(umask)
45
+ return current_umask if umask.nil?
46
+ unless umask.is_a?(Integer) && umask.between?(0, 0o777)
47
+ raise Litebackup.invalid_argument("umask must be between 0 and 0777")
48
+ end
49
+
50
+ umask
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Litebackup
4
+ # Sent with every call. Daemons refuse SDKs older than their minimum with sdk_unsupported.
5
+ VERSION = "1.3.0"
6
+ # Connecting to an older daemon fails with daemon_unsupported.
7
+ MINIMUM_DAEMON_VERSION = "1.1.0"
8
+ end