summaryrefslogtreecommitdiff
path: root/pwnlib/update.py
blob: dd8f0ed8a1c0d0d51cea3239f969a1987e639a58 (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
"""
# Pwntools Update

In order to ensure that Pwntools users always have the latest and
greatest version, Pwntools automatically checks for updates.

Since this update check takes a moment, it is only performed once
every week.  It can be permanently disabled via:

::

    $ echo never > ~/.cache/.pwntools-cache-*/update

Or adding the following lines to ~/.pwn.conf (or system-wide /etc/pwn.conf):

::

    [update]
    interval=never

"""
from __future__ import absolute_import
from __future__ import division

import datetime
import json
import os
import time

import packaging.version

from pwnlib.args import args
from pwnlib.config import register_config
from pwnlib.context import context
from pwnlib.log import getLogger
from pwnlib.util.misc import read
from pwnlib.util.misc import write
from pwnlib.util.web import wget
from pwnlib.version import __version__

log = getLogger(__name__)

current_version = packaging.version.Version(__version__)
package_name    = 'pwntools'
package_repo    = 'Gallopsled/pwntools'
update_freq     = datetime.timedelta(days=7).total_seconds()
disabled        = False

def read_update_config(settings):
    for key, value in settings.items():
        if key == 'interval':
            if value == 'never':
                global disabled
                disabled = True
            else:
                try:
                    value = int(value)
                except ValueError:
                    log.warn("Wrong value")
                else:
                    global update_freq
                    update_freq = datetime.timedelta(days=value).total_seconds()
        else:
            log.warn("Unknown configuration option %r in section %r" % (key, 'update'))

register_config('update', read_update_config)

def available_on_pypi(prerelease=current_version.is_prerelease):
    """Return True if an update is available on PyPI.

    >>> available_on_pypi() # doctest: +ELLIPSIS
    <Version('...')>
    >>> available_on_pypi(prerelease=False).is_prerelease
    False
    """
    # Deferred import to save startup time
    from six.moves.xmlrpc_client import ServerProxy

    versions = getattr(available_on_pypi, 'cached', None)
    if versions is None:
        client = ServerProxy('https://pypi.python.org/pypi')
        versions = client.package_releases('pwntools', True)
        available_on_pypi.cached = versions

    versions = map(packaging.version.Version, versions)

    if not prerelease:
        versions = filter(lambda v: not v.is_prerelease, versions)

    return max(versions)

def cache_file():
    """Returns the path of the file used to cache update data, and ensures that it exists."""
    cache_dir = context.cache_dir

    if not cache_dir:
        return None

    cache_file = os.path.join(cache_dir, 'update')

    if not os.path.isdir(cache_dir):
        os.makedirs(cache_dir)

    if not os.path.exists(cache_file):
        write(cache_file, '')

    return cache_file

def last_check():
    """Return the date of the last check"""
    cache = cache_file()
    if cache:
        return os.path.getmtime(cache_file())

    # Fallback
    return time.time()

def should_check():
    """Return True if we should check for an update"""
    filename = cache_file()

    if not filename:
        return False

    if disabled or read(filename).strip() == b'never':
        return False

    return time.time() > (last_check() + update_freq)

def perform_check(prerelease=current_version.is_prerelease):
    """Perform the update check, and report to the user.

    Arguments:
        prerelease(bool): Whether or not to include pre-release versions.

    Returns:
        A list of arguments to the update command.

    >>> from packaging.version import Version
    >>> pwnlib.update.current_version = Version("999.0.0")
    >>> print(perform_check())
    None
    >>> pwnlib.update.current_version = Version("0.0.0")
    >>> perform_check() # doctest: +ELLIPSIS
    ['pip', 'install', '-U', ...]

    >>> def bail(*a): raise Exception()
    >>> pypi   = pwnlib.update.available_on_pypi

    >>> perform_check(prerelease=False)
    ['pip', 'install', '-U', 'pwntools']
    >>> perform_check(prerelease=True)  # doctest: +ELLIPSIS
    ['pip', 'install', '-U', 'pwntools...']
    """
    pypi = current_version
    try:
        pypi = available_on_pypi(prerelease)
    except Exception:
        log.warning("An issue occurred while checking PyPI")

    best = max(pypi, current_version)
    where = None
    command = None

    cache = cache_file()

    if cache:
        os.utime(cache, None)

    if best == current_version:
        log.info("You have the latest version of Pwntools (%s)" % best)
        return

    command = [
        'pip',
        'install',
        '-U'
    ]

    if best == pypi:
        where = 'pypi'
        pypi_package = package_name
        if best.is_prerelease:
            pypi_package += '==%s' % (best)
        command += [pypi_package]

    command_str = ' '.join(command)

    log.info("A newer version of %s is available on %s (%s --> %s).\n" % (package_name, where, current_version, best) +
             "Update with: $ %s" % command_str)

    return command

def check_automatically():
    xdg_config_home = os.environ.get('XDG_CONFIG_HOME') or "~/.config"

    if should_check():
        message  = ["Checking for new versions of %s" % package_name]
        message += ["To disable this functionality, set the contents of %s to 'never' (old way)." % cache_file()]
        message += ["Or add the following lines to ~/.pwn.conf or %s/pwn.conf (or /etc/pwn.conf system-wide):" % xdg_config_home]
        message += ["""\
    [update]
    interval=never"""]
        log.info("\n".join(message))
        perform_check()