Issue #15989: Fix several occurrences of integer overflow
when result of PyInt_AsLong() or PyLong_AsLong() narrowed
to int without checks.

This is a backport of changesets 13e2e44db99d and 525407d89277.
diff --git a/Modules/_io/_iomodule.c b/Modules/_io/_iomodule.c
index d73dff2..a024d86 100644
--- a/Modules/_io/_iomodule.c
+++ b/Modules/_io/_iomodule.c
@@ -300,7 +300,8 @@
     int text = 0, binary = 0, universal = 0;
 
     char rawmode[5], *m;
-    int line_buffering, isatty;
+    int line_buffering;
+    long isatty;
 
     PyObject *raw, *modeobj = NULL, *buffer = NULL, *wrapper = NULL;
 
@@ -443,12 +444,12 @@
 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
         {
             struct stat st;
-            long fileno;
+            int fileno;
             PyObject *res = PyObject_CallMethod(raw, "fileno", NULL);
             if (res == NULL)
                 goto error;
 
-            fileno = PyInt_AsLong(res);
+            fileno = _PyInt_AsInt(res);
             Py_DECREF(res);
             if (fileno == -1 && PyErr_Occurred())
                 goto error;
diff --git a/Modules/_io/fileio.c b/Modules/_io/fileio.c
index 7fe2454..6cd7d81 100644
--- a/Modules/_io/fileio.c
+++ b/Modules/_io/fileio.c
@@ -211,7 +211,7 @@
         return -1;
     }
 
-    fd = PyLong_AsLong(nameobj);
+    fd = _PyLong_AsInt(nameobj);
     if (fd < 0) {
         if (!PyErr_Occurred()) {
             PyErr_SetString(PyExc_ValueError,