summaryrefslogtreecommitdiff
path: root/python/update.py
blob: 393487097658a6a8eb8886f19529218a9ca346d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# Copyright (c) 2015-2026 Vector 35 Inc
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

import traceback
import ctypes
from typing import Any, Optional

# Binary Ninja components
import binaryninja
from . import _binaryninjacore as core
from .enums import UpdateResult
from .log import log_error_for_exception


class _UpdateChannelMetaClass(type):
	def __iter__(self):
		binaryninja._init_plugins()
		count = ctypes.c_ulonglong()
		errors = ctypes.c_char_p()
		channels = core.BNGetUpdateChannels(count, errors)
		assert channels is not None, "core.BNGetUpdateChannels returned None"
		if errors:
			error_str = errors.value
			core.free_string(errors)
			raise IOError(error_str)
		try:
			for i in range(0, count.value):
				yield UpdateChannel(channels[i].name, channels[i].description, channels[i].latestVersion)
		finally:
			core.BNFreeUpdateChannelList(channels, count.value)

	def __getitem__(cls, name):
		binaryninja._init_plugins()
		count = ctypes.c_ulonglong()
		errors = ctypes.c_char_p()
		channels = core.BNGetUpdateChannels(count, errors)
		assert channels is not None, "core.BNGetUpdateChannels returned None"
		if errors:
			error_str = errors.value
			core.free_string(errors)
			raise IOError(error_str)
		result = None
		for i in range(0, count.value):
			if channels[i].name == str(name):
				result = UpdateChannel(channels[i].name, channels[i].description, channels[i].latestVersion)
				break
		core.BNFreeUpdateChannelList(channels, count.value)
		if result is None:
			raise KeyError("'%s' is not a valid channel" % str(name))
		return result

	def __contains__(cls: '_UpdateChannelMetaClass', name: object) -> bool:
		if not isinstance(name, str):
			return False
		try:
			cls[name]
			return True
		except KeyError:
			return False

	def get(cls: '_UpdateChannelMetaClass', name: str, default: Any = None) -> Optional['UpdateChannel']:
		try:
			return cls[name]
		except KeyError:
			if default is not None:
				return default
			return None


class UpdateProgressCallback:
	def __init__(self, func):
		self.cb = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong,
		                           ctypes.c_ulonglong)(self.callback)
		self.func = func

	def callback(self, ctxt, progress, total):
		try:
			if self.func is not None:
				return self.func(progress, total)
			return True
		except Exception:
			log_error_for_exception("Unhandled Python exception in update progress callback")

	@property
	def active(cls):
		return core.BNGetActiveUpdateChannel()

	@active.setter
	def active(cls, value: str) -> None:
		return core.BNSetActiveUpdateChannel(value)


