Skip to content

Commit b0ee2b4

Browse files
[3.9] bpo-42681: Fix range checks for color and pair numbers in curses (GH-23874). (GH-24077)
(cherry picked from commit 1470edd)
1 parent 0303008 commit b0ee2b4

File tree

5 files changed

+157
-61
lines changed

5 files changed

+157
-61
lines changed

Doc/library/curses.rst

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -112,14 +112,15 @@ The module :mod:`curses` defines the following functions:
112112
.. function:: color_content(color_number)
113113

114114
Return the intensity of the red, green, and blue (RGB) components in the color
115-
*color_number*, which must be between ``0`` and :const:`COLORS`. Return a 3-tuple,
115+
*color_number*, which must be between ``0`` and ``COLORS - 1``. Return a 3-tuple,
116116
containing the R,G,B values for the given color, which will be between
117117
``0`` (no component) and ``1000`` (maximum amount of component).
118118

119119

120-
.. function:: color_pair(color_number)
120+
.. function:: color_pair(pair_number)
121121

122-
Return the attribute value for displaying text in the specified color. This
122+
Return the attribute value for displaying text in the specified color pair.
123+
Only the first 256 color pairs are supported. This
123124
attribute value can be combined with :const:`A_STANDOUT`, :const:`A_REVERSE`,
124125
and the other :const:`A_\*` attributes. :func:`pair_number` is the counterpart
125126
to this function.
@@ -278,7 +279,7 @@ The module :mod:`curses` defines the following functions:
278279
Change the definition of a color, taking the number of the color to be changed
279280
followed by three RGB values (for the amounts of red, green, and blue
280281
components). The value of *color_number* must be between ``0`` and
281-
:const:`COLORS`. Each of *r*, *g*, *b*, must be a value between ``0`` and
282+
`COLORS - 1`. Each of *r*, *g*, *b*, must be a value between ``0`` and
282283
``1000``. When :func:`init_color` is used, all occurrences of that color on the
283284
screen immediately change to the new definition. This function is a no-op on
284285
most terminals; it is active only if :func:`can_change_color` returns ``True``.
@@ -291,7 +292,8 @@ The module :mod:`curses` defines the following functions:
291292
color number. The value of *pair_number* must be between ``1`` and
292293
``COLOR_PAIRS - 1`` (the ``0`` color pair is wired to white on black and cannot
293294
be changed). The value of *fg* and *bg* arguments must be between ``0`` and
294-
:const:`COLORS`. If the color-pair was previously initialized, the screen is
295+
``COLORS - 1``, or, after calling :func:`use_default_colors`, ``-1``.
296+
If the color-pair was previously initialized, the screen is
295297
refreshed and all occurrences of that color-pair are changed to the new
296298
definition.
297299

@@ -441,7 +443,7 @@ The module :mod:`curses` defines the following functions:
441443
.. function:: pair_content(pair_number)
442444

443445
Return a tuple ``(fg, bg)`` containing the colors for the requested color pair.
444-
The value of *pair_number* must be between ``1`` and ``COLOR_PAIRS - 1``.
446+
The value of *pair_number* must be between ``0`` and ``COLOR_PAIRS - 1``.
445447

446448

447449
.. function:: pair_number(attr)

Lib/test/test_curses.py

Lines changed: 119 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@
44
# This script doesn't actually display anything very coherent. but it
55
# does call (nearly) every method and function.
66
#
7-
# Functions not tested: {def,reset}_{shell,prog}_mode, getch(), getstr(),
8-
# init_color()
7+
# Functions not tested: {def,reset}_{shell,prog}_mode, getch(), getstr()
98
# Only called, not tested: getmouse(), ungetmouse()
109
#
1110

1211
import os
1312
import string
1413
import sys
1514
import tempfile
15+
import functools
1616
import unittest
1717

1818
from test.support import requires, import_module, verbose, SaveSignals
@@ -36,7 +36,17 @@ def requires_curses_func(name):
3636
return unittest.skipUnless(hasattr(curses, name),
3737
'requires curses.%s' % name)
3838

39+
def requires_colors(test):
40+
@functools.wraps(test)
41+
def wrapped(self, *args, **kwargs):
42+
if not curses.has_colors():
43+
self.skipTest('requires colors support')
44+
curses.start_color()
45+
test(self, *args, **kwargs)
46+
return wrapped
47+
3948
term = os.environ.get('TERM')
49+
SHORT_MAX = 0x7fff
4050

