-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathfile.py
More file actions
473 lines (392 loc) · 14.5 KB
/
file.py
File metadata and controls
473 lines (392 loc) · 14.5 KB
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
import ctypes
import datetime
from typing import List, Optional, Union
from .. import _binaryninjacore as core
from .. import enums
from . import databasesync
from . import folder as _folder
from . import project, remote, snapshot, util
from ..binaryview import BinaryView
from ..database import Database
from ..filemetadata import FileMetadata
from ..project import ProjectFile
class RemoteFile:
"""
Class representing a remote project file. It controls the various
snapshots and raw file contents associated with the analysis.
"""
def __init__(self, handle: core.BNRemoteFileHandle):
self._handle = ctypes.cast(handle, core.BNRemoteFileHandle)
def __del__(self):
if core is not None:
core.BNFreeRemoteFile(self._handle)
def __eq__(self, other):
if not isinstance(other, RemoteFile):
return False
return other.id == self.id
def __str__(self):
path = self.name
parent = self.folder
while parent is not None:
path = parent.name + '/' + path
parent = parent.parent
return f'<file: {self.remote.name}/{self.project.name}/{path}>'
def __repr__(self):
path = self.name
parent = self.folder
while parent is not None:
path = parent.name + '/' + path
parent = parent.parent
return f'<file: {self.remote.name}/{self.project.name}/{path}>'
@staticmethod
def get_for_local_database(database: 'Database') -> Optional['RemoteFile']:
"""
Look up the remote File for a local database, or None if there is no matching
remote File found.
See :func:`get_for_bv` to load from a BinaryView.
:param database: Local database
:return: Remote File object
:rtype: File or None
"""
remote = databasesync.get_remote_for_local_database(database)
if remote is None:
return None
if not remote.has_pulled_projects:
remote.pull_projects()
project = databasesync.get_remote_project_for_local_database(database)
if project is None:
return None
if not project.has_pulled_files:
project.pull_files()
return databasesync.get_remote_file_for_local_database(database)
@staticmethod
def get_for_bv(bv: 'BinaryView') -> Optional['RemoteFile']:
"""
Look up the remote File for a local BinaryView, or None if there is no matching
remote File found.
:param bv: Local BinaryView
:return: Remote File object
:rtype: File or None
"""
if not bv.file.has_database:
return None
return RemoteFile.get_for_local_database(bv.file.database)
@property
def core_file(self) -> 'ProjectFile':
core_handle = core.BNRemoteFileGetCoreFile(self._handle)
if core_handle is None:
raise RuntimeError(util._last_error())
return ProjectFile(handle=ctypes.cast(core_handle, ctypes.POINTER(core.BNProjectFile)))
@property
def project(self) -> 'project.RemoteProject':
"""
Owning Project
:return: Project object
"""
value = core.BNRemoteFileGetProject(self._handle)
if value is None:
raise RuntimeError(util._last_error())
return project.RemoteProject(handle=value)
@property
def remote(self) -> 'remote.Remote':
"""
Owning Remote
:return: Remote object
"""
value = core.BNRemoteFileGetRemote(self._handle)
if value is None:
raise RuntimeError(util._last_error())
return remote.Remote(handle=value)
@property
def folder(self) -> Optional['_folder.RemoteFolder']:
"""
Parent folder, if one exists. None if this is in the root of the project.
:return: Folder object or None
"""
if not self.project.has_pulled_folders:
self.project.pull_folders()
value = core.BNRemoteFileGetFolder(self._handle)
if value is None:
return None
return _folder.RemoteFolder(handle=value)
@folder.setter
def folder(self, folder: Optional['_folder.RemoteFolder']):
"""
Set the parent folder of a file.
:param folder: New parent folder, or None to move file to the root of the project.
"""
folder_handle = folder._handle if folder is not None else None
if not core.BNRemoteFileSetFolder(self._handle, folder_handle):
raise RuntimeError(util._last_error())
@property
def url(self) -> str:
"""
Web api endpoint URL
:return: URL string
"""
return core.BNRemoteFileGetUrl(self._handle)
@property
def chat_log_url(self) -> str:
"""
Chat log api endpoint URL
:return: URL string
"""
return core.BNRemoteFileGetChatLogUrl(self._handle)
@property
def id(self) -> str:
"""
Unique id
:return: Id string
"""
return core.BNRemoteFileGetId(self._handle)
@property
def type(self) -> enums.RemoteFileType:
"""
File Type
All files share the same properties, but files with different types may make different
uses of those properties, or not use some of them at all.
:return: Type of file on server (enum)
"""
return enums.RemoteFileType(core.BNRemoteFileGetType(self._handle))
@property
def created(self) -> datetime.datetime:
"""
Created date of the file
:return: Date object
"""
return datetime.datetime.utcfromtimestamp(core.BNRemoteFileGetCreated(self._handle))
@property
def last_modified(self) -> datetime.datetime:
"""
Last modified date of the file
:return: Date object
"""
return datetime.datetime.utcfromtimestamp(core.BNRemoteFileGetLastModified(self._handle))
@property
def last_snapshot(self) -> datetime.datetime:
"""
Date of last snapshot in the file
:return: Date object
"""
return datetime.datetime.utcfromtimestamp(core.BNRemoteFileGetLastSnapshot(self._handle))
@property
def last_snapshot_by(self) -> str:
"""
Username of user who pushed the last snapshot in the file
:return: Username string
"""
return core.BNRemoteFileGetLastSnapshotBy(self._handle)
@property
def hash(self) -> str:
"""
Hash of file contents (no algorithm guaranteed)
:return: Hash string
"""
return core.BNRemoteFileGetHash(self._handle)
@property
def name(self) -> str:
"""
Displayed name of file
:return: Name string
"""
return core.BNRemoteFileGetName(self._handle)
@name.setter
def name(self, value: str):
"""
Set the display name of the file. You will need to push the file to update the remote version.
:param value: New name
"""
if not core.BNRemoteFileSetName(self._handle, value):
raise RuntimeError(util._last_error())
@property
def description(self) -> str:
"""
Description of the file
:return: Description string
"""
return core.BNRemoteFileGetDescription(self._handle)
@description.setter
def description(self, value: str):
"""
Set the description of the file. You will need to push the file to update the remote version.
:param description: New description
"""
if not core.BNRemoteFileSetDescription(self._handle, value):
raise RuntimeError(util._last_error())
@property
def size(self) -> int:
"""
Size of raw content of file, in bytes
:return: Size in bytes
"""
return core.BNRemoteFileGetSize(self._handle)
@property
def default_path(self) -> str:
"""
Get the default filepath for a remote File. This is based off the Setting for
collaboration.directory, the file's id, the file's project's id, and the file's
remote's id.
:return: Default file path
:rtype: str
"""
return databasesync.default_file_path(self)
@property
def has_pulled_snapshots(self) -> bool:
"""
If the file has pulled the snapshots yet
:return: True if they have been pulled
"""
return core.BNRemoteFileHasPulledSnapshots(self._handle)
@property
def snapshots(self) -> List['snapshot.CollabSnapshot']:
"""
Get the list of snapshots in this file.
.. note:: If snapshots have not been pulled, they will be pulled upon calling this.
:return: List of Snapshot objects
:raises: RuntimeError if there was an error pulling snapshots
"""
if not self.has_pulled_snapshots:
self.pull_snapshots()
count = ctypes.c_size_t()
value = core.BNRemoteFileGetSnapshots(self._handle, count)
if value is None:
raise RuntimeError(util._last_error())
result = []
for i in range(count.value):
result.append(snapshot.CollabSnapshot(value[i]))
return result
def get_snapshot_by_id(self, id: str) -> Optional['snapshot.CollabSnapshot']:
"""
Get a specific Snapshot in the File by its id
.. note:: If snapshots have not been pulled, they will be pulled upon calling this.
:param id: Id of Snapshot
:return: Snapshot object, if one with that id exists. Else, None
:raises: RuntimeError if there was an error pulling snapshots
"""
if not self.has_pulled_snapshots:
self.pull_snapshots()
value = core.BNRemoteFileGetSnapshotById(self._handle, id)
if value is None:
return None
return snapshot.CollabSnapshot(value)
def pull_snapshots(self, progress: 'util.ProgressFuncType' = util.nop):
"""
Pull the list of Snapshots from the Remote.
:param progress: Function to call for progress updates
:raises: RuntimeError if there was an error pulling snapshots
"""
if not core.BNRemoteFilePullSnapshots(self._handle, util.wrap_progress(progress), None):
raise RuntimeError(util._last_error())
def create_snapshot(self, name: str, contents: bytes, analysis_cache_contents: bytes, file: bytes, parent_ids: List[str], progress: 'util.ProgressFuncType' = util.nop) -> 'snapshot.CollabSnapshot':
"""
Create a new snapshot on the remote (and pull it)
:param name: Snapshot name
:param contents: Snapshot contents
:param analysis_cache_contents: Contents of analysis cache of snapshot
:param file: New file contents (if contents changed)
:param parent_ids: List of ids of parent snapshots (or empty if this is a root snapshot)
:param progress: Function to call on progress updates
:return: Reference to the created snapshot
:raises: RuntimeError if there was an error
"""
array = (ctypes.c_char_p * len(parent_ids))()
for i in range(len(parent_ids)):
array[i] = parent_ids[i]
value = core.BNRemoteFileCreateSnapshot(self._handle, name, contents, len(contents), analysis_cache_contents, len(analysis_cache_contents), file, len(file), array, len(parent_ids), util.wrap_progress(progress), None)
if value is None:
raise RuntimeError(util._last_error())
return snapshot.CollabSnapshot(value)
def delete_snapshot(self, snapshot: 'snapshot.CollabSnapshot'):
"""
Delete a snapshot from the remote
:param snapshot: Snapshot to delete
:raises: RuntimeError if there was an error
"""
if not core.BNRemoteFileDeleteSnapshot(self._handle, snapshot._handle):
raise RuntimeError(util._last_error())
def download(self, progress: 'util.ProgressFuncType' = util.nop):
"""
Download a remote file and possibly dependencies to its project
Dependency download behavior depends on the value of the collaboration.autoDownloadFileDependencies setting
:param progress: Function to call on progress updates
:raises: RuntimeError if there was an error
"""
value = core.BNRemoteFileDownload(self._handle, util.wrap_progress(progress), None)
if not value:
raise RuntimeError(util._last_error())
def download_contents(self, progress: 'util.ProgressFuncType' = util.nop) -> bytes:
"""
Download the contents of a remote file
:param progress: Function to call on progress updates
:return: Contents of the file
:raises: RuntimeError if there was an error
"""
data = (ctypes.POINTER(ctypes.c_ubyte))()
size = ctypes.c_size_t()
value = core.BNRemoteFileDownloadContents(self._handle, util.wrap_progress(progress), None, data, size)
if not value:
raise RuntimeError(util._last_error())
return bytes(ctypes.cast(data, ctypes.POINTER(ctypes.c_uint8 * size.value)).contents)
def download_to_bndb(self, path: Optional[str] = None, progress: 'util.ProgressFuncType' = util.nop) -> FileMetadata:
"""
Download a remote file and save it to a bndb at the given path.
This calls databasesync.download_file and self.sync to fully prepare the bndb.
:param path: Path to new bndb to create
:param progress: Function to call on progress updates
:return: Constructed FileMetadata object
:raises: RuntimeError if there was an error
"""
# TODO: deprecated, use RemoteFile.download() and ProjectFile.export()
if path is None:
path = self.default_path
file = databasesync.download_file(self, path, util.split_progress(progress, 0, [0.5, 0.5]))
self.sync(
file.database, lambda conflicts: False, util.split_progress(progress, 1, [0.5, 0.5]))
return file
def sync(self, bv_or_db: Union['BinaryView', 'Database'], conflict_handler: 'util.ConflictHandlerType', progress: 'util.ProgressFuncType' = util.nop, name_changeset: 'util.NameChangesetFuncType' = util.nop):
"""
Completely sync a file, pushing/pulling/merging/applying changes
:param bv_or_db: Binary view or database to sync with
:param conflict_handler: Function to call to resolve snapshot conflicts
:param name_changeset: Function to call for naming a pushed changeset, if necessary
:param progress: Function to call for progress updates
:raises RuntimeError: If there was an error (or the operation was cancelled)
"""
if isinstance(bv_or_db, BinaryView):
if not bv_or_db.file.has_database:
raise RuntimeError("Cannot sync non-database view")
db = bv_or_db.file.database
else:
db = bv_or_db
databasesync.sync_database(db, self, conflict_handler, progress, name_changeset)
def pull(self, bv_or_db: Union['BinaryView', 'Database'], conflict_handler: 'util.ConflictHandlerType', progress: 'util.ProgressFuncType' = util.nop, name_changeset: 'util.NameChangesetFuncType' = util.nop):
"""
Pull updated snapshots from the remote. Merge local changes with remote changes and
potentially create a new snapshot for unsaved changes, named via name_changeset.
:param bv_or_db: Binary view or database to sync with
:param conflict_handler: Function to call to resolve snapshot conflicts
:param name_changeset: Function to call for naming a pushed changeset, if necessary
:param progress: Function to call for progress updates
:raises RuntimeError: If there was an error (or the operation was cancelled)
"""
if isinstance(bv_or_db, BinaryView):
if not bv_or_db.file.has_database:
raise RuntimeError("Cannot pull non-database view")
db = bv_or_db.file.database
else:
db = bv_or_db
databasesync.pull_database(db, self, conflict_handler, progress, name_changeset)
def push(self, bv_or_db: Union['BinaryView', 'Database'], progress: 'util.ProgressFuncType' = util.nop):
"""
Push locally added snapshots to the remote
:param bv_or_db: Binary view or database to sync with
:param progress: Function to call for progress updates
:raises RuntimeError: If there was an error (or the operation was cancelled)
"""
if isinstance(bv_or_db, BinaryView):
if not bv_or_db.file.has_database:
raise RuntimeError("Cannot push non-database view")
db = bv_or_db.file.database
else:
db = bv_or_db
databasesync.push_database(db, self, progress)