class UpdateChannel(metaclass=_UpdateChannelMetaClass):
	def __init__(self, name, desc, ver):
		self._name = name
		self._description = desc
		self._latest_version_num = ver

	@property
	def versions(self):
		"""List of versions (read-only)"""
		count = ctypes.c_ulonglong()
		errors = ctypes.c_char_p()
		versions = core.BNGetUpdateChannelVersions(self._name, count, errors)
		assert versions is not None, "core.BNGetUpdateChannelVersions returned None"
		if errors:
			error_str = errors.value
			core.free_string(errors)
			raise IOError(error_str)
		result = []
		for i in range(0, count.value):
			result.append(UpdateVersion(self, versions[i].version, versions[i].notes, versions[i].time))
		core.BNFreeUpdateChannelVersionList(versions, count.value)
		return result

	@property
	def latest_version(self):
		"""Latest version (read-only)"""
		count = ctypes.c_ulonglong()
		errors = ctypes.c_char_p()
		versions = core.BNGetUpdateChannelVersions(self._name, count, errors)
		assert versions is not None, "core.BNGetUpdateChannelVersions returned None"
		if errors:
			error_str = errors.value
			core.free_string(errors)
			raise IOError(error_str)
		result = None
		for i in range(0, count.value):
			if versions[i].version == self._latest_version_num:
				result = UpdateVersion(self, versions[i].version, versions[i].notes, versions[i].time)
				break
		core.BNFreeUpdateChannelVersionList(versions, count.value)
		return result

	@property
	def updates_available(self):
		"""Whether updates are available (read-only)"""
		errors = ctypes.c_char_p()
		result = core.BNAreUpdatesAvailable(self._name, None, None, errors)
		if errors:
			error_str = errors.value
			core.free_string(errors)
			raise IOError(error_str)
		return result

	def __setattr__(self, name, value):
		try:
			object.__setattr__(self, name, value)
		except AttributeError:
			raise AttributeError("attribute '%s' is read only" % name)

	def __repr__(self):
		return "<channel: %s>" % self._name

	def __str__(self):
		return self._name

	def update_to_latest(self, progress=None):
		cb = UpdateProgressCallback(progress)
		errors = ctypes.c_char_p()
		result = core.BNUpdateToLatestVersion(self._name, errors, cb.cb, None)
		if errors:
			error_str = errors.value
			core.free_string(errors)
			raise IOError(error_str)
		return UpdateResult(result)

	@property
	def name(self):
		return self._name

	@name.setter
	def name(self, value):
		self._name = value

	@property
	def description(self):
		return self._description

	@description.setter
	def description(self, value):
		self._description = value

	@property
	def latest_version_num(self):
		return self._latest_version_num

	@latest_version_num.setter
	def latest_version_num(self, value):
		self._latest_version_num = value


class UpdateVersion:
	def __init__(self, channel, ver, notes, t):
		self._channel = channel
		self._version = ver
		self._notes = notes
		self._time = t

	def __repr__(self):
		return "<version: %s>" % self._version

	def __str__(self):
		return self._version

	def update(self, progress=None):
		cb = UpdateProgressCallback(progress)
		errors = ctypes.c_char_p()
		result = core.BNUpdateToVersion(self._channel.name, self._version, errors, cb.cb, None)
		if errors:
			error_str = errors.value
			core.free_string(errors)
			raise IOError(error_str)
		return UpdateResult(result)

	@property
	def channel(self):
		return self._channel

	@channel.setter
	def channel(self, value):
		self._channel = value

	@property
	def version(self):
		return self._version

	@version.setter
	def version(self, value):
		self._version = value

	@property
	def notes(self):
		return self._notes

	@notes.setter
	def notes(self, value):
		self._notes = value

	@property
	def time(self):
		return self._time

	@time.setter
	def time(self, value):
		self._time = value


def are_auto_updates_enabled():
	"""
	``are_auto_updates_enabled`` queries if auto updates are enabled.

	:return: boolean True if auto updates are enabled. False if they are disabled.
	:rtype: bool
	"""
	return core.BNAreAutoUpdatesEnabled()


def set_auto_updates_enabled(enabled):
	"""
	``set_auto_updates_enabled`` sets auto update enabled status.

	:param bool enabled: True to enable update, False to disable updates.
	:rtype: None
	"""
	core.BNSetAutoUpdatesEnabled(enabled)


def get_time_since_last_update_check():
	"""
	``get_time_since_last_update_check`` returns the time stamp for the last time updates were checked.

	:return: time stamp for last update check
	:rtype: int
	"""
	return core.BNGetTimeSinceLastUpdateCheck()


def is_update_installation_pending():
	"""
	``is_update_installation_pending`` whether an update has been downloaded and is waiting installation

	:return: boolean True if an update is pending, false if no update is pending
	:rtype: bool
	"""
	return core.BNIsUpdateInstallationPending()


def install_pending_update():
	"""
	``install_pending_update`` installs any pending updates

	:rtype: None
	"""
	errors = ctypes.c_char_p()
	core.BNInstallPendingUpdate(errors)
	if errors:
		error_str = errors.value
		core.free_string(errors)
		raise IOError(error_str)


def updates_checked():
	core.BNUpdatesChecked()