4151
# If newterm was supported we could use it instead of initscr and not exit
4252
@unittest.skipIf(not term or term == 'unknown',
@@ -47,6 +57,8 @@ class TestCurses(unittest.TestCase):
4757

4858
@classmethod
4959
def setUpClass(cls):
60+
if verbose:
61+
print(f'TERM={term}', file=sys.stderr, flush=True)
5062
# testing setupterm() inside initscr/endwin
5163
# causes terminal breakage
5264
stdout_fd = sys.__stdout__.fileno()
@@ -304,18 +316,111 @@ def test_module_funcs(self):
304316
curses.use_env(1)
305317

306318
# Functions only available on a few platforms
307-
def test_colors_funcs(self):
308-
if not curses.has_colors():
309-
self.skipTest('requires colors support')
310-
curses.start_color()
311-
curses.init_pair(2, 1,1)
312-
curses.color_content(1)
313-
curses.color_pair(2)
314-
curses.pair_content(min(curses.COLOR_PAIRS - 1, 0x7fff))
315-
curses.pair_number(0)
316-
317-
if hasattr(curses, 'use_default_colors'):
318-
curses.use_default_colors()
319+
320+
def bad_colors(self):
321+
return (-2**31 - 1, 2**31, -2**63 - 1, 2**63, 2**64)
322+
323+
def bad_pairs(self):
324+
return (-2**31 - 1, 2**31, -2**63 - 1, 2**63, 2**64)
325+
326+
@requires_colors
327+
def test_color_content(self):
328+
self.assertEqual(curses.color_content(curses.COLOR_BLACK), (0, 0, 0))
329+
curses.color_content(0)
330+
curses.color_content(min(curses.COLORS - 1, SHORT_MAX))
331+
332+
for color in self.bad_colors():
333+
self.assertRaises(OverflowError, curses.color_content, color)
334+
if curses.COLORS <= SHORT_MAX:
335+
self.assertRaises(curses.error, curses.color_content, curses.COLORS)
336+
self.assertRaises(curses.error, curses.color_content, -1)
337+
338+
@requires_colors
339+
def test_init_color(self):
340+
if not curses.can_change_color:
341+
self.skipTest('cannot change color')
342+
343+
old = curses.color_content(0)
344+
try:
345+
curses.init_color(0, *old)
346+
except curses.error:
347+
self.skipTest('cannot change color (init_color() failed)')
348+
self.addCleanup(curses.init_color, 0, *old)
349+
curses.init_color(0, 0, 0, 0)
350+
self.assertEqual(curses.color_content(0), (0, 0, 0))
351+
curses.init_color(0, 1000, 1000, 1000)
352+
self.assertEqual(curses.color_content(0), (1000, 1000, 1000))
353+
354+
maxcolor = min(curses.COLORS - 1, SHORT_MAX)
355+
old = curses.color_content(maxcolor)
356+
curses.init_color(maxcolor, *old)
357+
self.addCleanup(curses.init_color, maxcolor, *old)
358+
curses.init_color(maxcolor, 0, 500, 1000)
359+
self.assertEqual(curses.color_content(maxcolor), (0, 500, 1000))
360+
361+
for color in self.bad_colors():
362+
self.assertRaises(OverflowError, curses.init_color, color, 0, 0, 0)
363+
if curses.COLORS <= SHORT_MAX:
364+
self.assertRaises(curses.error, curses.init_color, curses.COLORS, 0, 0, 0)
365+
self.assertRaises(curses.error, curses.init_color, -1, 0, 0, 0)
366+
for comp in (-1, 1001):
367+
self.assertRaises(curses.error, curses.init_color, 0, comp, 0, 0)
368+
self.assertRaises(curses.error, curses.init_color, 0, 0, comp, 0)
369+
self.assertRaises(curses.error, curses.init_color, 0, 0, 0, comp)
370+
371+
@requires_colors
372+
def test_pair_content(self):
373+
if not hasattr(curses, 'use_default_colors'):
374+
self.assertEqual(curses.pair_content(0),
375+
(curses.COLOR_WHITE, curses.COLOR_BLACK))
376+
curses.pair_content(0)
377+
curses.pair_content(min(curses.COLOR_PAIRS - 1, SHORT_MAX))
378+
379+
for pair in self.bad_pairs():
380+
self.assertRaises(OverflowError, curses.pair_content, pair)
381+
self.assertRaises(curses.error, curses.pair_content, -1)
382+
383+
@requires_colors
384+
def test_init_pair(self):
385+
old = curses.pair_content(1)
386+
curses.init_pair(1, *old)
387+
self.addCleanup(curses.init_pair, 1, *old)
388+
389+
curses.init_pair(1, 0, 0)
390+
self.assertEqual(curses.pair_content(1), (0, 0))
391+
maxcolor = min(curses.COLORS - 1, SHORT_MAX)
392+
curses.init_pair(1, maxcolor, maxcolor)
393+
self.assertEqual(curses.pair_content(1), (maxcolor, maxcolor))
394+
maxpair = min(curses.COLOR_PAIRS - 1, SHORT_MAX)
395+
curses.init_pair(maxpair, 2, 3)
396+
self.assertEqual(curses.pair_content(maxpair), (2, 3))
397+
398+
for pair in self.bad_pairs():
399+
self.assertRaises(OverflowError, curses.init_pair, pair, 0, 0)
400+
self.assertRaises(curses.error, curses.init_pair, -1, 0, 0)
401+
for color in self.bad_colors():
402+
self.assertRaises(OverflowError, curses.init_pair, 1, color, 0)
403+
self.assertRaises(OverflowError, curses.init_pair, 1, 0, color)
404+
if curses.COLORS <= SHORT_MAX:
405+
self.assertRaises(curses.error, curses.init_pair, 1, curses.COLORS, 0)
406+
self.assertRaises(curses.error, curses.init_pair, 1, 0, curses.COLORS)
407+
408+
@requires_colors
409+
def test_color_attrs(self):
410+
for pair in 0, 1, 255:
411+
attr = curses.color_pair(pair)
412+
self.assertEqual(curses.pair_number(attr), pair, attr)
413+
self.assertEqual(curses.pair_number(attr | curses.A_BOLD), pair)
414+
self.assertEqual(curses.color_pair(0), 0)
415+
self.assertEqual(curses.pair_number(0), 0)
416+
417+
@requires_curses_func('use_default_colors')
418+
@requires_colors
419+
def test_use_default_colors(self):
420+
self.assertIn(curses.pair_content(0),
421+
((curses.COLOR_WHITE, curses.COLOR_BLACK), (-1, -1)))
422+
curses.use_default_colors()
423+
self.assertEqual(curses.pair_content(0), (-1, -1))
319424

320425
@requires_curses_func('keyname')
321426
def test_keyname(self):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed range checks for color and pair numbers in :mod:`curses`.

Modules/_cursesmodule.c

Lines changed: 16 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -176,18 +176,6 @@ static char *screen_encoding = NULL;
176176

177177
/* Utility Functions */
178178

179-
static inline int
180-
color_pair_to_attr(short color_number)
181-
{
182-
return ((int)color_number << 8);
183-
}
184-
185-
static inline short
186-
attr_to_color_pair(int attr)
187-
{
188-
return (short)((attr & A_COLOR) >> 8);
189-
}
190-
191179
/*
192180
* Check the return code from a curses function and return None
193181
* or raise an exception as appropriate. These are exported using the
@@ -618,7 +606,7 @@ _curses_window_addch_impl(PyCursesWindowObject *self, int group_left_1,
618606
if (type == 2) {
619607
funcname = "add_wch";
620608
wstr[1] = L'\0';
621-
setcchar(&wcval, wstr, attr, attr_to_color_pair(attr), NULL);
609+
setcchar(&wcval, wstr, attr, PAIR_NUMBER(attr), NULL);
622610
if (coordinates_group)
623611
rtn = mvwadd_wch(self->win,y,x, &wcval);
624612
else {
@@ -2586,7 +2574,7 @@ NoArgOrFlagNoReturnFunctionBody(cbreak, flag)
25862574
_curses.color_content
25872575
25882576
color_number: short
2589-
The number of the color (0 - COLORS).
2577+
The number of the color (0 - (COLORS-1)).
25902578
/
25912579
25922580
Return the red, green, and blue (RGB) components of the specified color.
@@ -2597,7 +2585,7 @@ which will be between 0 (no component) and 1000 (maximum amount of component).
25972585

25982586
static PyObject *
25992587
_curses_color_content_impl(PyObject *module, short color_number)
2600-
/*[clinic end generated code: output=cb15cf3120d4bfc1 input=5555abb1c11e11b7]*/
2588+
/*[clinic end generated code: output=cb15cf3120d4bfc1 input=630f6737514db6ad]*/
26012589
{
26022590
short r,g,b;
26032591

@@ -2616,8 +2604,8 @@ _curses_color_content_impl(PyObject *module, short color_number)
26162604
/*[clinic input]
26172605
_curses.color_pair
26182606
2619-
color_number: short
2620-
The number of the color (0 - COLORS).
2607+
pair_number: short
2608+
The number of the color pair.
26212609
/
26222610
26232611
Return the attribute value for displaying text in the specified color.
@@ -2627,13 +2615,13 @@ other A_* attributes. pair_number() is the counterpart to this function.
26272615
[clinic start generated code]*/
26282616

26292617
static PyObject *
2630-
_curses_color_pair_impl(PyObject *module, short color_number)
2631-
/*[clinic end generated code: output=6a84cb6b29ecaf9a input=a9d3eb6f50e4dc12]*/
2618+
_curses_color_pair_impl(PyObject *module, short pair_number)
2619+
/*[clinic end generated code: output=ce609d238b70dc11 input=8dd0d5da94cb15b5]*/
26322620
{
26332621
PyCursesInitialised;
26342622
PyCursesInitialisedColor;
26352623

2636-
return PyLong_FromLong(color_pair_to_attr(color_number));
2624+
return PyLong_FromLong(COLOR_PAIR(pair_number));
26372625
}
26382626

26392627
/*[clinic input]
@@ -3028,7 +3016,7 @@ _curses_has_key_impl(PyObject *module, int key)
30283016
_curses.init_color
30293017
30303018
color_number: short
3031-
The number of the color to be changed (0 - COLORS).
3019+
The number of the color to be changed (0 - (COLORS-1)).
30323020
r: short
30333021
Red component (0 - 1000).
30343022
g: short
@@ -3041,13 +3029,13 @@ Change the definition of a color.
30413029
30423030
When init_color() is used, all occurrences of that color on the screen
30433031
immediately change to the new definition. This function is a no-op on
3044-
most terminals; it is active only if can_change_color() returns 1.
3032+
most terminals; it is active only if can_change_color() returns true.
30453033
[clinic start generated code]*/
30463034

30473035
static PyObject *
30483036
_curses_init_color_impl(PyObject *module, short color_number, short r,
30493037
short g, short b)
3050-
/*[clinic end generated code: output=280236f5efe9776a input=f3a05bd38f619175]*/
3038+
/*[clinic end generated code: output=280236f5efe9776a input=128601b5dc76d548]*/
30513039
{
30523040
PyCursesInitialised;
30533041
PyCursesInitialisedColor;
@@ -3061,9 +3049,9 @@ _curses.init_pair
30613049
pair_number: short
30623050
The number of the color-pair to be changed (1 - (COLOR_PAIRS-1)).
30633051
fg: short
3064-
Foreground color number (0 - COLORS).
3052+
Foreground color number (-1 - (COLORS-1)).
30653053
bg: short
3066-
Background color number (0 - COLORS).
3054+
Background color number (-1 - (COLORS-1)).
30673055
/
30683056
30693057
Change the definition of a color-pair.
@@ -3075,7 +3063,7 @@ all occurrences of that color-pair are changed to the new definition.
30753063
static PyObject *
30763064
_curses_init_pair_impl(PyObject *module, short pair_number, short fg,
30773065
short bg)
3078-
/*[clinic end generated code: output=9c2ce39c22f376b6 input=c9f0b11b17a2ac6d]*/
3066+
/*[clinic end generated code: output=9c2ce39c22f376b6 input=12c320ec14396ea2]*/
30793067
{
30803068
PyCursesInitialised;
30813069
PyCursesInitialisedColor;
@@ -3715,7 +3703,7 @@ _curses_pair_content_impl(PyObject *module, short pair_number)
37153703

37163704
if (pair_content(pair_number, &f, &b)==ERR) {
37173705
PyErr_SetString(PyCursesError,
3718-
"Argument 1 was out of range. (1..COLOR_PAIRS-1)");
3706+
"Argument 1 was out of range. (0..COLOR_PAIRS-1)");
37193707
return NULL;
37203708
}
37213709

@@ -3740,7 +3728,7 @@ _curses_pair_number_impl(PyObject *module, int attr)
37403728
PyCursesInitialised;
37413729
PyCursesInitialisedColor;
37423730

3743-
return PyLong_FromLong(attr_to_color_pair(attr));
3731+
return PyLong_FromLong(PAIR_NUMBER(attr));
37443732
}
37453733

37463734
/*[clinic input]

0 commit comments

Comments
 (0)