Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Data overflow fixes #323

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions qrcode/console_scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ def raise_error(msg: str) -> NoReturn:
else:
qr.add_data(data, optimize=opts.optimize)

try:
qr.make()
except qrcode.exceptions.DataOverflowError:
raise_error("too much data to fit in QR code")

if opts.output:
img = qr.make_image()
with open(opts.output, "wb") as out:
Expand Down
9 changes: 5 additions & 4 deletions qrcode/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,8 @@ def make(self, fit=True):
:param fit: If ``True`` (or if a size has not been provided), find the
best fit for the data to avoid data overflow errors.
"""
if fit or (self.version is None):
self.best_fit(start=self.version)
if fit or (self._version is None):
self.best_fit(start=self._version)
if self.mask_pattern is None:
self.makeImpl(False, self.best_mask_pattern())
else:
Expand Down Expand Up @@ -229,11 +229,12 @@ def best_fit(self, start=None):
data.write(buffer)

needed_bits = len(buffer)
self.version = bisect_left(
new_version = bisect_left(
util.BIT_LIMIT_TABLE[self.error_correction], needed_bits, start
)
if self.version == 41:
if new_version == 41:
raise exceptions.DataOverflowError()
self.version = new_version

# Now check whether we need more bits for the mode sizes, recursing if
# our guess was too low
Expand Down
6 changes: 6 additions & 0 deletions qrcode/tests/test_qrcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,12 @@ def test_fit(self):
qr.make()
self.assertEqual(qr.version, 2)

def test_fit_overflow(self):
# Alphanumeric. Version 40 with ERROR_CORRECT_LOW has max 4296 characters.
qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_L)
qr.add_data("A" * 4297)
self.assertRaises(DataOverflowError, qr.make)

def test_mode_number(self):
qr = qrcode.QRCode()
qr.add_data("1234567890123456789012345678901234", optimize=0)
Expand Down