[36] | 1 |
|
---|
[919] | 2 | from .config import Config
|
---|
| 3 | from .util import utf2unicode
|
---|
[36] | 4 |
|
---|
| 5 | import os
|
---|
| 6 | import sys
|
---|
[919] | 7 | import urllib.request, urllib.error, urllib.parse
|
---|
[36] | 8 | import tempfile
|
---|
| 9 | import socket
|
---|
| 10 | import subprocess
|
---|
[37] | 11 | import hashlib
|
---|
[788] | 12 | import traceback
|
---|
[948] | 13 | import io
|
---|
[36] | 14 |
|
---|
[39] | 15 | if os.name=="nt":
|
---|
| 16 | import win32api
|
---|
| 17 |
|
---|
[36] | 18 | #------------------------------------------------------------------------------
|
---|
| 19 |
|
---|
[298] | 20 | ## @package mlx.update
|
---|
| 21 | #
|
---|
| 22 | # Automatic update handling.
|
---|
| 23 | #
|
---|
| 24 | # The program can update itself automatically. For this purpose it maintains a
|
---|
| 25 | # manifest of the files installed containing the relative paths, sizes and
|
---|
| 26 | # checksums of each files. When the program starts up, this manifest file is
|
---|
| 27 | # downloaded from the update server and is compared to the local one. Then the
|
---|
| 28 | # updated and new files are downloaded with names that are created by appending
|
---|
| 29 | # the checksum to the actual name, so as not to overwrite any existing files at
|
---|
| 30 | # this stage. If all files are downloaded, the downloaded files are renamed to
|
---|
| 31 | # their real names. On Windows, the old file is removed first to avoid trouble
|
---|
| 32 | # with 'busy' files. If removing a file fails, the file will be moved to a
|
---|
| 33 | # temporary directory, that will be removed when the program starts the next
|
---|
| 34 | # time.
|
---|
| 35 |
|
---|
| 36 | #------------------------------------------------------------------------------
|
---|
| 37 |
|
---|
[36] | 38 | manifestName = "MLXMANIFEST"
|
---|
[37] | 39 | toremoveName = "toremove"
|
---|
[36] | 40 |
|
---|
| 41 | #------------------------------------------------------------------------------
|
---|
| 42 |
|
---|
| 43 | class Manifest(object):
|
---|
| 44 | """The manifest of the files.
|
---|
| 45 |
|
---|
| 46 | The manifest file consists of one line for each file. Each line contains 3
|
---|
| 47 | items separated by tabs:
|
---|
| 48 | - the path of the file relative to the distribution's root
|
---|
| 49 | - the size of the file
|
---|
| 50 | - the MD5 sum of the file."""
|
---|
| 51 | def __init__(self):
|
---|
| 52 | """Construct the manifest."""
|
---|
| 53 | self._files = {}
|
---|
| 54 |
|
---|
| 55 | @property
|
---|
| 56 | def files(self):
|
---|
| 57 | """Get an iterator over the files.
|
---|
| 58 |
|
---|
| 59 | Each file is returned as a 3-tuple with items as in the file."""
|
---|
[919] | 60 | for (path, (size, sum)) in self._files.items():
|
---|
[36] | 61 | yield (path, size, sum)
|
---|
[189] | 62 |
|
---|
| 63 | def copy(self):
|
---|
| 64 | """Create a copy of the manifest."""
|
---|
| 65 | manifest = Manifest()
|
---|
| 66 | manifest._files = self._files.copy()
|
---|
| 67 | return manifest
|
---|
[36] | 68 |
|
---|
| 69 | def addFile(self, path, size, sum):
|
---|
| 70 | """Add a file to the manifest."""
|
---|
[37] | 71 | self._files[path] = (size, sum)
|
---|
[36] | 72 |
|
---|
[37] | 73 | def addFiles(self, baseDirectory, subdirectory):
|
---|
| 74 | """Add the files in the given directory and subdirectories of it to the
|
---|
| 75 | manifest."""
|
---|
| 76 | directory = baseDirectory
|
---|
| 77 | for d in subdirectory: directory = os.path.join(directory, d)
|
---|
| 78 |
|
---|
| 79 | for entry in os.listdir(directory):
|
---|
| 80 | fullPath = os.path.join(directory, entry)
|
---|
| 81 | if os.path.isfile(fullPath):
|
---|
| 82 | size = os.stat(fullPath).st_size
|
---|
| 83 | sum = hashlib.md5()
|
---|
| 84 | with open(fullPath, "rb") as f:
|
---|
| 85 | while True:
|
---|
| 86 | data = f.read(4096)
|
---|
| 87 | if data: sum.update(data)
|
---|
| 88 | else: break
|
---|
| 89 | self.addFile("/".join(subdirectory + [entry]), size,
|
---|
| 90 | sum.hexdigest())
|
---|
| 91 | elif os.path.isdir(fullPath):
|
---|
| 92 | self.addFiles(baseDirectory, subdirectory + [entry])
|
---|
| 93 |
|
---|
[36] | 94 | def readFrom(self, file):
|
---|
| 95 | """Read a manifest from the given file object."""
|
---|
| 96 | for line in iter(file.readline, ""):
|
---|
| 97 | (path, size, sum) = line.strip().split("\t")
|
---|
| 98 | self._files[path] = (int(size), sum)
|
---|
| 99 |
|
---|
| 100 | def writeInto(self, file):
|
---|
| 101 | """Write the manifest into the file at the given path."""
|
---|
[919] | 102 | for (path, (size, sum)) in self._files.items():
|
---|
[36] | 103 | file.write("%s\t%d\t%s\n" % (path, size, sum))
|
---|
| 104 |
|
---|
| 105 | def compare(self, other):
|
---|
| 106 | """Compare this manifest with the other one.
|
---|
| 107 |
|
---|
| 108 | This returns a tuple of two lists:
|
---|
| 109 | - the files that are either different or are present in other, but not
|
---|
| 110 | here. Each file is returned as a 3-tuple as with other functions, the
|
---|
| 111 | size and sum are those of the new file.
|
---|
| 112 | - the paths of the files that are present here, but not in other."""
|
---|
| 113 | modifiedAndNew = []
|
---|
| 114 | for (path, otherSize, otherSum) in other.files:
|
---|
| 115 | if path in self._files:
|
---|
| 116 | (size, sum) = self._files[path]
|
---|
| 117 | if size!=otherSize or sum!=otherSum:
|
---|
| 118 | modifiedAndNew.append((path, otherSize, otherSum))
|
---|
| 119 | else:
|
---|
| 120 | modifiedAndNew.append((path, otherSize, otherSum))
|
---|
| 121 |
|
---|
[949] | 122 | if os.name=="nt":
|
---|
| 123 | otherFiles = [path.lower() for path in other._files]
|
---|
| 124 | else:
|
---|
| 125 | otherFiles = other._files
|
---|
| 126 |
|
---|
| 127 | removed = [path for path in self._files if
|
---|
| 128 | (path.lower() if os.name=="nt" else path) not in otherFiles]
|
---|
[36] | 129 |
|
---|
| 130 | return (modifiedAndNew, removed)
|
---|
[189] | 131 |
|
---|
| 132 | def __contains__(self, path):
|
---|
| 133 | """Determine if the given path is in the manifest."""
|
---|
| 134 | return path in self._files
|
---|
| 135 |
|
---|
| 136 | def __getitem__(self, path):
|
---|
| 137 | """Get data of the file with the given path."""
|
---|
| 138 | return self._files[path] if path in self._files else None
|
---|
[36] | 139 |
|
---|
| 140 | #------------------------------------------------------------------------------
|
---|
| 141 |
|
---|
| 142 | class ClientListener(object):
|
---|
| 143 | """A listener that sends any requests via a socket."""
|
---|
| 144 | def __init__(self, sock):
|
---|
| 145 | """Construct the listener."""
|
---|
| 146 | self._sock = sock
|
---|
| 147 |
|
---|
| 148 | def downloadingManifest(self):
|
---|
| 149 | """Called when the downloading of the manifest has started."""
|
---|
| 150 | self._send(["downloadingManifest"])
|
---|
| 151 |
|
---|
| 152 | def downloadedManifest(self):
|
---|
| 153 | """Called when the manifest has been downloaded."""
|
---|
| 154 | self._send(["downloadedManifest"])
|
---|
| 155 |
|
---|
| 156 | def needSudo(self):
|
---|
| 157 | """Called when an admin-level program must be called to complete the
|
---|
| 158 | update.
|
---|
| 159 |
|
---|
| 160 | This is not valid from a client, as that client is supposed to be the
|
---|
| 161 | admin-level program :)"""
|
---|
| 162 | assert False
|
---|
| 163 |
|
---|
[37] | 164 | def setTotalSize(self, numToModifyAndNew, totalSize, numToRemove,
|
---|
| 165 | numToRemoveLocal):
|
---|
[36] | 166 | """Called when starting the downloading of the files."""
|
---|
| 167 | self._send(["setTotalSize", str(numToModifyAndNew), str(totalSize),
|
---|
[37] | 168 | str(numToRemove), str(numToRemoveLocal)])
|
---|
[36] | 169 |
|
---|
| 170 | def setDownloaded(self, downloaded):
|
---|
| 171 | """Called periodically after downloading a certain amount of data."""
|
---|
| 172 | self._send(["setDownloaded", str(downloaded)])
|
---|
| 173 |
|
---|
| 174 | def startRenaming(self):
|
---|
| 175 | """Called when the renaming of the downloaded files is started."""
|
---|
| 176 | self._send(["startRenaming"])
|
---|
| 177 |
|
---|
| 178 | def renamed(self, path, count):
|
---|
| 179 | """Called when a file has been renamed."""
|
---|
| 180 | self._send(["renamed", path, str(count)])
|
---|
| 181 |
|
---|
| 182 | def startRemoving(self):
|
---|
| 183 | """Called when the removing of files has started."""
|
---|
| 184 | self._send(["startRemoving"])
|
---|
| 185 |
|
---|
| 186 | def removed(self, path, count):
|
---|
| 187 | """Called when a file has been removed."""
|
---|
| 188 | self._send(["removed", path, str(count)])
|
---|
| 189 |
|
---|
| 190 | def writingManifest(self):
|
---|
| 191 | """Called when we have started writing the manifest."""
|
---|
| 192 | self._send(["writingManifest"])
|
---|
| 193 |
|
---|
| 194 | def done(self):
|
---|
| 195 | """Called when the update has completed."""
|
---|
| 196 | self._send(["done"])
|
---|
| 197 |
|
---|
| 198 | def failed(self, what):
|
---|
| 199 | """Called when something has failed."""
|
---|
| 200 | self._send(["failed", what])
|
---|
| 201 |
|
---|
| 202 | def _send(self, words):
|
---|
| 203 | """Send the given words via the socket."""
|
---|
[948] | 204 | self._sock.send(bytes("\t".join(words) + "\n", "utf-8"))
|
---|
[36] | 205 |
|
---|
| 206 | #------------------------------------------------------------------------------
|
---|
| 207 |
|
---|
| 208 | def readLocalManifest(directory):
|
---|
| 209 | """Read the local manifest from the given directory."""
|
---|
| 210 | manifestPath = os.path.join(directory, manifestName)
|
---|
| 211 |
|
---|
| 212 | manifest = Manifest()
|
---|
| 213 | try:
|
---|
| 214 | with open(manifestPath, "rt") as f:
|
---|
| 215 | manifest.readFrom(f)
|
---|
[919] | 216 | except Exception as e:
|
---|
| 217 | print("Error reading the manifest, ignoring:", utf2unicode(str(e)))
|
---|
[36] | 218 | manifest = Manifest()
|
---|
| 219 |
|
---|
| 220 | return manifest
|
---|
| 221 |
|
---|
| 222 | #------------------------------------------------------------------------------
|
---|
| 223 |
|
---|
| 224 | def prepareUpdate(directory, updateURL, listener):
|
---|
| 225 | """Prepare the update by downloading the manifest and comparing it with the
|
---|
| 226 | local one."""
|
---|
| 227 | manifest = readLocalManifest(directory)
|
---|
| 228 |
|
---|
| 229 | updateURL += "/" + os.name
|
---|
| 230 |
|
---|
| 231 | listener.downloadingManifest()
|
---|
| 232 | f = None
|
---|
| 233 | try:
|
---|
| 234 | updateManifest = Manifest()
|
---|
[948] | 235 | reply = urllib.request.urlopen(updateURL + "/" + manifestName)
|
---|
| 236 | charset = reply.headers.get_content_charset()
|
---|
| 237 | content = reply.read().decode("utf-8" if charset is None else charset)
|
---|
| 238 | updateManifest.readFrom(io.StringIO(content))
|
---|
[36] | 239 |
|
---|
[919] | 240 | except Exception as e:
|
---|
[401] | 241 | error = utf2unicode(str(e))
|
---|
[919] | 242 | print("Error downloading manifest:", error, file=sys.stderr)
|
---|
[401] | 243 | listener.failed(error)
|
---|
[36] | 244 | return None
|
---|
| 245 | finally:
|
---|
| 246 | if f is not None: f.close()
|
---|
| 247 |
|
---|
| 248 | listener.downloadedManifest()
|
---|
| 249 |
|
---|
| 250 | (modifiedAndNew, removed) = manifest.compare(updateManifest)
|
---|
| 251 |
|
---|
| 252 | return (manifest, updateManifest, modifiedAndNew, removed)
|
---|
| 253 |
|
---|
| 254 | #------------------------------------------------------------------------------
|
---|
| 255 |
|
---|
[37] | 256 | def getToremoveFiles(directory):
|
---|
| 257 | """Add the files to remove from the toremove directory."""
|
---|
| 258 | toremove = []
|
---|
| 259 | toremoveDirectory = os.path.join(directory, toremoveName)
|
---|
| 260 | if os.path.isdir(toremoveDirectory):
|
---|
| 261 | for entry in os.listdir(toremoveDirectory):
|
---|
| 262 | toremove.append(os.path.join(toremoveName, entry))
|
---|
| 263 | return toremove
|
---|
| 264 |
|
---|
| 265 | #------------------------------------------------------------------------------
|
---|
| 266 |
|
---|
[36] | 267 | def createLocalPath(directory, path):
|
---|
| 268 | """Create a local path from the given manifest path."""
|
---|
| 269 | localPath = directory
|
---|
| 270 | for element in path.split("/"):
|
---|
| 271 | localPath = os.path.join(localPath, element)
|
---|
| 272 | return localPath
|
---|
| 273 |
|
---|
| 274 | #------------------------------------------------------------------------------
|
---|
| 275 |
|
---|
[37] | 276 | def getToremoveDir(toremoveDir, directory):
|
---|
| 277 | """Get the path of the directory that will contain the files that are to be
|
---|
| 278 | removed."""
|
---|
| 279 | if toremoveDir is None:
|
---|
| 280 | toremoveDir = os.path.join(directory, toremoveName)
|
---|
| 281 | try:
|
---|
| 282 | os.mkdir(toremoveDir)
|
---|
| 283 | except:
|
---|
| 284 | pass
|
---|
| 285 |
|
---|
| 286 | return toremoveDir
|
---|
| 287 |
|
---|
| 288 | #------------------------------------------------------------------------------
|
---|
| 289 |
|
---|
| 290 | def removeFile(toremoveDir, directory, path):
|
---|
| 291 | """Remove the file at the given path or store it in a temporary directory.
|
---|
| 292 |
|
---|
| 293 | If the removal of the file fails, it will be stored in a temporary
|
---|
| 294 | directory. This is useful for files thay may be open and cannot be removed
|
---|
| 295 | right away."""
|
---|
| 296 | try:
|
---|
| 297 | os.remove(path)
|
---|
| 298 | except:
|
---|
| 299 | try:
|
---|
| 300 | sum = hashlib.md5()
|
---|
[948] | 301 | sum.update(bytes(path, "utf-8"))
|
---|
[37] | 302 | toremoveDir = getToremoveDir(toremoveDir, directory)
|
---|
[788] | 303 | targetPath = os.path.join(toremoveDir, sum.hexdigest())
|
---|
| 304 | try:
|
---|
| 305 | os.remove(targetPath)
|
---|
| 306 | except:
|
---|
| 307 | pass
|
---|
| 308 | os.rename(path, targetPath)
|
---|
[919] | 309 | except Exception as e:
|
---|
| 310 | print("Cannot remove file " + path + ": " + utf2unicode(str(e)))
|
---|
[37] | 311 |
|
---|
| 312 | #------------------------------------------------------------------------------
|
---|
| 313 |
|
---|
[781] | 314 | def removeFiles(directory, listener, removed, count):
|
---|
| 315 | """Remove the given files."""
|
---|
| 316 | toremoveDir = None
|
---|
| 317 |
|
---|
| 318 | listener.startRemoving()
|
---|
| 319 |
|
---|
| 320 | removed.sort(reverse = True)
|
---|
| 321 | for path in removed:
|
---|
| 322 | removePath = createLocalPath(directory, path)
|
---|
| 323 | removeFile(toremoveDir, directory, removePath)
|
---|
| 324 |
|
---|
| 325 | removeDirectory = os.path.dirname(removePath)
|
---|
| 326 | try:
|
---|
| 327 | os.removedirs(removeDirectory)
|
---|
| 328 | except:
|
---|
| 329 | pass
|
---|
| 330 |
|
---|
| 331 | count += 1
|
---|
| 332 | listener.removed(path, count)
|
---|
| 333 |
|
---|
| 334 | return count
|
---|
| 335 |
|
---|
| 336 | #------------------------------------------------------------------------------
|
---|
| 337 |
|
---|
[36] | 338 | def updateFiles(directory, updateURL, listener,
|
---|
[37] | 339 | manifest, modifiedAndNew, removed, localRemoved):
|
---|
[36] | 340 | """Update the files according to the given information."""
|
---|
| 341 | totalSize = 0
|
---|
| 342 | for (path, size, sum) in modifiedAndNew:
|
---|
| 343 | totalSize += size
|
---|
| 344 |
|
---|
[37] | 345 | listener.setTotalSize(len(modifiedAndNew), totalSize,
|
---|
| 346 | len(removed), len(localRemoved))
|
---|
[36] | 347 |
|
---|
| 348 | downloaded = 0
|
---|
| 349 | fin = None
|
---|
[37] | 350 | toremoveDir = None
|
---|
| 351 |
|
---|
[36] | 352 | try:
|
---|
| 353 | updateURL += "/" + os.name
|
---|
| 354 |
|
---|
[781] | 355 | removeCount = 0
|
---|
| 356 | if localRemoved:
|
---|
| 357 | removeCount = removeFiles(directory, listener,
|
---|
| 358 | localRemoved, removeCount)
|
---|
| 359 |
|
---|
[36] | 360 | for (path, size, sum) in modifiedAndNew:
|
---|
| 361 | targetFile = createLocalPath(directory, path)
|
---|
| 362 | targetFile += "."
|
---|
| 363 | targetFile += sum
|
---|
| 364 |
|
---|
| 365 | targetDirectory = os.path.dirname(targetFile)
|
---|
[950] | 366 | if targetDirectory and not os.path.isdir(targetDirectory):
|
---|
[36] | 367 | os.makedirs(targetDirectory)
|
---|
| 368 |
|
---|
| 369 | with open(targetFile, "wb") as fout:
|
---|
[919] | 370 | fin = urllib.request.urlopen(updateURL + "/" + path)
|
---|
[36] | 371 | while True:
|
---|
[958] | 372 | data = fin.read(256*1024)
|
---|
[36] | 373 | if not data:
|
---|
| 374 | break
|
---|
| 375 | fout.write(data)
|
---|
| 376 | downloaded += len(data)
|
---|
| 377 | listener.setDownloaded(downloaded)
|
---|
| 378 | fin.close()
|
---|
| 379 | fin = None
|
---|
[37] | 380 |
|
---|
[36] | 381 | listener.startRenaming()
|
---|
| 382 | count = 0
|
---|
| 383 | for (path, size, sum) in modifiedAndNew:
|
---|
| 384 | targetFile = createLocalPath(directory, path)
|
---|
| 385 |
|
---|
| 386 | downloadedFile = targetFile + "." + sum
|
---|
| 387 | if os.name=="nt" and os.path.isfile(targetFile):
|
---|
[37] | 388 | removeFile(toremoveDir, directory, targetFile)
|
---|
[36] | 389 | os.rename(downloadedFile, targetFile)
|
---|
| 390 | count += 1
|
---|
| 391 | listener.renamed(path, count)
|
---|
[37] | 392 |
|
---|
[781] | 393 | removeFiles(directory, listener, removed, removeCount)
|
---|
[36] | 394 |
|
---|
| 395 | listener.writingManifest()
|
---|
| 396 |
|
---|
| 397 | manifestPath = os.path.join(directory, manifestName)
|
---|
| 398 | with open(manifestPath, "wt") as f:
|
---|
| 399 | manifest.writeInto(f)
|
---|
| 400 |
|
---|
| 401 | listener.done()
|
---|
[919] | 402 | except Exception as e:
|
---|
[788] | 403 | exc = traceback.format_exc()
|
---|
[919] | 404 | print(utf2unicode(exc), file=sys.stderr)
|
---|
[788] | 405 |
|
---|
[401] | 406 | error = utf2unicode(str(e))
|
---|
[919] | 407 | print("Error:", error, file=sys.stderr)
|
---|
[788] | 408 |
|
---|
[401] | 409 | listener.failed(error)
|
---|
[36] | 410 |
|
---|
| 411 | #------------------------------------------------------------------------------
|
---|
| 412 |
|
---|
| 413 | def isDirectoryWritable(directory):
|
---|
| 414 | """Determine if the given directory can be written."""
|
---|
| 415 | checkFile = os.path.join(directory, "writable.chk")
|
---|
| 416 | try:
|
---|
| 417 | f = open(checkFile, "wt")
|
---|
| 418 | f.close()
|
---|
| 419 | return True
|
---|
[919] | 420 | except Exception as e:
|
---|
[36] | 421 | return False
|
---|
| 422 | finally:
|
---|
| 423 | try:
|
---|
| 424 | os.remove(checkFile)
|
---|
| 425 | except:
|
---|
| 426 | pass
|
---|
| 427 |
|
---|
| 428 | #------------------------------------------------------------------------------
|
---|
| 429 |
|
---|
| 430 | def processMLXUpdate(buffer, listener):
|
---|
| 431 | """Process the given buffer supposedly containing a list of commands."""
|
---|
| 432 | endsWithLine = buffer[-1]=="\n"
|
---|
| 433 | lines = buffer.splitlines()
|
---|
| 434 |
|
---|
| 435 | if endsWithLine:
|
---|
| 436 | buffer = ""
|
---|
| 437 | else:
|
---|
| 438 | buffer = lines[-1]
|
---|
| 439 | lines = lines[:-1]
|
---|
| 440 |
|
---|
| 441 | for line in lines:
|
---|
| 442 | words = line.split("\t")
|
---|
| 443 | try:
|
---|
| 444 | command = words[0]
|
---|
| 445 | if command=="downloadingManifest":
|
---|
| 446 | listener.downloadingManifest()
|
---|
| 447 | elif command=="downloadedManifest":
|
---|
| 448 | listener.downloadedManifest()
|
---|
| 449 | elif command=="setTotalSize":
|
---|
[919] | 450 | listener.setTotalSize(int(words[1]), int(words[2]),
|
---|
[37] | 451 | int(words[3]), int(words[4]))
|
---|
[36] | 452 | elif command=="setDownloaded":
|
---|
[919] | 453 | listener.setDownloaded(int(words[1]))
|
---|
[36] | 454 | elif command=="startRenaming":
|
---|
| 455 | listener.startRenaming()
|
---|
| 456 | elif command=="renamed":
|
---|
| 457 | listener.renamed(words[1], int(words[2]))
|
---|
| 458 | elif command=="startRemoving":
|
---|
| 459 | listener.startRemoving()
|
---|
| 460 | elif command=="removed":
|
---|
| 461 | listener.removed(words[1], int(words[2]))
|
---|
| 462 | elif command=="writingManifest":
|
---|
| 463 | listener.writingManifest()
|
---|
| 464 | elif command=="done":
|
---|
| 465 | listener.done()
|
---|
| 466 | elif command=="failed":
|
---|
| 467 | listener.failed(words[1])
|
---|
[919] | 468 | except Exception as e:
|
---|
| 469 | print("Failed to parse line '%s': %s" % \
|
---|
| 470 | (line, utf2unicode(str(e))), file=sys.stderr)
|
---|
[36] | 471 |
|
---|
| 472 | return buffer
|
---|
| 473 |
|
---|
| 474 | #------------------------------------------------------------------------------
|
---|
| 475 |
|
---|
| 476 | def sudoUpdate(directory, updateURL, listener, manifest):
|
---|
| 477 | """Perform the update via the mlxupdate program."""
|
---|
| 478 | manifestFD = None
|
---|
| 479 | manifestFile = None
|
---|
| 480 | serverSocket = None
|
---|
| 481 | mlxUpdateSocket = None
|
---|
| 482 | try:
|
---|
| 483 | (manifestFD, manifestFile) = tempfile.mkstemp()
|
---|
| 484 | f = os.fdopen(manifestFD, "wt")
|
---|
| 485 | try:
|
---|
| 486 | manifest.writeInto(f)
|
---|
| 487 | finally:
|
---|
| 488 | f.close()
|
---|
| 489 | manifestFD = None
|
---|
| 490 |
|
---|
| 491 | serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
---|
[115] | 492 | serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
---|
[36] | 493 | serverSocket.bind(("127.0.0.1", 0))
|
---|
| 494 | (_host, port) = serverSocket.getsockname()
|
---|
| 495 | serverSocket.listen(1)
|
---|
| 496 |
|
---|
[39] | 497 |
|
---|
| 498 | if os.name=="nt":
|
---|
| 499 | win32api.ShellExecute(0, "open", os.path.join(directory, "mlxupdate"),
|
---|
[671] | 500 | str(port) + " " + manifestFile + " " + updateURL, "", 1)
|
---|
[39] | 501 | else:
|
---|
| 502 | process = subprocess.Popen([os.path.join(directory, "mlxupdate"),
|
---|
[671] | 503 | str(port), manifestFile, updateURL],
|
---|
| 504 | shell = os.name=="nt")
|
---|
[36] | 505 |
|
---|
| 506 | (mlxUpdateSocket, _) = serverSocket.accept()
|
---|
| 507 | serverSocket.close()
|
---|
| 508 | serverSocket = None
|
---|
| 509 |
|
---|
| 510 | buffer = ""
|
---|
| 511 | while True:
|
---|
| 512 | data = mlxUpdateSocket.recv(4096)
|
---|
| 513 | if not data:
|
---|
| 514 | break;
|
---|
| 515 |
|
---|
[948] | 516 | buffer += str(data, "utf-8")
|
---|
[36] | 517 | buffer = processMLXUpdate(buffer, listener)
|
---|
| 518 |
|
---|
| 519 | mlxUpdateSocket.close()
|
---|
| 520 | mlxUpdateSocket = None
|
---|
| 521 |
|
---|
[39] | 522 | if os.name!="nt":
|
---|
| 523 | process.wait()
|
---|
| 524 |
|
---|
[919] | 525 | except Exception as e:
|
---|
[401] | 526 | error = utf2unicode(str(e))
|
---|
[919] | 527 | print("Failed updating:", error, file=sys.stderr)
|
---|
[401] | 528 | listener.failed(error)
|
---|
[36] | 529 | finally:
|
---|
| 530 | if serverSocket is not None:
|
---|
| 531 | try:
|
---|
| 532 | serverSocket.close()
|
---|
| 533 | except:
|
---|
| 534 | pass
|
---|
| 535 | if mlxUpdateSocket is not None:
|
---|
| 536 | try:
|
---|
| 537 | mlxUpdateSocket.close()
|
---|
| 538 | except:
|
---|
| 539 | pass
|
---|
| 540 | if manifestFD is not None:
|
---|
| 541 | try:
|
---|
| 542 | os.close(manifestFD)
|
---|
| 543 | except:
|
---|
| 544 | pass
|
---|
| 545 | if manifestFile is not None:
|
---|
| 546 | try:
|
---|
| 547 | os.remove(manifestFile)
|
---|
| 548 | except:
|
---|
| 549 | pass
|
---|
| 550 |
|
---|
| 551 |
|
---|
| 552 | #------------------------------------------------------------------------------
|
---|
| 553 |
|
---|
| 554 | def update(directory, updateURL, listener, fromGUI = False):
|
---|
| 555 | """Perform the update."""
|
---|
[788] | 556 | try:
|
---|
| 557 | result = prepareUpdate(directory, updateURL, listener)
|
---|
| 558 | if result is None:
|
---|
| 559 | return
|
---|
[36] | 560 |
|
---|
[788] | 561 | (manifest, updateManifest, modifiedAndNew, removed) = result
|
---|
| 562 | localRemoved = getToremoveFiles(directory)
|
---|
| 563 |
|
---|
| 564 | if not modifiedAndNew and not removed and not localRemoved:
|
---|
| 565 | listener.done()
|
---|
| 566 | return
|
---|
[36] | 567 |
|
---|
[788] | 568 | if fromGUI and not isDirectoryWritable(directory):
|
---|
| 569 | if listener.needSudo():
|
---|
| 570 | sudoUpdate(directory, updateURL, listener, updateManifest)
|
---|
| 571 | else:
|
---|
| 572 | updateFiles(directory, updateURL, listener, updateManifest,
|
---|
| 573 | modifiedAndNew, removed, localRemoved)
|
---|
[919] | 574 | except Exception as e:
|
---|
[788] | 575 | exc = traceback.format_exc()
|
---|
[919] | 576 | print(utf2unicode(exc), file=sys.stderr)
|
---|
[788] | 577 |
|
---|
| 578 | error = utf2unicode(str(e))
|
---|
[919] | 579 | print("Update error:", error, file=sys.stderr)
|
---|
[788] | 580 |
|
---|
| 581 | listener.failed(error)
|
---|
[36] | 582 |
|
---|
| 583 | #------------------------------------------------------------------------------
|
---|
| 584 |
|
---|
| 585 | def updateProcess():
|
---|
| 586 | """This is called in the child process, when we need a child process."""
|
---|
[788] | 587 | try:
|
---|
| 588 | clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
---|
| 589 | clientSocket.connect(("127.0.0.1", int(sys.argv[1])))
|
---|
[36] | 590 |
|
---|
[788] | 591 | directory = os.path.dirname(sys.argv[0])
|
---|
| 592 |
|
---|
| 593 | manifest = readLocalManifest(directory)
|
---|
[36] | 594 |
|
---|
[788] | 595 | updateManifest = Manifest()
|
---|
| 596 | with open(sys.argv[2], "rt") as f:
|
---|
| 597 | updateManifest.readFrom(f)
|
---|
| 598 |
|
---|
| 599 | (modifiedAndNew, removed) = manifest.compare(updateManifest)
|
---|
| 600 | localRemoved = getToremoveFiles(directory)
|
---|
[36] | 601 |
|
---|
[788] | 602 | updateFiles(directory, sys.argv[3],
|
---|
| 603 | ClientListener(clientSocket),
|
---|
| 604 | updateManifest, modifiedAndNew, removed, localRemoved)
|
---|
| 605 | except:
|
---|
| 606 | exc = traceback.format_exc()
|
---|
[919] | 607 | print(utf2unicode(exc), file=sys.stderr)
|
---|
[37] | 608 |
|
---|
| 609 | #------------------------------------------------------------------------------
|
---|
| 610 |
|
---|
| 611 | def buildManifest(directory):
|
---|
| 612 | """Build a manifest from the contents of the given directory, into the
|
---|
| 613 | given directory."""
|
---|
| 614 |
|
---|
| 615 | manifestPath = os.path.join(directory, manifestName)
|
---|
| 616 | try:
|
---|
| 617 | os.remove(manifestPath)
|
---|
| 618 | except:
|
---|
| 619 | pass
|
---|
| 620 |
|
---|
| 621 | manifest = Manifest()
|
---|
| 622 | manifest.addFiles(directory, [])
|
---|
| 623 | with open(manifestPath, "wt") as f:
|
---|
| 624 | manifest.writeInto(f)
|
---|
[36] | 625 |
|
---|
| 626 | #------------------------------------------------------------------------------
|
---|
| 627 |
|
---|
[37] | 628 | # if __name__ == "__main__":
|
---|
| 629 | # manifest1 = Manifest()
|
---|
| 630 | # manifest1.addFile("file1.exe", 3242, "40398754589435345934")
|
---|
| 631 | # manifest1.addFile("dir/file2.zip", 45645, "347893245873456987")
|
---|
| 632 | # manifest1.addFile("dir/file3.txt", 123, "3432434534534534")
|
---|
[36] | 633 |
|
---|
[37] | 634 | # with open("manifest1", "wt") as f:
|
---|
| 635 | # manifest1.writeInto(f)
|
---|
[36] | 636 |
|
---|
[37] | 637 | # manifest2 = Manifest()
|
---|
| 638 | # manifest2.addFile("file1.exe", 4353, "390734659834756349876")
|
---|
| 639 | # manifest2.addFile("dir/file2.zip", 45645, "347893245873456987")
|
---|
| 640 | # manifest2.addFile("dir/file4.log", 2390, "56546546546546")
|
---|
[36] | 641 |
|
---|
[37] | 642 | # with open("manifest2", "wt") as f:
|
---|
| 643 | # manifest2.writeInto(f)
|
---|
[36] | 644 |
|
---|
[37] | 645 | # manifest1 = Manifest()
|
---|
| 646 | # with open("manifest1", "rt") as f:
|
---|
| 647 | # manifest1.readFrom(f)
|
---|
[36] | 648 |
|
---|
[37] | 649 | # manifest2 = Manifest()
|
---|
| 650 | # with open("manifest2", "rt") as f:
|
---|
| 651 | # manifest2.readFrom(f)
|
---|
[36] | 652 |
|
---|
[37] | 653 | # (modifiedAndNew, removed) = manifest1.compare(manifest2)
|
---|
[36] | 654 |
|
---|
[37] | 655 | # for (path, size, sum) in modifiedAndNew:
|
---|
| 656 | # print "modified or new:", path, size, sum
|
---|
[36] | 657 |
|
---|
[37] | 658 | # for path in removed:
|
---|
| 659 | # print "removed:", path
|
---|
[36] | 660 |
|
---|
| 661 | #------------------------------------------------------------------------------
|
---|