Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- evalkit_llava/lib/cmake/liblzma/liblzma-config-version.cmake +70 -0
- evalkit_llava/lib/cmake/liblzma/liblzma-config.cmake +16 -0
- evalkit_llava/lib/cmake/liblzma/liblzma-targets-release.cmake +19 -0
- evalkit_llava/lib/cmake/liblzma/liblzma-targets.cmake +102 -0
- evalkit_llava/lib/engines-3/afalg.so +0 -0
- evalkit_llava/lib/engines-3/capi.so +0 -0
- evalkit_llava/lib/engines-3/loader_attic.so +0 -0
- evalkit_llava/lib/engines-3/padlock.so +0 -0
- evalkit_llava/lib/itcl4.2.4/itcl.tcl +151 -0
- evalkit_llava/lib/itcl4.2.4/itclConfig.sh +67 -0
- evalkit_llava/lib/itcl4.2.4/itclHullCmds.tcl +562 -0
- evalkit_llava/lib/itcl4.2.4/itclWidget.tcl +447 -0
- evalkit_llava/lib/itcl4.2.4/libitclstub4.2.4.a +0 -0
- evalkit_llava/lib/itcl4.2.4/pkgIndex.tcl +14 -0
- evalkit_llava/lib/libncursesw.so +3 -0
- evalkit_llava/lib/python3.10/ctypes/__pycache__/util.cpython-310.pyc +0 -0
- evalkit_llava/lib/python3.10/ctypes/__pycache__/wintypes.cpython-310.pyc +0 -0
- evalkit_llava/lib/python3.10/dbm/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_llava/lib/python3.10/dbm/__pycache__/dumb.cpython-310.pyc +0 -0
- evalkit_llava/lib/python3.10/dbm/__pycache__/gnu.cpython-310.pyc +0 -0
- evalkit_llava/lib/python3.10/dbm/__pycache__/ndbm.cpython-310.pyc +0 -0
- evalkit_llava/lib/python3.10/dbm/dumb.py +316 -0
- evalkit_llava/lib/python3.10/dbm/gnu.py +3 -0
- evalkit_llava/lib/python3.10/dbm/ndbm.py +3 -0
- evalkit_llava/lib/python3.10/http/__init__.py +150 -0
- evalkit_llava/lib/python3.10/http/__pycache__/cookiejar.cpython-310.pyc +0 -0
- evalkit_llava/lib/python3.10/http/__pycache__/server.cpython-310.pyc +0 -0
- evalkit_llava/lib/python3.10/http/client.py +1526 -0
- evalkit_llava/lib/python3.10/http/cookiejar.py +2125 -0
- evalkit_llava/lib/python3.10/http/cookies.py +594 -0
- evalkit_llava/lib/python3.10/http/server.py +1312 -0
- evalkit_llava/lib/python3.10/site-packages/setuptools/_vendor/more_itertools/__pycache__/more.cpython-310.pyc +3 -0
- evalkit_llava/lib/python3.10/venv/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_llava/lib/python3.10/venv/scripts/posix/activate.csh +26 -0
- evalkit_llava/lib/python3.10/wsgiref/__init__.py +23 -0
- evalkit_llava/lib/python3.10/wsgiref/simple_server.py +165 -0
- evalkit_llava/lib/python3.10/wsgiref/validate.py +441 -0
- evalkit_llava/lib/sqlite3.44.2/pkgIndex.tcl +12 -0
- evalkit_llava/lib/tcl8/8.4/platform-1.0.19.tm +450 -0
- evalkit_llava/lib/tcl8/8.4/platform/shell-1.1.4.tm +241 -0
- evalkit_llava/lib/tcl8/8.5/msgcat-1.6.1.tm +1210 -0
- evalkit_llava/lib/tcl8/8.5/tcltest-2.5.7.tm +0 -0
- evalkit_llava/lib/tcl8/8.6/http-2.9.8.tm +0 -0
- evalkit_llava/lib/tcl8/8.6/tdbc/sqlite3-1.1.7.tm +723 -0
- evalkit_llava/lib/tdbc1.1.7/libtdbc1.1.7.so +0 -0
- evalkit_llava/lib/tdbc1.1.7/libtdbcstub1.1.7.a +0 -0
- evalkit_llava/lib/tdbc1.1.7/pkgIndex.tcl +26 -0
- evalkit_llava/lib/tdbc1.1.7/tdbc.tcl +922 -0
- evalkit_llava/lib/tdbc1.1.7/tdbcConfig.sh +81 -0
.gitattributes
CHANGED
|
@@ -116,3 +116,5 @@ evalkit_llava/lib/libtinfow.so filter=lfs diff=lfs merge=lfs -text
|
|
| 116 |
evalkit_llava/lib/libncursesw.so.6 filter=lfs diff=lfs merge=lfs -text
|
| 117 |
evalkit_llava/lib/libreadline.so.8 filter=lfs diff=lfs merge=lfs -text
|
| 118 |
evalkit_llava/lib/libtinfow.so.6.4 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 116 |
evalkit_llava/lib/libncursesw.so.6 filter=lfs diff=lfs merge=lfs -text
|
| 117 |
evalkit_llava/lib/libreadline.so.8 filter=lfs diff=lfs merge=lfs -text
|
| 118 |
evalkit_llava/lib/libtinfow.so.6.4 filter=lfs diff=lfs merge=lfs -text
|
| 119 |
+
evalkit_llava/lib/libncursesw.so filter=lfs diff=lfs merge=lfs -text
|
| 120 |
+
evalkit_llava/lib/python3.10/site-packages/setuptools/_vendor/more_itertools/__pycache__/more.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
evalkit_llava/lib/cmake/liblzma/liblzma-config-version.cmake
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This is a basic version file for the Config-mode of find_package().
|
| 2 |
+
# It is used by write_basic_package_version_file() as input file for configure_file()
|
| 3 |
+
# to create a version-file which can be installed along a config.cmake file.
|
| 4 |
+
#
|
| 5 |
+
# The created file sets PACKAGE_VERSION_EXACT if the current version string and
|
| 6 |
+
# the requested version string are exactly the same and it sets
|
| 7 |
+
# PACKAGE_VERSION_COMPATIBLE if the current version is >= requested version,
|
| 8 |
+
# but only if the requested major version is the same as the current one.
|
| 9 |
+
# The variable CVF_VERSION must be set before calling configure_file().
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
set(PACKAGE_VERSION "5.6.4")
|
| 13 |
+
|
| 14 |
+
if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
|
| 15 |
+
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
| 16 |
+
else()
|
| 17 |
+
|
| 18 |
+
if("5.6.4" MATCHES "^([0-9]+)\\.")
|
| 19 |
+
set(CVF_VERSION_MAJOR "${CMAKE_MATCH_1}")
|
| 20 |
+
if(NOT CVF_VERSION_MAJOR VERSION_EQUAL 0)
|
| 21 |
+
string(REGEX REPLACE "^0+" "" CVF_VERSION_MAJOR "${CVF_VERSION_MAJOR}")
|
| 22 |
+
endif()
|
| 23 |
+
else()
|
| 24 |
+
set(CVF_VERSION_MAJOR "5.6.4")
|
| 25 |
+
endif()
|
| 26 |
+
|
| 27 |
+
if(PACKAGE_FIND_VERSION_RANGE)
|
| 28 |
+
# both endpoints of the range must have the expected major version
|
| 29 |
+
math (EXPR CVF_VERSION_MAJOR_NEXT "${CVF_VERSION_MAJOR} + 1")
|
| 30 |
+
if (NOT PACKAGE_FIND_VERSION_MIN_MAJOR STREQUAL CVF_VERSION_MAJOR
|
| 31 |
+
OR ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND NOT PACKAGE_FIND_VERSION_MAX_MAJOR STREQUAL CVF_VERSION_MAJOR)
|
| 32 |
+
OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND NOT PACKAGE_FIND_VERSION_MAX VERSION_LESS_EQUAL CVF_VERSION_MAJOR_NEXT)))
|
| 33 |
+
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
| 34 |
+
elseif(PACKAGE_FIND_VERSION_MIN_MAJOR STREQUAL CVF_VERSION_MAJOR
|
| 35 |
+
AND ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_LESS_EQUAL PACKAGE_FIND_VERSION_MAX)
|
| 36 |
+
OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MAX)))
|
| 37 |
+
set(PACKAGE_VERSION_COMPATIBLE TRUE)
|
| 38 |
+
else()
|
| 39 |
+
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
| 40 |
+
endif()
|
| 41 |
+
else()
|
| 42 |
+
if(PACKAGE_FIND_VERSION_MAJOR STREQUAL CVF_VERSION_MAJOR)
|
| 43 |
+
set(PACKAGE_VERSION_COMPATIBLE TRUE)
|
| 44 |
+
else()
|
| 45 |
+
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
| 46 |
+
endif()
|
| 47 |
+
|
| 48 |
+
if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
|
| 49 |
+
set(PACKAGE_VERSION_EXACT TRUE)
|
| 50 |
+
endif()
|
| 51 |
+
endif()
|
| 52 |
+
endif()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# if the installed project requested no architecture check, don't perform the check
|
| 56 |
+
if("FALSE")
|
| 57 |
+
return()
|
| 58 |
+
endif()
|
| 59 |
+
|
| 60 |
+
# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it:
|
| 61 |
+
if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "8" STREQUAL "")
|
| 62 |
+
return()
|
| 63 |
+
endif()
|
| 64 |
+
|
| 65 |
+
# check that the installed version has the same 32/64bit-ness as the one which is currently searching:
|
| 66 |
+
if(NOT CMAKE_SIZEOF_VOID_P STREQUAL "8")
|
| 67 |
+
math(EXPR installedBits "8 * 8")
|
| 68 |
+
set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)")
|
| 69 |
+
set(PACKAGE_VERSION_UNSUITABLE TRUE)
|
| 70 |
+
endif()
|
evalkit_llava/lib/cmake/liblzma/liblzma-config.cmake
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
include(CMakeFindDependencyMacro)
|
| 2 |
+
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
|
| 3 |
+
find_dependency(Threads)
|
| 4 |
+
|
| 5 |
+
include("${CMAKE_CURRENT_LIST_DIR}/liblzma-targets.cmake")
|
| 6 |
+
|
| 7 |
+
if(NOT TARGET LibLZMA::LibLZMA)
|
| 8 |
+
# Be compatible with the spelling used by the FindLibLZMA module. This
|
| 9 |
+
# doesn't use ALIAS because it would make CMake resolve LibLZMA::LibLZMA
|
| 10 |
+
# to liblzma::liblzma instead of keeping the original spelling. Keeping
|
| 11 |
+
# the original spelling is important for good FindLibLZMA compatibility.
|
| 12 |
+
add_library(LibLZMA::LibLZMA INTERFACE IMPORTED)
|
| 13 |
+
set_target_properties(LibLZMA::LibLZMA PROPERTIES
|
| 14 |
+
INTERFACE_LINK_LIBRARIES liblzma::liblzma)
|
| 15 |
+
endif()
|
| 16 |
+
|
evalkit_llava/lib/cmake/liblzma/liblzma-targets-release.cmake
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#----------------------------------------------------------------
|
| 2 |
+
# Generated CMake target import file for configuration "Release".
|
| 3 |
+
#----------------------------------------------------------------
|
| 4 |
+
|
| 5 |
+
# Commands may need to know the format version.
|
| 6 |
+
set(CMAKE_IMPORT_FILE_VERSION 1)
|
| 7 |
+
|
| 8 |
+
# Import target "liblzma::liblzma" for configuration "Release"
|
| 9 |
+
set_property(TARGET liblzma::liblzma APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
|
| 10 |
+
set_target_properties(liblzma::liblzma PROPERTIES
|
| 11 |
+
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/liblzma.so.5.6.4"
|
| 12 |
+
IMPORTED_SONAME_RELEASE "liblzma.so.5"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
list(APPEND _cmake_import_check_targets liblzma::liblzma )
|
| 16 |
+
list(APPEND _cmake_import_check_files_for_liblzma::liblzma "${_IMPORT_PREFIX}/lib/liblzma.so.5.6.4" )
|
| 17 |
+
|
| 18 |
+
# Commands beyond this point should not need to know the version.
|
| 19 |
+
set(CMAKE_IMPORT_FILE_VERSION)
|
evalkit_llava/lib/cmake/liblzma/liblzma-targets.cmake
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Generated by CMake
|
| 2 |
+
|
| 3 |
+
if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.8)
|
| 4 |
+
message(FATAL_ERROR "CMake >= 2.8.0 required")
|
| 5 |
+
endif()
|
| 6 |
+
if(CMAKE_VERSION VERSION_LESS "2.8.3")
|
| 7 |
+
message(FATAL_ERROR "CMake >= 2.8.3 required")
|
| 8 |
+
endif()
|
| 9 |
+
cmake_policy(PUSH)
|
| 10 |
+
cmake_policy(VERSION 2.8.3...3.23)
|
| 11 |
+
#----------------------------------------------------------------
|
| 12 |
+
# Generated CMake target import file.
|
| 13 |
+
#----------------------------------------------------------------
|
| 14 |
+
|
| 15 |
+
# Commands may need to know the format version.
|
| 16 |
+
set(CMAKE_IMPORT_FILE_VERSION 1)
|
| 17 |
+
|
| 18 |
+
# Protect against multiple inclusion, which would fail when already imported targets are added once more.
|
| 19 |
+
set(_cmake_targets_defined "")
|
| 20 |
+
set(_cmake_targets_not_defined "")
|
| 21 |
+
set(_cmake_expected_targets "")
|
| 22 |
+
foreach(_cmake_expected_target IN ITEMS liblzma::liblzma)
|
| 23 |
+
list(APPEND _cmake_expected_targets "${_cmake_expected_target}")
|
| 24 |
+
if(TARGET "${_cmake_expected_target}")
|
| 25 |
+
list(APPEND _cmake_targets_defined "${_cmake_expected_target}")
|
| 26 |
+
else()
|
| 27 |
+
list(APPEND _cmake_targets_not_defined "${_cmake_expected_target}")
|
| 28 |
+
endif()
|
| 29 |
+
endforeach()
|
| 30 |
+
unset(_cmake_expected_target)
|
| 31 |
+
if(_cmake_targets_defined STREQUAL _cmake_expected_targets)
|
| 32 |
+
unset(_cmake_targets_defined)
|
| 33 |
+
unset(_cmake_targets_not_defined)
|
| 34 |
+
unset(_cmake_expected_targets)
|
| 35 |
+
unset(CMAKE_IMPORT_FILE_VERSION)
|
| 36 |
+
cmake_policy(POP)
|
| 37 |
+
return()
|
| 38 |
+
endif()
|
| 39 |
+
if(NOT _cmake_targets_defined STREQUAL "")
|
| 40 |
+
string(REPLACE ";" ", " _cmake_targets_defined_text "${_cmake_targets_defined}")
|
| 41 |
+
string(REPLACE ";" ", " _cmake_targets_not_defined_text "${_cmake_targets_not_defined}")
|
| 42 |
+
message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_cmake_targets_defined_text}\nTargets not yet defined: ${_cmake_targets_not_defined_text}\n")
|
| 43 |
+
endif()
|
| 44 |
+
unset(_cmake_targets_defined)
|
| 45 |
+
unset(_cmake_targets_not_defined)
|
| 46 |
+
unset(_cmake_expected_targets)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# Compute the installation prefix relative to this file.
|
| 50 |
+
get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH)
|
| 51 |
+
get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
|
| 52 |
+
get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
|
| 53 |
+
get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
|
| 54 |
+
if(_IMPORT_PREFIX STREQUAL "/")
|
| 55 |
+
set(_IMPORT_PREFIX "")
|
| 56 |
+
endif()
|
| 57 |
+
|
| 58 |
+
# Create imported target liblzma::liblzma
|
| 59 |
+
add_library(liblzma::liblzma SHARED IMPORTED)
|
| 60 |
+
|
| 61 |
+
set_target_properties(liblzma::liblzma PROPERTIES
|
| 62 |
+
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
# Load information for each installed configuration.
|
| 66 |
+
file(GLOB _cmake_config_files "${CMAKE_CURRENT_LIST_DIR}/liblzma-targets-*.cmake")
|
| 67 |
+
foreach(_cmake_config_file IN LISTS _cmake_config_files)
|
| 68 |
+
include("${_cmake_config_file}")
|
| 69 |
+
endforeach()
|
| 70 |
+
unset(_cmake_config_file)
|
| 71 |
+
unset(_cmake_config_files)
|
| 72 |
+
|
| 73 |
+
# Cleanup temporary variables.
|
| 74 |
+
set(_IMPORT_PREFIX)
|
| 75 |
+
|
| 76 |
+
# Loop over all imported files and verify that they actually exist
|
| 77 |
+
foreach(_cmake_target IN LISTS _cmake_import_check_targets)
|
| 78 |
+
foreach(_cmake_file IN LISTS "_cmake_import_check_files_for_${_cmake_target}")
|
| 79 |
+
if(NOT EXISTS "${_cmake_file}")
|
| 80 |
+
message(FATAL_ERROR "The imported target \"${_cmake_target}\" references the file
|
| 81 |
+
\"${_cmake_file}\"
|
| 82 |
+
but this file does not exist. Possible reasons include:
|
| 83 |
+
* The file was deleted, renamed, or moved to another location.
|
| 84 |
+
* An install or uninstall procedure did not complete successfully.
|
| 85 |
+
* The installation package was faulty and contained
|
| 86 |
+
\"${CMAKE_CURRENT_LIST_FILE}\"
|
| 87 |
+
but not all the files it references.
|
| 88 |
+
")
|
| 89 |
+
endif()
|
| 90 |
+
endforeach()
|
| 91 |
+
unset(_cmake_file)
|
| 92 |
+
unset("_cmake_import_check_files_for_${_cmake_target}")
|
| 93 |
+
endforeach()
|
| 94 |
+
unset(_cmake_target)
|
| 95 |
+
unset(_cmake_import_check_targets)
|
| 96 |
+
|
| 97 |
+
# This file does not depend on other imported targets which have
|
| 98 |
+
# been exported from the same project but in a separate export set.
|
| 99 |
+
|
| 100 |
+
# Commands beyond this point should not need to know the version.
|
| 101 |
+
set(CMAKE_IMPORT_FILE_VERSION)
|
| 102 |
+
cmake_policy(POP)
|
evalkit_llava/lib/engines-3/afalg.so
ADDED
|
Binary file (15 kB). View file
|
|
|
evalkit_llava/lib/engines-3/capi.so
ADDED
|
Binary file (15.1 kB). View file
|
|
|
evalkit_llava/lib/engines-3/loader_attic.so
ADDED
|
Binary file (60.5 kB). View file
|
|
|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#
|
| 2 |
+
# itcl.tcl
|
| 3 |
+
# ----------------------------------------------------------------------
|
| 4 |
+
# Invoked automatically upon startup to customize the interpreter
|
| 5 |
+
# for [incr Tcl].
|
| 6 |
+
# ----------------------------------------------------------------------
|
| 7 |
+
# AUTHOR: Michael J. McLennan
|
| 8 |
+
# Bell Labs Innovations for Lucent Technologies
|
| 9 | |
| 10 |
+
# http://www.tcltk.com/itcl
|
| 11 |
+
# ----------------------------------------------------------------------
|
| 12 |
+
# Copyright (c) 1993-1998 Lucent Technologies, Inc.
|
| 13 |
+
# ======================================================================
|
| 14 |
+
# See the file "license.terms" for information on usage and
|
| 15 |
+
# redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
|
| 16 |
+
|
| 17 |
+
proc ::itcl::delete_helper { name args } {
|
| 18 |
+
::itcl::delete object $name
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
# ----------------------------------------------------------------------
|
| 22 |
+
# USAGE: local <className> <objName> ?<arg> <arg>...?
|
| 23 |
+
#
|
| 24 |
+
# Creates a new object called <objName> in class <className>, passing
|
| 25 |
+
# the remaining <arg>'s to the constructor. Unlike the usual
|
| 26 |
+
# [incr Tcl] objects, however, an object created by this procedure
|
| 27 |
+
# will be automatically deleted when the local call frame is destroyed.
|
| 28 |
+
# This command is useful for creating objects that should only remain
|
| 29 |
+
# alive until a procedure exits.
|
| 30 |
+
# ----------------------------------------------------------------------
|
| 31 |
+
proc ::itcl::local {class name args} {
|
| 32 |
+
set ptr [uplevel [list $class $name] $args]
|
| 33 |
+
uplevel [list set itcl-local-$ptr $ptr]
|
| 34 |
+
set cmd [uplevel namespace which -command $ptr]
|
| 35 |
+
uplevel [list trace add variable itcl-local-$ptr unset \
|
| 36 |
+
"::itcl::delete_helper $cmd"]
|
| 37 |
+
return $ptr
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
# ----------------------------------------------------------------------
|
| 41 |
+
# auto_mkindex
|
| 42 |
+
# ----------------------------------------------------------------------
|
| 43 |
+
# Define Itcl commands that will be recognized by the auto_mkindex
|
| 44 |
+
# parser in Tcl...
|
| 45 |
+
#
|
| 46 |
+
|
| 47 |
+
#
|
| 48 |
+
# USAGE: itcl::class name body
|
| 49 |
+
# Adds an entry for the given class declaration.
|
| 50 |
+
#
|
| 51 |
+
foreach __cmd {itcl::class class itcl::type type ictl::widget widget itcl::widgetadaptor widgetadaptor itcl::extendedclass extendedclass} {
|
| 52 |
+
auto_mkindex_parser::command $__cmd {name body} {
|
| 53 |
+
variable index
|
| 54 |
+
variable scriptFile
|
| 55 |
+
append index "set [list auto_index([fullname $name])]"
|
| 56 |
+
append index " \[list source \[file join \$dir [list $scriptFile]\]\]\n"
|
| 57 |
+
|
| 58 |
+
variable parser
|
| 59 |
+
variable contextStack
|
| 60 |
+
set contextStack [linsert $contextStack 0 $name]
|
| 61 |
+
$parser eval $body
|
| 62 |
+
set contextStack [lrange $contextStack 1 end]
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
#
|
| 67 |
+
# USAGE: itcl::body name arglist body
|
| 68 |
+
# Adds an entry for the given method/proc body.
|
| 69 |
+
#
|
| 70 |
+
foreach __cmd {itcl::body body} {
|
| 71 |
+
auto_mkindex_parser::command $__cmd {name arglist body} {
|
| 72 |
+
variable index
|
| 73 |
+
variable scriptFile
|
| 74 |
+
append index "set [list auto_index([fullname $name])]"
|
| 75 |
+
append index " \[list source \[file join \$dir [list $scriptFile]\]\]\n"
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
#
|
| 80 |
+
# USAGE: itcl::configbody name arglist body
|
| 81 |
+
# Adds an entry for the given method/proc body.
|
| 82 |
+
#
|
| 83 |
+
foreach __cmd {itcl::configbody configbody} {
|
| 84 |
+
auto_mkindex_parser::command $__cmd {name body} {
|
| 85 |
+
variable index
|
| 86 |
+
variable scriptFile
|
| 87 |
+
append index "set [list auto_index([fullname $name])]"
|
| 88 |
+
append index " \[list source \[file join \$dir [list $scriptFile]\]\]\n"
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
#
|
| 93 |
+
# USAGE: ensemble name ?body?
|
| 94 |
+
# Adds an entry to the auto index list for the given ensemble name.
|
| 95 |
+
#
|
| 96 |
+
foreach __cmd {itcl::ensemble ensemble} {
|
| 97 |
+
auto_mkindex_parser::command $__cmd {name {body ""}} {
|
| 98 |
+
variable index
|
| 99 |
+
variable scriptFile
|
| 100 |
+
append index "set [list auto_index([fullname $name])]"
|
| 101 |
+
append index " \[list source \[file join \$dir [list $scriptFile]\]\]\n"
|
| 102 |
+
}
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
#
|
| 106 |
+
# USAGE: public arg ?arg arg...?
|
| 107 |
+
# protected arg ?arg arg...?
|
| 108 |
+
# private arg ?arg arg...?
|
| 109 |
+
#
|
| 110 |
+
# Evaluates the arguments as commands, so we can recognize proc
|
| 111 |
+
# declarations within classes.
|
| 112 |
+
#
|
| 113 |
+
foreach __cmd {public protected private} {
|
| 114 |
+
auto_mkindex_parser::command $__cmd {args} {
|
| 115 |
+
variable parser
|
| 116 |
+
$parser eval $args
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
# SF bug #246 unset variable __cmd to avoid problems in user programs!!
|
| 121 |
+
unset __cmd
|
| 122 |
+
|
| 123 |
+
# ----------------------------------------------------------------------
|
| 124 |
+
# auto_import
|
| 125 |
+
# ----------------------------------------------------------------------
|
| 126 |
+
# This procedure overrides the usual "auto_import" function in the
|
| 127 |
+
# Tcl library. It is invoked during "namespace import" to make see
|
| 128 |
+
# if the imported commands reside in an autoloaded library. If so,
|
| 129 |
+
# stubs are created to represent the commands. Executing a stub
|
| 130 |
+
# later on causes the real implementation to be autoloaded.
|
| 131 |
+
#
|
| 132 |
+
# Arguments -
|
| 133 |
+
# pattern The pattern of commands being imported (like "foo::*")
|
| 134 |
+
# a canonical namespace as returned by [namespace current]
|
| 135 |
+
|
| 136 |
+
proc auto_import {pattern} {
|
| 137 |
+
global auto_index
|
| 138 |
+
|
| 139 |
+
set ns [uplevel namespace current]
|
| 140 |
+
set patternList [auto_qualify $pattern $ns]
|
| 141 |
+
|
| 142 |
+
auto_load_index
|
| 143 |
+
|
| 144 |
+
foreach pattern $patternList {
|
| 145 |
+
foreach name [array names auto_index $pattern] {
|
| 146 |
+
if {"" == [info commands $name]} {
|
| 147 |
+
::itcl::import::stub create $name
|
| 148 |
+
}
|
| 149 |
+
}
|
| 150 |
+
}
|
| 151 |
+
}
|
evalkit_llava/lib/itcl4.2.4/itclConfig.sh
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# itclConfig.sh --
|
| 2 |
+
#
|
| 3 |
+
# This shell script (for sh) is generated automatically by Itcl's
|
| 4 |
+
# configure script. It will create shell variables for most of
|
| 5 |
+
# the configuration options discovered by the configure script.
|
| 6 |
+
# This script is intended to be included by the configure scripts
|
| 7 |
+
# for Itcl extensions so that they don't have to figure this all
|
| 8 |
+
# out for themselves. This file does not duplicate information
|
| 9 |
+
# already provided by tclConfig.sh, so you may need to use that
|
| 10 |
+
# file in addition to this one.
|
| 11 |
+
#
|
| 12 |
+
# The information in this file is specific to a single platform.
|
| 13 |
+
|
| 14 |
+
# Itcl's version number.
|
| 15 |
+
itcl_VERSION='4.2.4'
|
| 16 |
+
ITCL_VERSION='4.2.4'
|
| 17 |
+
|
| 18 |
+
# The name of the Itcl library (may be either a .a file or a shared library):
|
| 19 |
+
itcl_LIB_FILE=libitcl4.2.4.so
|
| 20 |
+
ITCL_LIB_FILE=libitcl4.2.4.so
|
| 21 |
+
|
| 22 |
+
# String to pass to linker to pick up the Itcl library from its
|
| 23 |
+
# build directory.
|
| 24 |
+
itcl_BUILD_LIB_SPEC='-L/croot/tk_1714770549989/work/tcl8.6.14/unix/pkgs/itcl4.2.4 -litcl4.2.4'
|
| 25 |
+
ITCL_BUILD_LIB_SPEC='-L/croot/tk_1714770549989/work/tcl8.6.14/unix/pkgs/itcl4.2.4 -litcl4.2.4'
|
| 26 |
+
|
| 27 |
+
# String to pass to linker to pick up the Itcl library from its
|
| 28 |
+
# installed directory.
|
| 29 |
+
itcl_LIB_SPEC='-L/root/envs/evalkit_llava/lib/itcl4.2.4 -litcl4.2.4'
|
| 30 |
+
ITCL_LIB_SPEC='-L/root/envs/evalkit_llava/lib/itcl4.2.4 -litcl4.2.4'
|
| 31 |
+
|
| 32 |
+
# The name of the Itcl stub library (a .a file):
|
| 33 |
+
itcl_STUB_LIB_FILE=libitclstub4.2.4.a
|
| 34 |
+
ITCL_STUB_LIB_FILE=libitclstub4.2.4.a
|
| 35 |
+
|
| 36 |
+
# String to pass to linker to pick up the Itcl stub library from its
|
| 37 |
+
# build directory.
|
| 38 |
+
itcl_BUILD_STUB_LIB_SPEC='-L/croot/tk_1714770549989/work/tcl8.6.14/unix/pkgs/itcl4.2.4 -litclstub4.2.4'
|
| 39 |
+
ITCL_BUILD_STUB_LIB_SPEC='-L/croot/tk_1714770549989/work/tcl8.6.14/unix/pkgs/itcl4.2.4 -litclstub4.2.4'
|
| 40 |
+
|
| 41 |
+
# String to pass to linker to pick up the Itcl stub library from its
|
| 42 |
+
# installed directory.
|
| 43 |
+
itcl_STUB_LIB_SPEC='-L/root/envs/evalkit_llava/lib/itcl4.2.4 -litclstub4.2.4'
|
| 44 |
+
ITCL_STUB_LIB_SPEC='-L/root/envs/evalkit_llava/lib/itcl4.2.4 -litclstub4.2.4'
|
| 45 |
+
|
| 46 |
+
# String to pass to linker to pick up the Itcl stub library from its
|
| 47 |
+
# build directory.
|
| 48 |
+
itcl_BUILD_STUB_LIB_PATH='/croot/tk_1714770549989/work/tcl8.6.14/unix/pkgs/itcl4.2.4/libitclstub4.2.4.a'
|
| 49 |
+
ITCL_BUILD_STUB_LIB_PATH='/croot/tk_1714770549989/work/tcl8.6.14/unix/pkgs/itcl4.2.4/libitclstub4.2.4.a'
|
| 50 |
+
|
| 51 |
+
# String to pass to linker to pick up the Itcl stub library from its
|
| 52 |
+
# installed directory.
|
| 53 |
+
itcl_STUB_LIB_PATH='/root/envs/evalkit_llava/lib/itcl4.2.4/libitclstub4.2.4.a'
|
| 54 |
+
ITCL_STUB_LIB_PATH='/root/envs/evalkit_llava/lib/itcl4.2.4/libitclstub4.2.4.a'
|
| 55 |
+
|
| 56 |
+
# Location of the top-level source directories from which [incr Tcl]
|
| 57 |
+
# was built. This is the directory that contains generic, unix, etc.
|
| 58 |
+
# If [incr Tcl] was compiled in a different place than the directory
|
| 59 |
+
# containing the source files, this points to the location of the sources,
|
| 60 |
+
# not the location where [incr Tcl] was compiled.
|
| 61 |
+
itcl_SRC_DIR='/croot/tk_1714770549989/work/tcl8.6.14/pkgs/itcl4.2.4'
|
| 62 |
+
ITCL_SRC_DIR='/croot/tk_1714770549989/work/tcl8.6.14/pkgs/itcl4.2.4'
|
| 63 |
+
|
| 64 |
+
# String to pass to the compiler so that an extension can
|
| 65 |
+
# find installed Itcl headers.
|
| 66 |
+
itcl_INCLUDE_SPEC=''
|
| 67 |
+
ITCL_INCLUDE_SPEC=''
|
evalkit_llava/lib/itcl4.2.4/itclHullCmds.tcl
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# itclHullCmds.tcl
|
| 3 |
+
# ----------------------------------------------------------------------
|
| 4 |
+
# Invoked automatically upon startup to customize the interpreter
|
| 5 |
+
# for [incr Tcl] when one of setupcomponent or createhull is called.
|
| 6 |
+
# ----------------------------------------------------------------------
|
| 7 |
+
# AUTHOR: Arnulf P. Wiedemann
|
| 8 |
+
#
|
| 9 |
+
# ----------------------------------------------------------------------
|
| 10 |
+
# Copyright (c) 2008 Arnulf P. Wiedemann
|
| 11 |
+
# ======================================================================
|
| 12 |
+
# See the file "license.terms" for information on usage and
|
| 13 |
+
# redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
|
| 14 |
+
|
| 15 |
+
package require Tk 8.6 9
|
| 16 |
+
|
| 17 |
+
namespace eval ::itcl::internal::commands {
|
| 18 |
+
|
| 19 |
+
# ======================= widgetDeleted ===========================
|
| 20 |
+
|
| 21 |
+
proc widgetDeleted {oldName newName op} {
|
| 22 |
+
# The widget is beeing deleted, so we have to delete the object
|
| 23 |
+
# which had the widget as itcl_hull too!
|
| 24 |
+
# We have to get the real name from for example
|
| 25 |
+
# ::itcl::internal::widgets::hull1.lw
|
| 26 |
+
# we need only .lw here
|
| 27 |
+
|
| 28 |
+
#puts stderr "widgetDeleted!$oldName!$newName!$op!"
|
| 29 |
+
set cmdName [namespace tail $oldName]
|
| 30 |
+
set flds [split $cmdName {.}]
|
| 31 |
+
set cmdName .[join [lrange $flds 1 end] {.}]
|
| 32 |
+
#puts stderr "DELWIDGET![namespace current]!$cmdName![::info command $cmdName]!"
|
| 33 |
+
rename $cmdName {}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
namespace eval ::itcl::builtin {
|
| 39 |
+
|
| 40 |
+
# ======================= createhull ===========================
|
| 41 |
+
# the hull widget is a tk widget which is the (mega) widget handled behind the itcl
|
| 42 |
+
# extendedclass/itcl widget.
|
| 43 |
+
# It is created be renaming the itcl class object to a temporary name <itcl object name>_
|
| 44 |
+
# creating the widget with the
|
| 45 |
+
# appropriate options and the installing that as the "hull" widget (the container)
|
| 46 |
+
# All the options in args and the options delegated to component itcl_hull are used
|
| 47 |
+
# Then a unique name (hull_widget_name) in the itcl namespace is created for widget:
|
| 48 |
+
# ::itcl::internal::widgets::hull<unique number><namespace tail path>
|
| 49 |
+
# and widget is renamed to that name
|
| 50 |
+
# Finally the <itcl object name>_ is renamed to the original <itcl object name> again
|
| 51 |
+
# Component itcl_hull is created if not existent
|
| 52 |
+
# itcl_hull is set to the hull_widget_name and the <itcl object name>
|
| 53 |
+
# is returned to the caller
|
| 54 |
+
# ==============================================================
|
| 55 |
+
|
| 56 |
+
proc createhull {widget_type path args} {
|
| 57 |
+
variable hullCount
|
| 58 |
+
upvar this this
|
| 59 |
+
upvar win win
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
#puts stderr "il-1![::info level -1]!$this!"
|
| 63 |
+
#puts stderr "createhull!$widget_type!$path!$args!$this![::info command $this]!"
|
| 64 |
+
#puts stderr "ns1![uplevel 1 namespace current]!"
|
| 65 |
+
#puts stderr "ns2![uplevel 2 namespace current]!"
|
| 66 |
+
#puts stderr "ns3![uplevel 3 namespace current]!"
|
| 67 |
+
#puts stderr "level-1![::info level -1]!"
|
| 68 |
+
#puts stderr "level-2![::info level -2]!"
|
| 69 |
+
# set my_this [namespace tail $this]
|
| 70 |
+
set my_this $this
|
| 71 |
+
set tmp $my_this
|
| 72 |
+
#puts stderr "II![::info command $this]![::info command $tmp]!"
|
| 73 |
+
#puts stderr "rename1!rename $my_this ${tmp}_!"
|
| 74 |
+
rename ::$my_this ${tmp}_
|
| 75 |
+
set options [list]
|
| 76 |
+
foreach {option_name value} $args {
|
| 77 |
+
switch -glob -- $option_name {
|
| 78 |
+
-class {
|
| 79 |
+
lappend options $option_name [namespace tail $value]
|
| 80 |
+
}
|
| 81 |
+
-* {
|
| 82 |
+
lappend options $option_name $value
|
| 83 |
+
}
|
| 84 |
+
default {
|
| 85 |
+
return -code error "bad option name\"$option_name\" options must start with a \"-\""
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
set my_win [namespace tail $path]
|
| 90 |
+
set cmd [list $widget_type $my_win]
|
| 91 |
+
#puts stderr "my_win!$my_win!cmd!$cmd!$path!"
|
| 92 |
+
if {[llength $options] > 0} {
|
| 93 |
+
lappend cmd {*}$options
|
| 94 |
+
}
|
| 95 |
+
set widget [uplevel 1 $cmd]
|
| 96 |
+
#puts stderr "widget!$widget!"
|
| 97 |
+
trace add command $widget delete ::itcl::internal::commands::widgetDeleted
|
| 98 |
+
set opts [uplevel 1 info delegated options]
|
| 99 |
+
foreach entry $opts {
|
| 100 |
+
foreach {optName compName} $entry break
|
| 101 |
+
if {$compName eq "itcl_hull"} {
|
| 102 |
+
set optInfos [uplevel 1 info delegated option $optName]
|
| 103 |
+
set realOptName [lindex $optInfos 4]
|
| 104 |
+
# strip off the "-" at the beginning
|
| 105 |
+
set myOptName [string range $realOptName 1 end]
|
| 106 |
+
set my_opt_val [option get $my_win $myOptName *]
|
| 107 |
+
if {$my_opt_val ne ""} {
|
| 108 |
+
$my_win configure -$myOptName $my_opt_val
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
set idx 1
|
| 113 |
+
while {1} {
|
| 114 |
+
set widgetName ::itcl::internal::widgets::hull${idx}$my_win
|
| 115 |
+
#puts stderr "widgetName!$widgetName!"
|
| 116 |
+
if {[string length [::info command $widgetName]] == 0} {
|
| 117 |
+
break
|
| 118 |
+
}
|
| 119 |
+
incr idx
|
| 120 |
+
}
|
| 121 |
+
#puts stderr "rename2!rename $widget $widgetName!"
|
| 122 |
+
set dorename 0
|
| 123 |
+
rename $widget $widgetName
|
| 124 |
+
#puts stderr "rename3!rename ${tmp}_ $tmp![::info command ${tmp}_]!my_this!$my_this!"
|
| 125 |
+
rename ${tmp}_ ::$tmp
|
| 126 |
+
set exists [uplevel 1 ::info exists itcl_hull]
|
| 127 |
+
if {!$exists} {
|
| 128 |
+
# that does not yet work, beacause of problems with resolving
|
| 129 |
+
::itcl::addcomponent $my_this itcl_hull
|
| 130 |
+
}
|
| 131 |
+
upvar itcl_hull itcl_hull
|
| 132 |
+
::itcl::setcomponent $my_this itcl_hull $widgetName
|
| 133 |
+
#puts stderr "IC![::info command $my_win]!"
|
| 134 |
+
set exists [uplevel 1 ::info exists itcl_interior]
|
| 135 |
+
if {!$exists} {
|
| 136 |
+
# that does not yet work, beacause of problems with resolving
|
| 137 |
+
::itcl::addcomponent $this itcl_interior
|
| 138 |
+
}
|
| 139 |
+
upvar itcl_interior itcl_interior
|
| 140 |
+
set itcl_interior $my_win
|
| 141 |
+
#puts stderr "hull end!win!$win!itcl_hull!$itcl_hull!itcl_interior!$itcl_interior!"
|
| 142 |
+
return $my_win
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
# ======================= addToItclOptions ===========================
|
| 146 |
+
|
| 147 |
+
proc addToItclOptions {my_class my_win myOptions argsDict} {
|
| 148 |
+
upvar win win
|
| 149 |
+
upvar itcl_hull itcl_hull
|
| 150 |
+
|
| 151 |
+
set opt_lst [list configure]
|
| 152 |
+
foreach opt [lsort $myOptions] {
|
| 153 |
+
#puts stderr "IOPT!$opt!$my_class!$my_win![::itcl::is class $my_class]!"
|
| 154 |
+
set isClass [::itcl::is class $my_class]
|
| 155 |
+
set found 0
|
| 156 |
+
if {$isClass} {
|
| 157 |
+
if {[catch {
|
| 158 |
+
set resource [namespace eval $my_class info option $opt -resource]
|
| 159 |
+
set class [namespace eval $my_class info option $opt -class]
|
| 160 |
+
set default_val [uplevel 2 info option $opt -default]
|
| 161 |
+
set found 1
|
| 162 |
+
} msg]} {
|
| 163 |
+
# puts stderr "MSG!$opt!$my_class!$msg!"
|
| 164 |
+
}
|
| 165 |
+
} else {
|
| 166 |
+
set tmp_win [uplevel #0 $my_class .___xx]
|
| 167 |
+
|
| 168 |
+
set my_info [$tmp_win configure $opt]
|
| 169 |
+
set resource [lindex $my_info 1]
|
| 170 |
+
set class [lindex $my_info 2]
|
| 171 |
+
set default_val [lindex $my_info 3]
|
| 172 |
+
uplevel #0 destroy $tmp_win
|
| 173 |
+
set found 1
|
| 174 |
+
}
|
| 175 |
+
if {$found} {
|
| 176 |
+
if {[catch {
|
| 177 |
+
set val [uplevel #0 ::option get $win $resource $class]
|
| 178 |
+
} msg]} {
|
| 179 |
+
set val ""
|
| 180 |
+
}
|
| 181 |
+
if {[::dict exists $argsDict $opt]} {
|
| 182 |
+
# we have an explicitly set option
|
| 183 |
+
set val [::dict get $argsDict $opt]
|
| 184 |
+
} else {
|
| 185 |
+
if {[string length $val] == 0} {
|
| 186 |
+
set val $default_val
|
| 187 |
+
}
|
| 188 |
+
}
|
| 189 |
+
set ::itcl::internal::variables::${my_win}::itcl_options($opt) $val
|
| 190 |
+
set ::itcl::internal::variables::${my_win}::__itcl_option_infos($opt) [list $resource $class $default_val]
|
| 191 |
+
#puts stderr "OPT1!$opt!$val!"
|
| 192 |
+
# uplevel 1 [list set itcl_options($opt) [list $val]]
|
| 193 |
+
if {[catch {uplevel 1 $win configure $opt [list $val]} msg]} {
|
| 194 |
+
#puts stderr "addToItclOptions ERR!$msg!$my_class!$win!configure!$opt!$val!"
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
# ======================= setupcomponent ===========================
|
| 201 |
+
|
| 202 |
+
proc setupcomponent {comp using widget_type path args} {
|
| 203 |
+
upvar this this
|
| 204 |
+
upvar win win
|
| 205 |
+
upvar itcl_hull itcl_hull
|
| 206 |
+
|
| 207 |
+
#puts stderr "setupcomponent!$comp!$widget_type!$path!$args!$this!$win!$itcl_hull!"
|
| 208 |
+
#puts stderr "CONT![uplevel 1 info context]!"
|
| 209 |
+
#puts stderr "ns1![uplevel 1 namespace current]!"
|
| 210 |
+
#puts stderr "ns2![uplevel 2 namespace current]!"
|
| 211 |
+
#puts stderr "ns3![uplevel 3 namespace current]!"
|
| 212 |
+
set my_comp_object [lindex [uplevel 1 info context] 1]
|
| 213 |
+
if {[::info exists ::itcl::internal::component_objects($my_comp_object)]} {
|
| 214 |
+
set my_comp_object [set ::itcl::internal::component_objects($my_comp_object)]
|
| 215 |
+
} else {
|
| 216 |
+
set ::itcl::internal::component_objects($path) $my_comp_object
|
| 217 |
+
}
|
| 218 |
+
set options [list]
|
| 219 |
+
foreach {option_name value} $args {
|
| 220 |
+
switch -glob -- $option_name {
|
| 221 |
+
-* {
|
| 222 |
+
lappend options $option_name $value
|
| 223 |
+
}
|
| 224 |
+
default {
|
| 225 |
+
return -code error "bad option name\"$option_name\" options must start with a \"-\""
|
| 226 |
+
}
|
| 227 |
+
}
|
| 228 |
+
}
|
| 229 |
+
if {[llength $args]} {
|
| 230 |
+
set argsDict [dict create {*}$args]
|
| 231 |
+
} else {
|
| 232 |
+
set argsDict [dict create]
|
| 233 |
+
}
|
| 234 |
+
set cmd [list $widget_type $path]
|
| 235 |
+
if {[llength $options] > 0} {
|
| 236 |
+
lappend cmd {*}$options
|
| 237 |
+
}
|
| 238 |
+
#puts stderr "cmd0![::info command $widget_type]!$path![::info command $path]!"
|
| 239 |
+
#puts stderr "cmd1!$cmd!"
|
| 240 |
+
# set my_comp [uplevel 3 $cmd]
|
| 241 |
+
set my_comp [uplevel #0 $cmd]
|
| 242 |
+
#puts stderr 111![::info command $path]!
|
| 243 |
+
::itcl::setcomponent $this $comp $my_comp
|
| 244 |
+
set opts [uplevel 1 info delegated options]
|
| 245 |
+
foreach entry $opts {
|
| 246 |
+
foreach {optName compName} $entry break
|
| 247 |
+
if {$compName eq $my_comp} {
|
| 248 |
+
set optInfos [uplevel 1 info delegated option $optName]
|
| 249 |
+
set realOptName [lindex $optInfos 4]
|
| 250 |
+
# strip off the "-" at the beginning
|
| 251 |
+
set myOptName [string range $realOptName 1 end]
|
| 252 |
+
set my_opt_val [option get $my_win $myOptName *]
|
| 253 |
+
if {$my_opt_val ne ""} {
|
| 254 |
+
$my_comp configure -$myOptName $my_opt_val
|
| 255 |
+
}
|
| 256 |
+
}
|
| 257 |
+
}
|
| 258 |
+
set my_class $widget_type
|
| 259 |
+
set my_parent_class [uplevel 1 namespace current]
|
| 260 |
+
if {[catch {
|
| 261 |
+
set myOptions [namespace eval $my_class {info classoptions}]
|
| 262 |
+
} msg]} {
|
| 263 |
+
set myOptions [list]
|
| 264 |
+
}
|
| 265 |
+
foreach entry [$path configure] {
|
| 266 |
+
foreach {opt dummy1 dummy2 dummy3} $entry break
|
| 267 |
+
lappend myOptions $opt
|
| 268 |
+
}
|
| 269 |
+
#puts stderr "OPTS!$myOptions!"
|
| 270 |
+
addToItclOptions $widget_type $my_comp_object $myOptions $argsDict
|
| 271 |
+
#puts stderr END!$path![::info command $path]!
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
proc itcl_initoptions {args} {
|
| 275 |
+
puts stderr "ITCL_INITOPT!$args!"
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
# ======================= initoptions ===========================
|
| 279 |
+
|
| 280 |
+
proc initoptions {args} {
|
| 281 |
+
upvar win win
|
| 282 |
+
upvar itcl_hull itcl_hull
|
| 283 |
+
upvar itcl_option_components itcl_option_components
|
| 284 |
+
|
| 285 |
+
#puts stderr "INITOPT!!$win!"
|
| 286 |
+
if {[llength $args]} {
|
| 287 |
+
set argsDict [dict create {*}$args]
|
| 288 |
+
} else {
|
| 289 |
+
set argsDict [dict create]
|
| 290 |
+
}
|
| 291 |
+
set my_class [uplevel 1 namespace current]
|
| 292 |
+
set myOptions [namespace eval $my_class {info classoptions}]
|
| 293 |
+
if {[dict exists $::itcl::internal::dicts::classComponents $my_class]} {
|
| 294 |
+
set class_info_dict [dict get $::itcl::internal::dicts::classComponents $my_class]
|
| 295 |
+
# set myOptions [lsort -unique [namespace eval $my_class {info options}]]
|
| 296 |
+
foreach comp [uplevel 1 info components] {
|
| 297 |
+
if {[dict exists $class_info_dict $comp -keptoptions]} {
|
| 298 |
+
foreach my_opt [dict get $class_info_dict $comp -keptoptions] {
|
| 299 |
+
if {[lsearch $myOptions $my_opt] < 0} {
|
| 300 |
+
#puts stderr "KEOPT!$my_opt!"
|
| 301 |
+
lappend myOptions $my_opt
|
| 302 |
+
}
|
| 303 |
+
}
|
| 304 |
+
}
|
| 305 |
+
}
|
| 306 |
+
} else {
|
| 307 |
+
set class_info_dict [list]
|
| 308 |
+
}
|
| 309 |
+
#puts stderr "OPTS!$win!$my_class![join [lsort $myOptions]] \n]!"
|
| 310 |
+
set opt_lst [list configure]
|
| 311 |
+
set my_win $win
|
| 312 |
+
foreach opt [lsort $myOptions] {
|
| 313 |
+
set found 0
|
| 314 |
+
if {[catch {
|
| 315 |
+
set resource [uplevel 1 info option $opt -resource]
|
| 316 |
+
set class [uplevel 1 info option $opt -class]
|
| 317 |
+
set default_val [uplevel 1 info option $opt -default]
|
| 318 |
+
set found 1
|
| 319 |
+
} msg]} {
|
| 320 |
+
# puts stderr "MSG!$opt!$msg!"
|
| 321 |
+
}
|
| 322 |
+
#puts stderr "OPT!$opt!$found!"
|
| 323 |
+
if {$found} {
|
| 324 |
+
if {[catch {
|
| 325 |
+
set val [uplevel #0 ::option get $my_win $resource $class]
|
| 326 |
+
} msg]} {
|
| 327 |
+
set val ""
|
| 328 |
+
}
|
| 329 |
+
if {[::dict exists $argsDict $opt]} {
|
| 330 |
+
# we have an explicitly set option
|
| 331 |
+
set val [::dict get $argsDict $opt]
|
| 332 |
+
} else {
|
| 333 |
+
if {[string length $val] == 0} {
|
| 334 |
+
set val $default_val
|
| 335 |
+
}
|
| 336 |
+
}
|
| 337 |
+
set ::itcl::internal::variables::${win}::itcl_options($opt) $val
|
| 338 |
+
set ::itcl::internal::variables::${win}::__itcl_option_infos($opt) [list $resource $class $default_val]
|
| 339 |
+
#puts stderr "OPT1!$opt!$val!"
|
| 340 |
+
# uplevel 1 [list set itcl_options($opt) [list $val]]
|
| 341 |
+
if {[catch {uplevel 1 $my_win configure $opt [list $val]} msg]} {
|
| 342 |
+
puts stderr "initoptions ERR!$msg!$my_class!$my_win!configure!$opt!$val!"
|
| 343 |
+
}
|
| 344 |
+
}
|
| 345 |
+
foreach comp [dict keys $class_info_dict] {
|
| 346 |
+
#puts stderr "OPT1!$opt!$comp![dict get $class_info_dict $comp]!"
|
| 347 |
+
if {[dict exists $class_info_dict $comp -keptoptions]} {
|
| 348 |
+
if {[lsearch [dict get $class_info_dict $comp -keptoptions] $opt] >= 0} {
|
| 349 |
+
if {$found == 0} {
|
| 350 |
+
# we use the option value of the first component for setting
|
| 351 |
+
# the option, as the components are traversed in the dict
|
| 352 |
+
# depending on the ordering of the component creation!!
|
| 353 |
+
set my_info [uplevel 1 \[set $comp\] configure $opt]
|
| 354 |
+
set resource [lindex $my_info 1]
|
| 355 |
+
set class [lindex $my_info 2]
|
| 356 |
+
set default_val [lindex $my_info 3]
|
| 357 |
+
set found 2
|
| 358 |
+
set val [uplevel #0 ::option get $my_win $resource $class]
|
| 359 |
+
if {[::dict exists $argsDict $opt]} {
|
| 360 |
+
# we have an explicitly set option
|
| 361 |
+
set val [::dict get $argsDict $opt]
|
| 362 |
+
} else {
|
| 363 |
+
if {[string length $val] == 0} {
|
| 364 |
+
set val $default_val
|
| 365 |
+
}
|
| 366 |
+
}
|
| 367 |
+
#puts stderr "OPT2!$opt!$val!"
|
| 368 |
+
set ::itcl::internal::variables::${win}::itcl_options($opt) $val
|
| 369 |
+
set ::itcl::internal::variables::${win}::__itcl_option_infos($opt) [list $resource $class $default_val]
|
| 370 |
+
# uplevel 1 [list set itcl_options($opt) [list $val]]
|
| 371 |
+
}
|
| 372 |
+
if {[catch {uplevel 1 \[set $comp\] configure $opt [list $val]} msg]} {
|
| 373 |
+
puts stderr "initoptions ERR2!$msg!$my_class!$comp!configure!$opt!$val!"
|
| 374 |
+
}
|
| 375 |
+
if {![uplevel 1 info exists itcl_option_components($opt)]} {
|
| 376 |
+
set itcl_option_components($opt) [list]
|
| 377 |
+
}
|
| 378 |
+
if {[lsearch [set itcl_option_components($opt)] $comp] < 0} {
|
| 379 |
+
if {![catch {
|
| 380 |
+
set optval [uplevel 1 [list set itcl_options($opt)]]
|
| 381 |
+
} msg3]} {
|
| 382 |
+
uplevel 1 \[set $comp\] configure $opt $optval
|
| 383 |
+
}
|
| 384 |
+
lappend itcl_option_components($opt) $comp
|
| 385 |
+
}
|
| 386 |
+
}
|
| 387 |
+
}
|
| 388 |
+
}
|
| 389 |
+
}
|
| 390 |
+
# uplevel 1 $opt_lst
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
# ======================= setoptions ===========================
|
| 394 |
+
|
| 395 |
+
proc setoptions {args} {
|
| 396 |
+
|
| 397 |
+
#puts stderr "setOPT!!$args!"
|
| 398 |
+
if {[llength $args]} {
|
| 399 |
+
set argsDict [dict create {*}$args]
|
| 400 |
+
} else {
|
| 401 |
+
set argsDict [dict create]
|
| 402 |
+
}
|
| 403 |
+
set my_class [uplevel 1 namespace current]
|
| 404 |
+
set myOptions [namespace eval $my_class {info options}]
|
| 405 |
+
#puts stderr "OPTS!$win!$my_class![join [lsort $myOptions]] \n]!"
|
| 406 |
+
set opt_lst [list configure]
|
| 407 |
+
foreach opt [lsort $myOptions] {
|
| 408 |
+
set found 0
|
| 409 |
+
if {[catch {
|
| 410 |
+
set resource [uplevel 1 info option $opt -resource]
|
| 411 |
+
set class [uplevel 1 info option $opt -class]
|
| 412 |
+
set default_val [uplevel 1 info option $opt -default]
|
| 413 |
+
set found 1
|
| 414 |
+
} msg]} {
|
| 415 |
+
# puts stderr "MSG!$opt!$msg!"
|
| 416 |
+
}
|
| 417 |
+
#puts stderr "OPT!$opt!$found!"
|
| 418 |
+
if {$found} {
|
| 419 |
+
set val ""
|
| 420 |
+
if {[::dict exists $argsDict $opt]} {
|
| 421 |
+
# we have an explicitly set option
|
| 422 |
+
set val [::dict get $argsDict $opt]
|
| 423 |
+
} else {
|
| 424 |
+
if {[string length $val] == 0} {
|
| 425 |
+
set val $default_val
|
| 426 |
+
}
|
| 427 |
+
}
|
| 428 |
+
set myObj [uplevel 1 set this]
|
| 429 |
+
#puts stderr "myObj!$myObj!"
|
| 430 |
+
set ::itcl::internal::variables::${myObj}::itcl_options($opt) $val
|
| 431 |
+
set ::itcl::internal::variables::${myObj}::__itcl_option_infos($opt) [list $resource $class $default_val]
|
| 432 |
+
#puts stderr "OPT1!$opt!$val!"
|
| 433 |
+
uplevel 1 [list set itcl_options($opt) [list $val]]
|
| 434 |
+
# if {[catch {uplevel 1 $myObj configure $opt [list $val]} msg]} {
|
| 435 |
+
#puts stderr "initoptions ERR!$msg!$my_class!$my_win!configure!$opt!$val!"
|
| 436 |
+
# }
|
| 437 |
+
}
|
| 438 |
+
}
|
| 439 |
+
# uplevel 1 $opt_lst
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
# ========================= keepcomponentoption ======================
|
| 443 |
+
# Invoked by Tcl during evaluating constructor whenever
|
| 444 |
+
# the "keepcomponentoption" command is invoked to list the options
|
| 445 |
+
# to be kept when an ::itcl::extendedclass component has been setup
|
| 446 |
+
# for an object.
|
| 447 |
+
#
|
| 448 |
+
# It checks, for all arguments, if the opt is an option of that class
|
| 449 |
+
# and of that component. If that is the case it adds the component name
|
| 450 |
+
# to the list of components for that option.
|
| 451 |
+
# The variable is the object variable: itcl_option_components($opt)
|
| 452 |
+
#
|
| 453 |
+
# Handles the following syntax:
|
| 454 |
+
#
|
| 455 |
+
# keepcomponentoption <componentName> <optionName> ?<optionName> ...?
|
| 456 |
+
#
|
| 457 |
+
# ======================================================================
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
proc keepcomponentoption {args} {
|
| 461 |
+
upvar win win
|
| 462 |
+
upvar itcl_hull itcl_hull
|
| 463 |
+
|
| 464 |
+
set usage "wrong # args, should be: keepcomponentoption componentName optionName ?optionName ...?"
|
| 465 |
+
|
| 466 |
+
#puts stderr "KEEP!$args![uplevel 1 namespace current]!"
|
| 467 |
+
if {[llength $args] < 2} {
|
| 468 |
+
puts stderr $usage
|
| 469 |
+
return -code error
|
| 470 |
+
}
|
| 471 |
+
set my_hull [uplevel 1 set itcl_hull]
|
| 472 |
+
set my_class [uplevel 1 namespace current]
|
| 473 |
+
set comp [lindex $args 0]
|
| 474 |
+
set args [lrange $args 1 end]
|
| 475 |
+
set class_info_dict [dict get $::itcl::internal::dicts::classComponents $my_class]
|
| 476 |
+
if {![dict exists $class_info_dict $comp]} {
|
| 477 |
+
puts stderr "keepcomponentoption cannot find component \"$comp\""
|
| 478 |
+
return -code error
|
| 479 |
+
}
|
| 480 |
+
set class_comp_dict [dict get $class_info_dict $comp]
|
| 481 |
+
if {![dict exists $class_comp_dict -keptoptions]} {
|
| 482 |
+
dict set class_comp_dict -keptoptions [list]
|
| 483 |
+
}
|
| 484 |
+
foreach opt $args {
|
| 485 |
+
#puts stderr "KEEP!$opt!"
|
| 486 |
+
if {[string range $opt 0 0] ne "-"} {
|
| 487 |
+
puts stderr "keepcomponentoption: option must begin with a \"-\"!"
|
| 488 |
+
return -code error
|
| 489 |
+
}
|
| 490 |
+
if {[lsearch [dict get $class_comp_dict -keptoptions] $opt] < 0} {
|
| 491 |
+
dict lappend class_comp_dict -keptoptions $opt
|
| 492 |
+
}
|
| 493 |
+
}
|
| 494 |
+
if {![info exists ::itcl::internal::component_objects([lindex [uplevel 1 info context] 1])]} {
|
| 495 |
+
set comp_object $::itcl::internal::component_objects([lindex [uplevel 1 info context] 1])
|
| 496 |
+
} else {
|
| 497 |
+
set comp_object "unknown_comp_obj_$comp!"
|
| 498 |
+
}
|
| 499 |
+
dict set class_info_dict $comp $class_comp_dict
|
| 500 |
+
dict set ::itcl::internal::dicts::classComponents $my_class $class_info_dict
|
| 501 |
+
puts stderr "CLDI!$class_comp_dict!"
|
| 502 |
+
addToItclOptions $my_class $comp_object $args [list]
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
proc ignorecomponentoption {args} {
|
| 506 |
+
puts stderr "IGNORE_COMPONENT_OPTION!$args!"
|
| 507 |
+
}
|
| 508 |
+
|
| 509 |
+
proc renamecomponentoption {args} {
|
| 510 |
+
puts stderr "rename_COMPONENT_OPTION!$args!"
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
proc addoptioncomponent {args} {
|
| 514 |
+
puts stderr "ADD_OPTION_COMPONENT!$args!"
|
| 515 |
+
}
|
| 516 |
+
|
| 517 |
+
proc ignoreoptioncomponent {args} {
|
| 518 |
+
puts stderr "IGNORE_OPTION_COMPONENT!$args!"
|
| 519 |
+
}
|
| 520 |
+
|
| 521 |
+
proc renameoptioncomponent {args} {
|
| 522 |
+
puts stderr "RENAME_OPTION_COMPONENT!$args!"
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
proc getEclassOptions {args} {
|
| 526 |
+
upvar win win
|
| 527 |
+
|
| 528 |
+
#puts stderr "getEclassOptions!$args!$win![uplevel 1 namespace current]!"
|
| 529 |
+
#parray ::itcl::internal::variables::${win}::itcl_options
|
| 530 |
+
set result [list]
|
| 531 |
+
foreach opt [array names ::itcl::internal::variables::${win}::itcl_options] {
|
| 532 |
+
if {[catch {
|
| 533 |
+
foreach {res cls def} [set ::itcl::internal::variables::${win}::__itcl_option_infos($opt)] break
|
| 534 |
+
lappend result [list $opt $res $cls $def [set ::itcl::internal::variables::${win}::itcl_options($opt)]]
|
| 535 |
+
} msg]} {
|
| 536 |
+
}
|
| 537 |
+
}
|
| 538 |
+
return $result
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
proc eclassConfigure {args} {
|
| 542 |
+
upvar win win
|
| 543 |
+
|
| 544 |
+
#puts stderr "+++ eclassConfigure!$args!"
|
| 545 |
+
if {[llength $args] > 1} {
|
| 546 |
+
foreach {opt val} $args break
|
| 547 |
+
if {[::info exists ::itcl::internal::variables::${win}::itcl_options($opt)]} {
|
| 548 |
+
set ::itcl::internal::variables::${win}::itcl_options($opt) $val
|
| 549 |
+
return
|
| 550 |
+
}
|
| 551 |
+
} else {
|
| 552 |
+
foreach {opt} $args break
|
| 553 |
+
if {[::info exists ::itcl::internal::variables::${win}::itcl_options($opt)]} {
|
| 554 |
+
#puts stderr "OP![set ::itcl::internal::variables::${win}::itcl_options($opt)]!"
|
| 555 |
+
foreach {res cls def} [set ::itcl::internal::variables::${win}::__itcl_option_infos($opt)] break
|
| 556 |
+
return [list $opt $res $cls $def [set ::itcl::internal::variables::${win}::itcl_options($opt)]]
|
| 557 |
+
}
|
| 558 |
+
}
|
| 559 |
+
return -code error
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
}
|
evalkit_llava/lib/itcl4.2.4/itclWidget.tcl
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# itclWidget.tcl
|
| 3 |
+
# ----------------------------------------------------------------------
|
| 4 |
+
# Invoked automatically upon startup to customize the interpreter
|
| 5 |
+
# for [incr Tcl] when one of ::itcl::widget or ::itcl::widgetadaptor is called.
|
| 6 |
+
# ----------------------------------------------------------------------
|
| 7 |
+
# AUTHOR: Arnulf P. Wiedemann
|
| 8 |
+
#
|
| 9 |
+
# ----------------------------------------------------------------------
|
| 10 |
+
# Copyright (c) 2008 Arnulf P. Wiedemann
|
| 11 |
+
# ======================================================================
|
| 12 |
+
# See the file "license.terms" for information on usage and
|
| 13 |
+
# redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
|
| 14 |
+
|
| 15 |
+
package require Tk 8.6 9
|
| 16 |
+
# package require itclwidget [set ::itcl::version]
|
| 17 |
+
|
| 18 |
+
namespace eval ::itcl {
|
| 19 |
+
|
| 20 |
+
proc widget {name args} {
|
| 21 |
+
set result [uplevel 1 ::itcl::internal::commands::genericclass widget $name $args]
|
| 22 |
+
# we handle create by owerselfs !! allow classunknown to handle that
|
| 23 |
+
oo::objdefine $result unexport create
|
| 24 |
+
return $result
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
proc widgetadaptor {name args} {
|
| 28 |
+
set result [uplevel 1 ::itcl::internal::commands::genericclass widgetadaptor $name $args]
|
| 29 |
+
# we handle create by owerselfs !! allow classunknown to handle that
|
| 30 |
+
oo::objdefine $result unexport create
|
| 31 |
+
return $result
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
} ; # end ::itcl
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
namespace eval ::itcl::internal::commands {
|
| 38 |
+
|
| 39 |
+
proc initWidgetOptions {varNsName widgetName className} {
|
| 40 |
+
set myDict [set ::itcl::internal::dicts::classOptions]
|
| 41 |
+
if {$myDict eq ""} {
|
| 42 |
+
return
|
| 43 |
+
}
|
| 44 |
+
if {![dict exists $myDict $className]} {
|
| 45 |
+
return
|
| 46 |
+
}
|
| 47 |
+
set myDict [dict get $myDict $className]
|
| 48 |
+
foreach option [dict keys $myDict] {
|
| 49 |
+
set infos [dict get $myDict $option]
|
| 50 |
+
set resource [dict get $infos -resource]
|
| 51 |
+
set class [dict get $infos -class]
|
| 52 |
+
set value [::option get $widgetName $resource $class]
|
| 53 |
+
if {$value eq ""} {
|
| 54 |
+
if {[dict exists $infos -default]} {
|
| 55 |
+
set defaultValue [dict get $infos -default]
|
| 56 |
+
uplevel 1 set ${varNsName}::itcl_options($option) $defaultValue
|
| 57 |
+
}
|
| 58 |
+
} else {
|
| 59 |
+
uplevel 1 set ${varNsName}::itcl_options($option) $value
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
proc initWidgetDelegatedOptions {varNsName widgetName className args} {
|
| 65 |
+
set myDict [set ::itcl::internal::dicts::classDelegatedOptions]
|
| 66 |
+
if {$myDict eq ""} {
|
| 67 |
+
return
|
| 68 |
+
}
|
| 69 |
+
if {![dict exists $myDict $className]} {
|
| 70 |
+
return
|
| 71 |
+
}
|
| 72 |
+
set myDict [dict get $myDict $className]
|
| 73 |
+
foreach option [dict keys $myDict] {
|
| 74 |
+
set infos [dict get $myDict $option]
|
| 75 |
+
if {![dict exists $infos -resource]} {
|
| 76 |
+
# this is the case when delegating "*"
|
| 77 |
+
continue
|
| 78 |
+
}
|
| 79 |
+
if {![dict exists $infos -component]} {
|
| 80 |
+
# nothing to do
|
| 81 |
+
continue
|
| 82 |
+
}
|
| 83 |
+
# check if not in the command line options
|
| 84 |
+
# these have higher priority
|
| 85 |
+
set myOption $option
|
| 86 |
+
if {[dict exists $infos -as]} {
|
| 87 |
+
set myOption [dict get $infos -as]
|
| 88 |
+
}
|
| 89 |
+
set noOptionSet 0
|
| 90 |
+
foreach {optName optVal} $args {
|
| 91 |
+
if {$optName eq $myOption} {
|
| 92 |
+
set noOptionSet 1
|
| 93 |
+
break
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
if {$noOptionSet} {
|
| 97 |
+
continue
|
| 98 |
+
}
|
| 99 |
+
set resource [dict get $infos -resource]
|
| 100 |
+
set class [dict get $infos -class]
|
| 101 |
+
set component [dict get $infos -component]
|
| 102 |
+
set value [::option get $widgetName $resource $class]
|
| 103 |
+
if {$component ne ""} {
|
| 104 |
+
if {$value ne ""} {
|
| 105 |
+
set compVar [namespace eval ${varNsName}${className} "set $component"]
|
| 106 |
+
if {$compVar ne ""} {
|
| 107 |
+
uplevel 1 $compVar configure $myOption $value
|
| 108 |
+
}
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
proc widgetinitobjectoptions {varNsName widgetName className} {
|
| 115 |
+
#puts stderr "initWidgetObjectOptions!$varNsName!$widgetName!$className!"
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
proc deletehull {newName oldName what} {
|
| 119 |
+
if {$what eq "delete"} {
|
| 120 |
+
set name [namespace tail $newName]
|
| 121 |
+
regsub {hull[0-9]+} $name {} name
|
| 122 |
+
rename $name {}
|
| 123 |
+
}
|
| 124 |
+
if {$what eq "rename"} {
|
| 125 |
+
set name [namespace tail $newName]
|
| 126 |
+
regsub {hull[0-9]+} $name {} name
|
| 127 |
+
rename $name {}
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
proc hullandoptionsinstall {objectName className widgetClass hulltype args} {
|
| 132 |
+
if {$hulltype eq ""} {
|
| 133 |
+
set hulltype frame
|
| 134 |
+
}
|
| 135 |
+
set idx 0
|
| 136 |
+
set found 0
|
| 137 |
+
foreach {optName optValue} $args {
|
| 138 |
+
if {$optName eq "-class"} {
|
| 139 |
+
set found 1
|
| 140 |
+
set widgetClass $optValue
|
| 141 |
+
break
|
| 142 |
+
}
|
| 143 |
+
incr idx
|
| 144 |
+
}
|
| 145 |
+
if {$found} {
|
| 146 |
+
set args [lreplace $args $idx [expr {$idx + 1}]]
|
| 147 |
+
}
|
| 148 |
+
if {$widgetClass eq ""} {
|
| 149 |
+
set widgetClass $className
|
| 150 |
+
set widgetClass [string totitle $widgetClass]
|
| 151 |
+
}
|
| 152 |
+
set cmd "set win $objectName; ::itcl::builtin::installhull using $hulltype -class $widgetClass $args"
|
| 153 |
+
uplevel 2 $cmd
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
} ; # end ::itcl::internal::commands
|
| 157 |
+
|
| 158 |
+
namespace eval ::itcl::builtin {
|
| 159 |
+
|
| 160 |
+
proc installhull {args} {
|
| 161 |
+
set cmdPath ::itcl::internal::commands
|
| 162 |
+
set className [uplevel 1 info class]
|
| 163 |
+
|
| 164 |
+
set replace 0
|
| 165 |
+
switch -- [llength $args] {
|
| 166 |
+
0 {
|
| 167 |
+
return -code error\
|
| 168 |
+
"wrong # args: should be \"[lindex [info level 0] 0]\
|
| 169 |
+
name|using <widgetType> ?arg ...?\""
|
| 170 |
+
}
|
| 171 |
+
1 {
|
| 172 |
+
set widgetName [lindex $args 0]
|
| 173 |
+
set varNsName $::itcl::internal::varNsName($widgetName)
|
| 174 |
+
}
|
| 175 |
+
default {
|
| 176 |
+
upvar win win
|
| 177 |
+
set widgetName $win
|
| 178 |
+
|
| 179 |
+
set varNsName $::itcl::internal::varNsName($widgetName)
|
| 180 |
+
set widgetType [lindex $args 1]
|
| 181 |
+
incr replace
|
| 182 |
+
if {[llength $args] > 3 && [lindex $args 2] eq "-class"} {
|
| 183 |
+
set classNam [lindex $args 3]
|
| 184 |
+
incr replace 2
|
| 185 |
+
} else {
|
| 186 |
+
set classNam [string totitle $widgetType]
|
| 187 |
+
}
|
| 188 |
+
uplevel 1 [lreplace $args 0 $replace $widgetType $widgetName -class $classNam]
|
| 189 |
+
uplevel 1 [list ${cmdPath}::initWidgetOptions $varNsName $widgetName $className]
|
| 190 |
+
}
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
# initialize the itcl_hull variable
|
| 194 |
+
set i 0
|
| 195 |
+
set nam ::itcl::internal::widgets::hull
|
| 196 |
+
while {1} {
|
| 197 |
+
incr i
|
| 198 |
+
set hullNam ${nam}${i}$widgetName
|
| 199 |
+
if {[::info command $hullNam] eq ""} {
|
| 200 |
+
break
|
| 201 |
+
}
|
| 202 |
+
}
|
| 203 |
+
uplevel 1 [list ${cmdPath}::sethullwindowname $widgetName]
|
| 204 |
+
uplevel 1 [list ::rename $widgetName $hullNam]
|
| 205 |
+
uplevel 1 [list ::trace add command $hullNam {delete rename} ::itcl::internal::commands::deletehull]
|
| 206 |
+
catch {${cmdPath}::checksetitclhull [list] 0}
|
| 207 |
+
namespace eval ${varNsName}${className} "set itcl_hull $hullNam"
|
| 208 |
+
catch {${cmdPath}::checksetitclhull [list] 2}
|
| 209 |
+
uplevel 1 [lreplace $args 0 $replace ${cmdPath}::initWidgetDelegatedOptions $varNsName $widgetName $className]
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
proc installcomponent {args} {
|
| 213 |
+
upvar win win
|
| 214 |
+
|
| 215 |
+
set className [uplevel 1 info class]
|
| 216 |
+
set myType [${className}::info types [namespace tail $className]]
|
| 217 |
+
set isType 0
|
| 218 |
+
if {$myType ne ""} {
|
| 219 |
+
set isType 1
|
| 220 |
+
}
|
| 221 |
+
set numArgs [llength $args]
|
| 222 |
+
set usage "usage: installcomponent <componentName> using <widgetType> <widgetPath> ?-option value ...?"
|
| 223 |
+
if {$numArgs < 4} {
|
| 224 |
+
error $usage
|
| 225 |
+
}
|
| 226 |
+
foreach {componentName using widgetType widgetPath} $args break
|
| 227 |
+
set opts [lrange $args 4 end]
|
| 228 |
+
if {$using ne "using"} {
|
| 229 |
+
error $usage
|
| 230 |
+
}
|
| 231 |
+
if {!$isType} {
|
| 232 |
+
set hullExists [uplevel 1 ::info exists itcl_hull]
|
| 233 |
+
if {!$hullExists} {
|
| 234 |
+
error "cannot install \"$componentName\" before \"itcl_hull\" exists"
|
| 235 |
+
}
|
| 236 |
+
set hullVal [uplevel 1 set itcl_hull]
|
| 237 |
+
if {$hullVal eq ""} {
|
| 238 |
+
error "cannot install \"$componentName\" before \"itcl_hull\" exists"
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
# check for delegated option and ask the option database for the values
|
| 242 |
+
# first check for number of delegated options
|
| 243 |
+
set numOpts 0
|
| 244 |
+
set starOption 0
|
| 245 |
+
set myDict [set ::itcl::internal::dicts::classDelegatedOptions]
|
| 246 |
+
if {[dict exists $myDict $className]} {
|
| 247 |
+
set myDict [dict get $myDict $className]
|
| 248 |
+
foreach option [dict keys $myDict] {
|
| 249 |
+
if {$option eq "*"} {
|
| 250 |
+
set starOption 1
|
| 251 |
+
}
|
| 252 |
+
incr numOpts
|
| 253 |
+
}
|
| 254 |
+
}
|
| 255 |
+
set myOptionDict [set ::itcl::internal::dicts::classOptions]
|
| 256 |
+
if {[dict exists $myOptionDict $className]} {
|
| 257 |
+
set myOptionDict [dict get $myOptionDict $className]
|
| 258 |
+
}
|
| 259 |
+
set cmd [list $widgetPath configure]
|
| 260 |
+
set cmd1 "set $componentName \[$widgetType $widgetPath\]"
|
| 261 |
+
uplevel 1 $cmd1
|
| 262 |
+
if {$starOption} {
|
| 263 |
+
upvar $componentName compName
|
| 264 |
+
set cmd1 [list $compName configure]
|
| 265 |
+
set configInfos [uplevel 1 $cmd1]
|
| 266 |
+
foreach entry $configInfos {
|
| 267 |
+
if {[llength $entry] > 2} {
|
| 268 |
+
foreach {optName resource class defaultValue} $entry break
|
| 269 |
+
set val ""
|
| 270 |
+
catch {
|
| 271 |
+
set val [::option get $win $resource $class]
|
| 272 |
+
}
|
| 273 |
+
if {$val ne ""} {
|
| 274 |
+
set addOpt 1
|
| 275 |
+
if {[dict exists $myDict $$optName]} {
|
| 276 |
+
set addOpt 0
|
| 277 |
+
} else {
|
| 278 |
+
set starDict [dict get $myDict "*"]
|
| 279 |
+
if {[dict exists $starDict -except]} {
|
| 280 |
+
set exceptions [dict get $starDict -except]
|
| 281 |
+
if {[lsearch $exceptions $optName] >= 0} {
|
| 282 |
+
set addOpt 0
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
}
|
| 286 |
+
if {[dict exists $myOptionDict $optName]} {
|
| 287 |
+
set addOpt 0
|
| 288 |
+
}
|
| 289 |
+
}
|
| 290 |
+
if {$addOpt} {
|
| 291 |
+
lappend cmd $optName $val
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
}
|
| 297 |
+
}
|
| 298 |
+
} else {
|
| 299 |
+
foreach optName [dict keys $myDict] {
|
| 300 |
+
set optInfos [dict get $myDict $optName]
|
| 301 |
+
set resource [dict get $optInfos -resource]
|
| 302 |
+
set class [namespace tail $className]
|
| 303 |
+
set class [string totitle $class]
|
| 304 |
+
set val ""
|
| 305 |
+
catch {
|
| 306 |
+
set val [::option get $win $resource $class]
|
| 307 |
+
}
|
| 308 |
+
if {$val ne ""} {
|
| 309 |
+
if {[dict exists $optInfos -as] } {
|
| 310 |
+
set optName [dict get $optInfos -as]
|
| 311 |
+
}
|
| 312 |
+
lappend cmd $optName $val
|
| 313 |
+
}
|
| 314 |
+
}
|
| 315 |
+
}
|
| 316 |
+
lappend cmd {*}$opts
|
| 317 |
+
uplevel 1 $cmd
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
} ; # end ::itcl::builtin
|
| 321 |
+
|
| 322 |
+
set ::itcl::internal::dicts::hullTypes [list \
|
| 323 |
+
frame \
|
| 324 |
+
toplevel \
|
| 325 |
+
labelframe \
|
| 326 |
+
ttk:frame \
|
| 327 |
+
ttk:toplevel \
|
| 328 |
+
ttk:labelframe \
|
| 329 |
+
]
|
| 330 |
+
|
| 331 |
+
namespace eval ::itcl::builtin::Info {
|
| 332 |
+
|
| 333 |
+
proc hulltypes {args} {
|
| 334 |
+
namespace upvar ::itcl::internal::dicts hullTypes hullTypes
|
| 335 |
+
|
| 336 |
+
set numArgs [llength $args]
|
| 337 |
+
if {$numArgs > 1} {
|
| 338 |
+
error "wrong # args should be: info hulltypes ?<pattern>?"
|
| 339 |
+
}
|
| 340 |
+
set pattern ""
|
| 341 |
+
if {$numArgs > 0} {
|
| 342 |
+
set pattern [lindex $args 0]
|
| 343 |
+
}
|
| 344 |
+
if {$pattern ne ""} {
|
| 345 |
+
return [lsearch -all -inline -glob $hullTypes $pattern]
|
| 346 |
+
}
|
| 347 |
+
return $hullTypes
|
| 348 |
+
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
proc widgetclasses {args} {
|
| 352 |
+
set numArgs [llength $args]
|
| 353 |
+
if {$numArgs > 1} {
|
| 354 |
+
error "wrong # args should be: info widgetclasses ?<pattern>?"
|
| 355 |
+
}
|
| 356 |
+
set pattern ""
|
| 357 |
+
if {$numArgs > 0} {
|
| 358 |
+
set pattern [lindex $args 0]
|
| 359 |
+
}
|
| 360 |
+
set myDict [set ::itcl::internal::dicts::classes]
|
| 361 |
+
if {![dict exists $myDict widget]} {
|
| 362 |
+
return [list]
|
| 363 |
+
}
|
| 364 |
+
set myDict [dict get $myDict widget]
|
| 365 |
+
set result [list]
|
| 366 |
+
if {$pattern ne ""} {
|
| 367 |
+
foreach key [dict keys $myDict] {
|
| 368 |
+
set myInfo [dict get $myDict $key]
|
| 369 |
+
set value [dict get $myInfo -widget]
|
| 370 |
+
if {[string match $pattern $value]} {
|
| 371 |
+
lappend result $value
|
| 372 |
+
}
|
| 373 |
+
}
|
| 374 |
+
} else {
|
| 375 |
+
foreach key [dict keys $myDict] {
|
| 376 |
+
set myInfo [dict get $myDict $key]
|
| 377 |
+
lappend result [dict get $myInfo -widget]
|
| 378 |
+
}
|
| 379 |
+
}
|
| 380 |
+
return $result
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
proc widgets {args} {
|
| 384 |
+
set numArgs [llength $args]
|
| 385 |
+
if {$numArgs > 1} {
|
| 386 |
+
error "wrong # args should be: info widgets ?<pattern>?"
|
| 387 |
+
}
|
| 388 |
+
set pattern ""
|
| 389 |
+
if {$numArgs > 0} {
|
| 390 |
+
set pattern [lindex $args 0]
|
| 391 |
+
}
|
| 392 |
+
set myDict [set ::itcl::internal::dicts::classes]
|
| 393 |
+
if {![dict exists $myDict widget]} {
|
| 394 |
+
return [list]
|
| 395 |
+
}
|
| 396 |
+
set myDict [dict get $myDict widget]
|
| 397 |
+
set result [list]
|
| 398 |
+
if {$pattern ne ""} {
|
| 399 |
+
foreach key [dict keys $myDict] {
|
| 400 |
+
set myInfo [dict get $myDict $key]
|
| 401 |
+
set value [dict get $myInfo -name]
|
| 402 |
+
if {[string match $pattern $value]} {
|
| 403 |
+
lappend result $value
|
| 404 |
+
}
|
| 405 |
+
}
|
| 406 |
+
} else {
|
| 407 |
+
foreach key [dict keys $myDict] {
|
| 408 |
+
set myInfo [dict get $myDict $key]
|
| 409 |
+
lappend result [dict get $myInfo -name]
|
| 410 |
+
}
|
| 411 |
+
}
|
| 412 |
+
return $result
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
proc widgetadaptors {args} {
|
| 416 |
+
set numArgs [llength $args]
|
| 417 |
+
if {$numArgs > 1} {
|
| 418 |
+
error "wrong # args should be: info widgetadaptors ?<pattern>?"
|
| 419 |
+
}
|
| 420 |
+
set pattern ""
|
| 421 |
+
if {$numArgs > 0} {
|
| 422 |
+
set pattern [lindex $args 0]
|
| 423 |
+
}
|
| 424 |
+
set myDict [set ::itcl::internal::dicts::classes]
|
| 425 |
+
if {![dict exists $myDict widgetadaptor]} {
|
| 426 |
+
return [list]
|
| 427 |
+
}
|
| 428 |
+
set myDict [dict get $myDict widgetadaptor]
|
| 429 |
+
set result [list]
|
| 430 |
+
if {$pattern ne ""} {
|
| 431 |
+
foreach key [dict keys $myDict] {
|
| 432 |
+
set myInfo [dict get $myDict $key]
|
| 433 |
+
set value [dict get $myInfo -name]
|
| 434 |
+
if {[string match $pattern $value]} {
|
| 435 |
+
lappend result $value
|
| 436 |
+
}
|
| 437 |
+
}
|
| 438 |
+
} else {
|
| 439 |
+
foreach key [dict keys $myDict] {
|
| 440 |
+
set myInfo [dict get $myDict $key]
|
| 441 |
+
lappend result [dict get $myInfo -name]
|
| 442 |
+
}
|
| 443 |
+
}
|
| 444 |
+
return $result
|
| 445 |
+
}
|
| 446 |
+
|
| 447 |
+
} ; # end ::itcl::builtin::Info
|
evalkit_llava/lib/itcl4.2.4/libitclstub4.2.4.a
ADDED
|
Binary file (2.75 kB). View file
|
|
|
evalkit_llava/lib/itcl4.2.4/pkgIndex.tcl
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- tcl -*-
|
| 2 |
+
# Tcl package index file, version 1.1
|
| 3 |
+
#
|
| 4 |
+
|
| 5 |
+
if {![package vsatisfies [package provide Tcl] 8.6-]} {return}
|
| 6 |
+
|
| 7 |
+
if {[package vsatisfies [package provide Tcl] 9.0-]} {
|
| 8 |
+
package ifneeded itcl 4.2.4 \
|
| 9 |
+
[list load [file join $dir libtcl9itcl4.2.4.so] Itcl]
|
| 10 |
+
} else {
|
| 11 |
+
package ifneeded itcl 4.2.4 \
|
| 12 |
+
[list load [file join $dir libitcl4.2.4.so] Itcl]
|
| 13 |
+
}
|
| 14 |
+
package ifneeded Itcl 4.2.4 [list package require -exact itcl 4.2.4]
|
evalkit_llava/lib/libncursesw.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7fa4e5e93804d78660b0eef727cdb4211209e1742e4ad3669348022668d90962
|
| 3 |
+
size 271304
|
evalkit_llava/lib/python3.10/ctypes/__pycache__/util.cpython-310.pyc
ADDED
|
Binary file (8.97 kB). View file
|
|
|
evalkit_llava/lib/python3.10/ctypes/__pycache__/wintypes.cpython-310.pyc
ADDED
|
Binary file (4.85 kB). View file
|
|
|
evalkit_llava/lib/python3.10/dbm/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (4.24 kB). View file
|
|
|
evalkit_llava/lib/python3.10/dbm/__pycache__/dumb.cpython-310.pyc
ADDED
|
Binary file (8.1 kB). View file
|
|
|
evalkit_llava/lib/python3.10/dbm/__pycache__/gnu.cpython-310.pyc
ADDED
|
Binary file (460 Bytes). View file
|
|
|
evalkit_llava/lib/python3.10/dbm/__pycache__/ndbm.cpython-310.pyc
ADDED
|
Binary file (459 Bytes). View file
|
|
|
evalkit_llava/lib/python3.10/dbm/dumb.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A dumb and slow but simple dbm clone.
|
| 2 |
+
|
| 3 |
+
For database spam, spam.dir contains the index (a text file),
|
| 4 |
+
spam.bak *may* contain a backup of the index (also a text file),
|
| 5 |
+
while spam.dat contains the data (a binary file).
|
| 6 |
+
|
| 7 |
+
XXX TO DO:
|
| 8 |
+
|
| 9 |
+
- seems to contain a bug when updating...
|
| 10 |
+
|
| 11 |
+
- reclaim free space (currently, space once occupied by deleted or expanded
|
| 12 |
+
items is never reused)
|
| 13 |
+
|
| 14 |
+
- support concurrent access (currently, if two processes take turns making
|
| 15 |
+
updates, they can mess up the index)
|
| 16 |
+
|
| 17 |
+
- support efficient access to large databases (currently, the whole index
|
| 18 |
+
is read when the database is opened, and some updates rewrite the whole index)
|
| 19 |
+
|
| 20 |
+
- support opening for read-only (flag = 'm')
|
| 21 |
+
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import ast as _ast
|
| 25 |
+
import io as _io
|
| 26 |
+
import os as _os
|
| 27 |
+
import collections.abc
|
| 28 |
+
|
| 29 |
+
__all__ = ["error", "open"]
|
| 30 |
+
|
| 31 |
+
_BLOCKSIZE = 512
|
| 32 |
+
|
| 33 |
+
error = OSError
|
| 34 |
+
|
| 35 |
+
class _Database(collections.abc.MutableMapping):
|
| 36 |
+
|
| 37 |
+
# The on-disk directory and data files can remain in mutually
|
| 38 |
+
# inconsistent states for an arbitrarily long time (see comments
|
| 39 |
+
# at the end of __setitem__). This is only repaired when _commit()
|
| 40 |
+
# gets called. One place _commit() gets called is from __del__(),
|
| 41 |
+
# and if that occurs at program shutdown time, module globals may
|
| 42 |
+
# already have gotten rebound to None. Since it's crucial that
|
| 43 |
+
# _commit() finish successfully, we can't ignore shutdown races
|
| 44 |
+
# here, and _commit() must not reference any globals.
|
| 45 |
+
_os = _os # for _commit()
|
| 46 |
+
_io = _io # for _commit()
|
| 47 |
+
|
| 48 |
+
def __init__(self, filebasename, mode, flag='c'):
|
| 49 |
+
self._mode = mode
|
| 50 |
+
self._readonly = (flag == 'r')
|
| 51 |
+
|
| 52 |
+
# The directory file is a text file. Each line looks like
|
| 53 |
+
# "%r, (%d, %d)\n" % (key, pos, siz)
|
| 54 |
+
# where key is the string key, pos is the offset into the dat
|
| 55 |
+
# file of the associated value's first byte, and siz is the number
|
| 56 |
+
# of bytes in the associated value.
|
| 57 |
+
self._dirfile = filebasename + '.dir'
|
| 58 |
+
|
| 59 |
+
# The data file is a binary file pointed into by the directory
|
| 60 |
+
# file, and holds the values associated with keys. Each value
|
| 61 |
+
# begins at a _BLOCKSIZE-aligned byte offset, and is a raw
|
| 62 |
+
# binary 8-bit string value.
|
| 63 |
+
self._datfile = filebasename + '.dat'
|
| 64 |
+
self._bakfile = filebasename + '.bak'
|
| 65 |
+
|
| 66 |
+
# The index is an in-memory dict, mirroring the directory file.
|
| 67 |
+
self._index = None # maps keys to (pos, siz) pairs
|
| 68 |
+
|
| 69 |
+
# Handle the creation
|
| 70 |
+
self._create(flag)
|
| 71 |
+
self._update(flag)
|
| 72 |
+
|
| 73 |
+
def _create(self, flag):
|
| 74 |
+
if flag == 'n':
|
| 75 |
+
for filename in (self._datfile, self._bakfile, self._dirfile):
|
| 76 |
+
try:
|
| 77 |
+
_os.remove(filename)
|
| 78 |
+
except OSError:
|
| 79 |
+
pass
|
| 80 |
+
# Mod by Jack: create data file if needed
|
| 81 |
+
try:
|
| 82 |
+
f = _io.open(self._datfile, 'r', encoding="Latin-1")
|
| 83 |
+
except OSError:
|
| 84 |
+
if flag not in ('c', 'n'):
|
| 85 |
+
raise
|
| 86 |
+
with _io.open(self._datfile, 'w', encoding="Latin-1") as f:
|
| 87 |
+
self._chmod(self._datfile)
|
| 88 |
+
else:
|
| 89 |
+
f.close()
|
| 90 |
+
|
| 91 |
+
# Read directory file into the in-memory index dict.
|
| 92 |
+
def _update(self, flag):
|
| 93 |
+
self._modified = False
|
| 94 |
+
self._index = {}
|
| 95 |
+
try:
|
| 96 |
+
f = _io.open(self._dirfile, 'r', encoding="Latin-1")
|
| 97 |
+
except OSError:
|
| 98 |
+
if flag not in ('c', 'n'):
|
| 99 |
+
raise
|
| 100 |
+
self._modified = True
|
| 101 |
+
else:
|
| 102 |
+
with f:
|
| 103 |
+
for line in f:
|
| 104 |
+
line = line.rstrip()
|
| 105 |
+
key, pos_and_siz_pair = _ast.literal_eval(line)
|
| 106 |
+
key = key.encode('Latin-1')
|
| 107 |
+
self._index[key] = pos_and_siz_pair
|
| 108 |
+
|
| 109 |
+
# Write the index dict to the directory file. The original directory
|
| 110 |
+
# file (if any) is renamed with a .bak extension first. If a .bak
|
| 111 |
+
# file currently exists, it's deleted.
|
| 112 |
+
def _commit(self):
|
| 113 |
+
# CAUTION: It's vital that _commit() succeed, and _commit() can
|
| 114 |
+
# be called from __del__(). Therefore we must never reference a
|
| 115 |
+
# global in this routine.
|
| 116 |
+
if self._index is None or not self._modified:
|
| 117 |
+
return # nothing to do
|
| 118 |
+
|
| 119 |
+
try:
|
| 120 |
+
self._os.unlink(self._bakfile)
|
| 121 |
+
except OSError:
|
| 122 |
+
pass
|
| 123 |
+
|
| 124 |
+
try:
|
| 125 |
+
self._os.rename(self._dirfile, self._bakfile)
|
| 126 |
+
except OSError:
|
| 127 |
+
pass
|
| 128 |
+
|
| 129 |
+
with self._io.open(self._dirfile, 'w', encoding="Latin-1") as f:
|
| 130 |
+
self._chmod(self._dirfile)
|
| 131 |
+
for key, pos_and_siz_pair in self._index.items():
|
| 132 |
+
# Use Latin-1 since it has no qualms with any value in any
|
| 133 |
+
# position; UTF-8, though, does care sometimes.
|
| 134 |
+
entry = "%r, %r\n" % (key.decode('Latin-1'), pos_and_siz_pair)
|
| 135 |
+
f.write(entry)
|
| 136 |
+
|
| 137 |
+
sync = _commit
|
| 138 |
+
|
| 139 |
+
def _verify_open(self):
|
| 140 |
+
if self._index is None:
|
| 141 |
+
raise error('DBM object has already been closed')
|
| 142 |
+
|
| 143 |
+
def __getitem__(self, key):
|
| 144 |
+
if isinstance(key, str):
|
| 145 |
+
key = key.encode('utf-8')
|
| 146 |
+
self._verify_open()
|
| 147 |
+
pos, siz = self._index[key] # may raise KeyError
|
| 148 |
+
with _io.open(self._datfile, 'rb') as f:
|
| 149 |
+
f.seek(pos)
|
| 150 |
+
dat = f.read(siz)
|
| 151 |
+
return dat
|
| 152 |
+
|
| 153 |
+
# Append val to the data file, starting at a _BLOCKSIZE-aligned
|
| 154 |
+
# offset. The data file is first padded with NUL bytes (if needed)
|
| 155 |
+
# to get to an aligned offset. Return pair
|
| 156 |
+
# (starting offset of val, len(val))
|
| 157 |
+
def _addval(self, val):
|
| 158 |
+
with _io.open(self._datfile, 'rb+') as f:
|
| 159 |
+
f.seek(0, 2)
|
| 160 |
+
pos = int(f.tell())
|
| 161 |
+
npos = ((pos + _BLOCKSIZE - 1) // _BLOCKSIZE) * _BLOCKSIZE
|
| 162 |
+
f.write(b'\0'*(npos-pos))
|
| 163 |
+
pos = npos
|
| 164 |
+
f.write(val)
|
| 165 |
+
return (pos, len(val))
|
| 166 |
+
|
| 167 |
+
# Write val to the data file, starting at offset pos. The caller
|
| 168 |
+
# is responsible for ensuring that there's enough room starting at
|
| 169 |
+
# pos to hold val, without overwriting some other value. Return
|
| 170 |
+
# pair (pos, len(val)).
|
| 171 |
+
def _setval(self, pos, val):
|
| 172 |
+
with _io.open(self._datfile, 'rb+') as f:
|
| 173 |
+
f.seek(pos)
|
| 174 |
+
f.write(val)
|
| 175 |
+
return (pos, len(val))
|
| 176 |
+
|
| 177 |
+
# key is a new key whose associated value starts in the data file
|
| 178 |
+
# at offset pos and with length siz. Add an index record to
|
| 179 |
+
# the in-memory index dict, and append one to the directory file.
|
| 180 |
+
def _addkey(self, key, pos_and_siz_pair):
|
| 181 |
+
self._index[key] = pos_and_siz_pair
|
| 182 |
+
with _io.open(self._dirfile, 'a', encoding="Latin-1") as f:
|
| 183 |
+
self._chmod(self._dirfile)
|
| 184 |
+
f.write("%r, %r\n" % (key.decode("Latin-1"), pos_and_siz_pair))
|
| 185 |
+
|
| 186 |
+
def __setitem__(self, key, val):
|
| 187 |
+
if self._readonly:
|
| 188 |
+
raise error('The database is opened for reading only')
|
| 189 |
+
if isinstance(key, str):
|
| 190 |
+
key = key.encode('utf-8')
|
| 191 |
+
elif not isinstance(key, (bytes, bytearray)):
|
| 192 |
+
raise TypeError("keys must be bytes or strings")
|
| 193 |
+
if isinstance(val, str):
|
| 194 |
+
val = val.encode('utf-8')
|
| 195 |
+
elif not isinstance(val, (bytes, bytearray)):
|
| 196 |
+
raise TypeError("values must be bytes or strings")
|
| 197 |
+
self._verify_open()
|
| 198 |
+
self._modified = True
|
| 199 |
+
if key not in self._index:
|
| 200 |
+
self._addkey(key, self._addval(val))
|
| 201 |
+
else:
|
| 202 |
+
# See whether the new value is small enough to fit in the
|
| 203 |
+
# (padded) space currently occupied by the old value.
|
| 204 |
+
pos, siz = self._index[key]
|
| 205 |
+
oldblocks = (siz + _BLOCKSIZE - 1) // _BLOCKSIZE
|
| 206 |
+
newblocks = (len(val) + _BLOCKSIZE - 1) // _BLOCKSIZE
|
| 207 |
+
if newblocks <= oldblocks:
|
| 208 |
+
self._index[key] = self._setval(pos, val)
|
| 209 |
+
else:
|
| 210 |
+
# The new value doesn't fit in the (padded) space used
|
| 211 |
+
# by the old value. The blocks used by the old value are
|
| 212 |
+
# forever lost.
|
| 213 |
+
self._index[key] = self._addval(val)
|
| 214 |
+
|
| 215 |
+
# Note that _index may be out of synch with the directory
|
| 216 |
+
# file now: _setval() and _addval() don't update the directory
|
| 217 |
+
# file. This also means that the on-disk directory and data
|
| 218 |
+
# files are in a mutually inconsistent state, and they'll
|
| 219 |
+
# remain that way until _commit() is called. Note that this
|
| 220 |
+
# is a disaster (for the database) if the program crashes
|
| 221 |
+
# (so that _commit() never gets called).
|
| 222 |
+
|
| 223 |
+
def __delitem__(self, key):
|
| 224 |
+
if self._readonly:
|
| 225 |
+
raise error('The database is opened for reading only')
|
| 226 |
+
if isinstance(key, str):
|
| 227 |
+
key = key.encode('utf-8')
|
| 228 |
+
self._verify_open()
|
| 229 |
+
self._modified = True
|
| 230 |
+
# The blocks used by the associated value are lost.
|
| 231 |
+
del self._index[key]
|
| 232 |
+
# XXX It's unclear why we do a _commit() here (the code always
|
| 233 |
+
# XXX has, so I'm not changing it). __setitem__ doesn't try to
|
| 234 |
+
# XXX keep the directory file in synch. Why should we? Or
|
| 235 |
+
# XXX why shouldn't __setitem__?
|
| 236 |
+
self._commit()
|
| 237 |
+
|
| 238 |
+
def keys(self):
|
| 239 |
+
try:
|
| 240 |
+
return list(self._index)
|
| 241 |
+
except TypeError:
|
| 242 |
+
raise error('DBM object has already been closed') from None
|
| 243 |
+
|
| 244 |
+
def items(self):
|
| 245 |
+
self._verify_open()
|
| 246 |
+
return [(key, self[key]) for key in self._index.keys()]
|
| 247 |
+
|
| 248 |
+
def __contains__(self, key):
|
| 249 |
+
if isinstance(key, str):
|
| 250 |
+
key = key.encode('utf-8')
|
| 251 |
+
try:
|
| 252 |
+
return key in self._index
|
| 253 |
+
except TypeError:
|
| 254 |
+
if self._index is None:
|
| 255 |
+
raise error('DBM object has already been closed') from None
|
| 256 |
+
else:
|
| 257 |
+
raise
|
| 258 |
+
|
| 259 |
+
def iterkeys(self):
|
| 260 |
+
try:
|
| 261 |
+
return iter(self._index)
|
| 262 |
+
except TypeError:
|
| 263 |
+
raise error('DBM object has already been closed') from None
|
| 264 |
+
__iter__ = iterkeys
|
| 265 |
+
|
| 266 |
+
def __len__(self):
|
| 267 |
+
try:
|
| 268 |
+
return len(self._index)
|
| 269 |
+
except TypeError:
|
| 270 |
+
raise error('DBM object has already been closed') from None
|
| 271 |
+
|
| 272 |
+
def close(self):
|
| 273 |
+
try:
|
| 274 |
+
self._commit()
|
| 275 |
+
finally:
|
| 276 |
+
self._index = self._datfile = self._dirfile = self._bakfile = None
|
| 277 |
+
|
| 278 |
+
__del__ = close
|
| 279 |
+
|
| 280 |
+
def _chmod(self, file):
|
| 281 |
+
self._os.chmod(file, self._mode)
|
| 282 |
+
|
| 283 |
+
def __enter__(self):
|
| 284 |
+
return self
|
| 285 |
+
|
| 286 |
+
def __exit__(self, *args):
|
| 287 |
+
self.close()
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def open(file, flag='c', mode=0o666):
|
| 291 |
+
"""Open the database file, filename, and return corresponding object.
|
| 292 |
+
|
| 293 |
+
The flag argument, used to control how the database is opened in the
|
| 294 |
+
other DBM implementations, supports only the semantics of 'c' and 'n'
|
| 295 |
+
values. Other values will default to the semantics of 'c' value:
|
| 296 |
+
the database will always opened for update and will be created if it
|
| 297 |
+
does not exist.
|
| 298 |
+
|
| 299 |
+
The optional mode argument is the UNIX mode of the file, used only when
|
| 300 |
+
the database has to be created. It defaults to octal code 0o666 (and
|
| 301 |
+
will be modified by the prevailing umask).
|
| 302 |
+
|
| 303 |
+
"""
|
| 304 |
+
|
| 305 |
+
# Modify mode depending on the umask
|
| 306 |
+
try:
|
| 307 |
+
um = _os.umask(0)
|
| 308 |
+
_os.umask(um)
|
| 309 |
+
except AttributeError:
|
| 310 |
+
pass
|
| 311 |
+
else:
|
| 312 |
+
# Turn off any bits that are set in the umask
|
| 313 |
+
mode = mode & (~um)
|
| 314 |
+
if flag not in ('r', 'w', 'c', 'n'):
|
| 315 |
+
raise ValueError("Flag must be one of 'r', 'w', 'c', or 'n'")
|
| 316 |
+
return _Database(file, mode, flag=flag)
|
evalkit_llava/lib/python3.10/dbm/gnu.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Provide the _gdbm module as a dbm submodule."""
|
| 2 |
+
|
| 3 |
+
from _gdbm import *
|
evalkit_llava/lib/python3.10/dbm/ndbm.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Provide the _dbm module as a dbm submodule."""
|
| 2 |
+
|
| 3 |
+
from _dbm import *
|
evalkit_llava/lib/python3.10/http/__init__.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import IntEnum
|
| 2 |
+
|
| 3 |
+
__all__ = ['HTTPStatus']
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class HTTPStatus(IntEnum):
|
| 7 |
+
"""HTTP status codes and reason phrases
|
| 8 |
+
|
| 9 |
+
Status codes from the following RFCs are all observed:
|
| 10 |
+
|
| 11 |
+
* RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616
|
| 12 |
+
* RFC 6585: Additional HTTP Status Codes
|
| 13 |
+
* RFC 3229: Delta encoding in HTTP
|
| 14 |
+
* RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518
|
| 15 |
+
* RFC 5842: Binding Extensions to WebDAV
|
| 16 |
+
* RFC 7238: Permanent Redirect
|
| 17 |
+
* RFC 2295: Transparent Content Negotiation in HTTP
|
| 18 |
+
* RFC 2774: An HTTP Extension Framework
|
| 19 |
+
* RFC 7725: An HTTP Status Code to Report Legal Obstacles
|
| 20 |
+
* RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2)
|
| 21 |
+
* RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0)
|
| 22 |
+
* RFC 8297: An HTTP Status Code for Indicating Hints
|
| 23 |
+
* RFC 8470: Using Early Data in HTTP
|
| 24 |
+
"""
|
| 25 |
+
def __new__(cls, value, phrase, description=''):
|
| 26 |
+
obj = int.__new__(cls, value)
|
| 27 |
+
obj._value_ = value
|
| 28 |
+
|
| 29 |
+
obj.phrase = phrase
|
| 30 |
+
obj.description = description
|
| 31 |
+
return obj
|
| 32 |
+
|
| 33 |
+
# informational
|
| 34 |
+
CONTINUE = 100, 'Continue', 'Request received, please continue'
|
| 35 |
+
SWITCHING_PROTOCOLS = (101, 'Switching Protocols',
|
| 36 |
+
'Switching to new protocol; obey Upgrade header')
|
| 37 |
+
PROCESSING = 102, 'Processing'
|
| 38 |
+
EARLY_HINTS = 103, 'Early Hints'
|
| 39 |
+
|
| 40 |
+
# success
|
| 41 |
+
OK = 200, 'OK', 'Request fulfilled, document follows'
|
| 42 |
+
CREATED = 201, 'Created', 'Document created, URL follows'
|
| 43 |
+
ACCEPTED = (202, 'Accepted',
|
| 44 |
+
'Request accepted, processing continues off-line')
|
| 45 |
+
NON_AUTHORITATIVE_INFORMATION = (203,
|
| 46 |
+
'Non-Authoritative Information', 'Request fulfilled from cache')
|
| 47 |
+
NO_CONTENT = 204, 'No Content', 'Request fulfilled, nothing follows'
|
| 48 |
+
RESET_CONTENT = 205, 'Reset Content', 'Clear input form for further input'
|
| 49 |
+
PARTIAL_CONTENT = 206, 'Partial Content', 'Partial content follows'
|
| 50 |
+
MULTI_STATUS = 207, 'Multi-Status'
|
| 51 |
+
ALREADY_REPORTED = 208, 'Already Reported'
|
| 52 |
+
IM_USED = 226, 'IM Used'
|
| 53 |
+
|
| 54 |
+
# redirection
|
| 55 |
+
MULTIPLE_CHOICES = (300, 'Multiple Choices',
|
| 56 |
+
'Object has several resources -- see URI list')
|
| 57 |
+
MOVED_PERMANENTLY = (301, 'Moved Permanently',
|
| 58 |
+
'Object moved permanently -- see URI list')
|
| 59 |
+
FOUND = 302, 'Found', 'Object moved temporarily -- see URI list'
|
| 60 |
+
SEE_OTHER = 303, 'See Other', 'Object moved -- see Method and URL list'
|
| 61 |
+
NOT_MODIFIED = (304, 'Not Modified',
|
| 62 |
+
'Document has not changed since given time')
|
| 63 |
+
USE_PROXY = (305, 'Use Proxy',
|
| 64 |
+
'You must use proxy specified in Location to access this resource')
|
| 65 |
+
TEMPORARY_REDIRECT = (307, 'Temporary Redirect',
|
| 66 |
+
'Object moved temporarily -- see URI list')
|
| 67 |
+
PERMANENT_REDIRECT = (308, 'Permanent Redirect',
|
| 68 |
+
'Object moved permanently -- see URI list')
|
| 69 |
+
|
| 70 |
+
# client error
|
| 71 |
+
BAD_REQUEST = (400, 'Bad Request',
|
| 72 |
+
'Bad request syntax or unsupported method')
|
| 73 |
+
UNAUTHORIZED = (401, 'Unauthorized',
|
| 74 |
+
'No permission -- see authorization schemes')
|
| 75 |
+
PAYMENT_REQUIRED = (402, 'Payment Required',
|
| 76 |
+
'No payment -- see charging schemes')
|
| 77 |
+
FORBIDDEN = (403, 'Forbidden',
|
| 78 |
+
'Request forbidden -- authorization will not help')
|
| 79 |
+
NOT_FOUND = (404, 'Not Found',
|
| 80 |
+
'Nothing matches the given URI')
|
| 81 |
+
METHOD_NOT_ALLOWED = (405, 'Method Not Allowed',
|
| 82 |
+
'Specified method is invalid for this resource')
|
| 83 |
+
NOT_ACCEPTABLE = (406, 'Not Acceptable',
|
| 84 |
+
'URI not available in preferred format')
|
| 85 |
+
PROXY_AUTHENTICATION_REQUIRED = (407,
|
| 86 |
+
'Proxy Authentication Required',
|
| 87 |
+
'You must authenticate with this proxy before proceeding')
|
| 88 |
+
REQUEST_TIMEOUT = (408, 'Request Timeout',
|
| 89 |
+
'Request timed out; try again later')
|
| 90 |
+
CONFLICT = 409, 'Conflict', 'Request conflict'
|
| 91 |
+
GONE = (410, 'Gone',
|
| 92 |
+
'URI no longer exists and has been permanently removed')
|
| 93 |
+
LENGTH_REQUIRED = (411, 'Length Required',
|
| 94 |
+
'Client must specify Content-Length')
|
| 95 |
+
PRECONDITION_FAILED = (412, 'Precondition Failed',
|
| 96 |
+
'Precondition in headers is false')
|
| 97 |
+
REQUEST_ENTITY_TOO_LARGE = (413, 'Request Entity Too Large',
|
| 98 |
+
'Entity is too large')
|
| 99 |
+
REQUEST_URI_TOO_LONG = (414, 'Request-URI Too Long',
|
| 100 |
+
'URI is too long')
|
| 101 |
+
UNSUPPORTED_MEDIA_TYPE = (415, 'Unsupported Media Type',
|
| 102 |
+
'Entity body in unsupported format')
|
| 103 |
+
REQUESTED_RANGE_NOT_SATISFIABLE = (416,
|
| 104 |
+
'Requested Range Not Satisfiable',
|
| 105 |
+
'Cannot satisfy request range')
|
| 106 |
+
EXPECTATION_FAILED = (417, 'Expectation Failed',
|
| 107 |
+
'Expect condition could not be satisfied')
|
| 108 |
+
IM_A_TEAPOT = (418, 'I\'m a Teapot',
|
| 109 |
+
'Server refuses to brew coffee because it is a teapot.')
|
| 110 |
+
MISDIRECTED_REQUEST = (421, 'Misdirected Request',
|
| 111 |
+
'Server is not able to produce a response')
|
| 112 |
+
UNPROCESSABLE_ENTITY = 422, 'Unprocessable Entity'
|
| 113 |
+
LOCKED = 423, 'Locked'
|
| 114 |
+
FAILED_DEPENDENCY = 424, 'Failed Dependency'
|
| 115 |
+
TOO_EARLY = 425, 'Too Early'
|
| 116 |
+
UPGRADE_REQUIRED = 426, 'Upgrade Required'
|
| 117 |
+
PRECONDITION_REQUIRED = (428, 'Precondition Required',
|
| 118 |
+
'The origin server requires the request to be conditional')
|
| 119 |
+
TOO_MANY_REQUESTS = (429, 'Too Many Requests',
|
| 120 |
+
'The user has sent too many requests in '
|
| 121 |
+
'a given amount of time ("rate limiting")')
|
| 122 |
+
REQUEST_HEADER_FIELDS_TOO_LARGE = (431,
|
| 123 |
+
'Request Header Fields Too Large',
|
| 124 |
+
'The server is unwilling to process the request because its header '
|
| 125 |
+
'fields are too large')
|
| 126 |
+
UNAVAILABLE_FOR_LEGAL_REASONS = (451,
|
| 127 |
+
'Unavailable For Legal Reasons',
|
| 128 |
+
'The server is denying access to the '
|
| 129 |
+
'resource as a consequence of a legal demand')
|
| 130 |
+
|
| 131 |
+
# server errors
|
| 132 |
+
INTERNAL_SERVER_ERROR = (500, 'Internal Server Error',
|
| 133 |
+
'Server got itself in trouble')
|
| 134 |
+
NOT_IMPLEMENTED = (501, 'Not Implemented',
|
| 135 |
+
'Server does not support this operation')
|
| 136 |
+
BAD_GATEWAY = (502, 'Bad Gateway',
|
| 137 |
+
'Invalid responses from another server/proxy')
|
| 138 |
+
SERVICE_UNAVAILABLE = (503, 'Service Unavailable',
|
| 139 |
+
'The server cannot process the request due to a high load')
|
| 140 |
+
GATEWAY_TIMEOUT = (504, 'Gateway Timeout',
|
| 141 |
+
'The gateway server did not receive a timely response')
|
| 142 |
+
HTTP_VERSION_NOT_SUPPORTED = (505, 'HTTP Version Not Supported',
|
| 143 |
+
'Cannot fulfill request')
|
| 144 |
+
VARIANT_ALSO_NEGOTIATES = 506, 'Variant Also Negotiates'
|
| 145 |
+
INSUFFICIENT_STORAGE = 507, 'Insufficient Storage'
|
| 146 |
+
LOOP_DETECTED = 508, 'Loop Detected'
|
| 147 |
+
NOT_EXTENDED = 510, 'Not Extended'
|
| 148 |
+
NETWORK_AUTHENTICATION_REQUIRED = (511,
|
| 149 |
+
'Network Authentication Required',
|
| 150 |
+
'The client needs to authenticate to gain network access')
|
evalkit_llava/lib/python3.10/http/__pycache__/cookiejar.cpython-310.pyc
ADDED
|
Binary file (53.7 kB). View file
|
|
|
evalkit_llava/lib/python3.10/http/__pycache__/server.cpython-310.pyc
ADDED
|
Binary file (35.4 kB). View file
|
|
|
evalkit_llava/lib/python3.10/http/client.py
ADDED
|
@@ -0,0 +1,1526 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""HTTP/1.1 client library
|
| 2 |
+
|
| 3 |
+
<intro stuff goes here>
|
| 4 |
+
<other stuff, too>
|
| 5 |
+
|
| 6 |
+
HTTPConnection goes through a number of "states", which define when a client
|
| 7 |
+
may legally make another request or fetch the response for a particular
|
| 8 |
+
request. This diagram details these state transitions:
|
| 9 |
+
|
| 10 |
+
(null)
|
| 11 |
+
|
|
| 12 |
+
| HTTPConnection()
|
| 13 |
+
v
|
| 14 |
+
Idle
|
| 15 |
+
|
|
| 16 |
+
| putrequest()
|
| 17 |
+
v
|
| 18 |
+
Request-started
|
| 19 |
+
|
|
| 20 |
+
| ( putheader() )* endheaders()
|
| 21 |
+
v
|
| 22 |
+
Request-sent
|
| 23 |
+
|\_____________________________
|
| 24 |
+
| | getresponse() raises
|
| 25 |
+
| response = getresponse() | ConnectionError
|
| 26 |
+
v v
|
| 27 |
+
Unread-response Idle
|
| 28 |
+
[Response-headers-read]
|
| 29 |
+
|\____________________
|
| 30 |
+
| |
|
| 31 |
+
| response.read() | putrequest()
|
| 32 |
+
v v
|
| 33 |
+
Idle Req-started-unread-response
|
| 34 |
+
______/|
|
| 35 |
+
/ |
|
| 36 |
+
response.read() | | ( putheader() )* endheaders()
|
| 37 |
+
v v
|
| 38 |
+
Request-started Req-sent-unread-response
|
| 39 |
+
|
|
| 40 |
+
| response.read()
|
| 41 |
+
v
|
| 42 |
+
Request-sent
|
| 43 |
+
|
| 44 |
+
This diagram presents the following rules:
|
| 45 |
+
-- a second request may not be started until {response-headers-read}
|
| 46 |
+
-- a response [object] cannot be retrieved until {request-sent}
|
| 47 |
+
-- there is no differentiation between an unread response body and a
|
| 48 |
+
partially read response body
|
| 49 |
+
|
| 50 |
+
Note: this enforcement is applied by the HTTPConnection class. The
|
| 51 |
+
HTTPResponse class does not enforce this state machine, which
|
| 52 |
+
implies sophisticated clients may accelerate the request/response
|
| 53 |
+
pipeline. Caution should be taken, though: accelerating the states
|
| 54 |
+
beyond the above pattern may imply knowledge of the server's
|
| 55 |
+
connection-close behavior for certain requests. For example, it
|
| 56 |
+
is impossible to tell whether the server will close the connection
|
| 57 |
+
UNTIL the response headers have been read; this means that further
|
| 58 |
+
requests cannot be placed into the pipeline until it is known that
|
| 59 |
+
the server will NOT be closing the connection.
|
| 60 |
+
|
| 61 |
+
Logical State __state __response
|
| 62 |
+
------------- ------- ----------
|
| 63 |
+
Idle _CS_IDLE None
|
| 64 |
+
Request-started _CS_REQ_STARTED None
|
| 65 |
+
Request-sent _CS_REQ_SENT None
|
| 66 |
+
Unread-response _CS_IDLE <response_class>
|
| 67 |
+
Req-started-unread-response _CS_REQ_STARTED <response_class>
|
| 68 |
+
Req-sent-unread-response _CS_REQ_SENT <response_class>
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
import email.parser
|
| 72 |
+
import email.message
|
| 73 |
+
import errno
|
| 74 |
+
import http
|
| 75 |
+
import io
|
| 76 |
+
import re
|
| 77 |
+
import socket
|
| 78 |
+
import sys
|
| 79 |
+
import collections.abc
|
| 80 |
+
from urllib.parse import urlsplit
|
| 81 |
+
|
| 82 |
+
# HTTPMessage, parse_headers(), and the HTTP status code constants are
|
| 83 |
+
# intentionally omitted for simplicity
|
| 84 |
+
__all__ = ["HTTPResponse", "HTTPConnection",
|
| 85 |
+
"HTTPException", "NotConnected", "UnknownProtocol",
|
| 86 |
+
"UnknownTransferEncoding", "UnimplementedFileMode",
|
| 87 |
+
"IncompleteRead", "InvalidURL", "ImproperConnectionState",
|
| 88 |
+
"CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
|
| 89 |
+
"BadStatusLine", "LineTooLong", "RemoteDisconnected", "error",
|
| 90 |
+
"responses"]
|
| 91 |
+
|
| 92 |
+
HTTP_PORT = 80
|
| 93 |
+
HTTPS_PORT = 443
|
| 94 |
+
|
| 95 |
+
_UNKNOWN = 'UNKNOWN'
|
| 96 |
+
|
| 97 |
+
# connection states
|
| 98 |
+
_CS_IDLE = 'Idle'
|
| 99 |
+
_CS_REQ_STARTED = 'Request-started'
|
| 100 |
+
_CS_REQ_SENT = 'Request-sent'
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# hack to maintain backwards compatibility
|
| 104 |
+
globals().update(http.HTTPStatus.__members__)
|
| 105 |
+
|
| 106 |
+
# another hack to maintain backwards compatibility
|
| 107 |
+
# Mapping status codes to official W3C names
|
| 108 |
+
responses = {v: v.phrase for v in http.HTTPStatus.__members__.values()}
|
| 109 |
+
|
| 110 |
+
# maximal line length when calling readline().
|
| 111 |
+
_MAXLINE = 65536
|
| 112 |
+
_MAXHEADERS = 100
|
| 113 |
+
|
| 114 |
+
# Header name/value ABNF (http://tools.ietf.org/html/rfc7230#section-3.2)
|
| 115 |
+
#
|
| 116 |
+
# VCHAR = %x21-7E
|
| 117 |
+
# obs-text = %x80-FF
|
| 118 |
+
# header-field = field-name ":" OWS field-value OWS
|
| 119 |
+
# field-name = token
|
| 120 |
+
# field-value = *( field-content / obs-fold )
|
| 121 |
+
# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
|
| 122 |
+
# field-vchar = VCHAR / obs-text
|
| 123 |
+
#
|
| 124 |
+
# obs-fold = CRLF 1*( SP / HTAB )
|
| 125 |
+
# ; obsolete line folding
|
| 126 |
+
# ; see Section 3.2.4
|
| 127 |
+
|
| 128 |
+
# token = 1*tchar
|
| 129 |
+
#
|
| 130 |
+
# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
|
| 131 |
+
# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
|
| 132 |
+
# / DIGIT / ALPHA
|
| 133 |
+
# ; any VCHAR, except delimiters
|
| 134 |
+
#
|
| 135 |
+
# VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1
|
| 136 |
+
|
| 137 |
+
# the patterns for both name and value are more lenient than RFC
|
| 138 |
+
# definitions to allow for backwards compatibility
|
| 139 |
+
_is_legal_header_name = re.compile(rb'[^:\s][^:\r\n]*').fullmatch
|
| 140 |
+
_is_illegal_header_value = re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
|
| 141 |
+
|
| 142 |
+
# These characters are not allowed within HTTP URL paths.
|
| 143 |
+
# See https://tools.ietf.org/html/rfc3986#section-3.3 and the
|
| 144 |
+
# https://tools.ietf.org/html/rfc3986#appendix-A pchar definition.
|
| 145 |
+
# Prevents CVE-2019-9740. Includes control characters such as \r\n.
|
| 146 |
+
# We don't restrict chars above \x7f as putrequest() limits us to ASCII.
|
| 147 |
+
_contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f]')
|
| 148 |
+
# Arguably only these _should_ allowed:
|
| 149 |
+
# _is_allowed_url_pchars_re = re.compile(r"^[/!$&'()*+,;=:@%a-zA-Z0-9._~-]+$")
|
| 150 |
+
# We are more lenient for assumed real world compatibility purposes.
|
| 151 |
+
|
| 152 |
+
# These characters are not allowed within HTTP method names
|
| 153 |
+
# to prevent http header injection.
|
| 154 |
+
_contains_disallowed_method_pchar_re = re.compile('[\x00-\x1f]')
|
| 155 |
+
|
| 156 |
+
# We always set the Content-Length header for these methods because some
|
| 157 |
+
# servers will otherwise respond with a 411
|
| 158 |
+
_METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _encode(data, name='data'):
|
| 162 |
+
"""Call data.encode("latin-1") but show a better error message."""
|
| 163 |
+
try:
|
| 164 |
+
return data.encode("latin-1")
|
| 165 |
+
except UnicodeEncodeError as err:
|
| 166 |
+
raise UnicodeEncodeError(
|
| 167 |
+
err.encoding,
|
| 168 |
+
err.object,
|
| 169 |
+
err.start,
|
| 170 |
+
err.end,
|
| 171 |
+
"%s (%.20r) is not valid Latin-1. Use %s.encode('utf-8') "
|
| 172 |
+
"if you want to send it encoded in UTF-8." %
|
| 173 |
+
(name.title(), data[err.start:err.end], name)) from None
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class HTTPMessage(email.message.Message):
|
| 177 |
+
# XXX The only usage of this method is in
|
| 178 |
+
# http.server.CGIHTTPRequestHandler. Maybe move the code there so
|
| 179 |
+
# that it doesn't need to be part of the public API. The API has
|
| 180 |
+
# never been defined so this could cause backwards compatibility
|
| 181 |
+
# issues.
|
| 182 |
+
|
| 183 |
+
def getallmatchingheaders(self, name):
|
| 184 |
+
"""Find all header lines matching a given header name.
|
| 185 |
+
|
| 186 |
+
Look through the list of headers and find all lines matching a given
|
| 187 |
+
header name (and their continuation lines). A list of the lines is
|
| 188 |
+
returned, without interpretation. If the header does not occur, an
|
| 189 |
+
empty list is returned. If the header occurs multiple times, all
|
| 190 |
+
occurrences are returned. Case is not important in the header name.
|
| 191 |
+
|
| 192 |
+
"""
|
| 193 |
+
name = name.lower() + ':'
|
| 194 |
+
n = len(name)
|
| 195 |
+
lst = []
|
| 196 |
+
hit = 0
|
| 197 |
+
for line in self.keys():
|
| 198 |
+
if line[:n].lower() == name:
|
| 199 |
+
hit = 1
|
| 200 |
+
elif not line[:1].isspace():
|
| 201 |
+
hit = 0
|
| 202 |
+
if hit:
|
| 203 |
+
lst.append(line)
|
| 204 |
+
return lst
|
| 205 |
+
|
| 206 |
+
def _read_headers(fp):
|
| 207 |
+
"""Reads potential header lines into a list from a file pointer.
|
| 208 |
+
|
| 209 |
+
Length of line is limited by _MAXLINE, and number of
|
| 210 |
+
headers is limited by _MAXHEADERS.
|
| 211 |
+
"""
|
| 212 |
+
headers = []
|
| 213 |
+
while True:
|
| 214 |
+
line = fp.readline(_MAXLINE + 1)
|
| 215 |
+
if len(line) > _MAXLINE:
|
| 216 |
+
raise LineTooLong("header line")
|
| 217 |
+
headers.append(line)
|
| 218 |
+
if len(headers) > _MAXHEADERS:
|
| 219 |
+
raise HTTPException("got more than %d headers" % _MAXHEADERS)
|
| 220 |
+
if line in (b'\r\n', b'\n', b''):
|
| 221 |
+
break
|
| 222 |
+
return headers
|
| 223 |
+
|
| 224 |
+
def parse_headers(fp, _class=HTTPMessage):
|
| 225 |
+
"""Parses only RFC2822 headers from a file pointer.
|
| 226 |
+
|
| 227 |
+
email Parser wants to see strings rather than bytes.
|
| 228 |
+
But a TextIOWrapper around self.rfile would buffer too many bytes
|
| 229 |
+
from the stream, bytes which we later need to read as bytes.
|
| 230 |
+
So we read the correct bytes here, as bytes, for email Parser
|
| 231 |
+
to parse.
|
| 232 |
+
|
| 233 |
+
"""
|
| 234 |
+
headers = _read_headers(fp)
|
| 235 |
+
hstring = b''.join(headers).decode('iso-8859-1')
|
| 236 |
+
return email.parser.Parser(_class=_class).parsestr(hstring)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class HTTPResponse(io.BufferedIOBase):
|
| 240 |
+
|
| 241 |
+
# See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
|
| 242 |
+
|
| 243 |
+
# The bytes from the socket object are iso-8859-1 strings.
|
| 244 |
+
# See RFC 2616 sec 2.2 which notes an exception for MIME-encoded
|
| 245 |
+
# text following RFC 2047. The basic status line parsing only
|
| 246 |
+
# accepts iso-8859-1.
|
| 247 |
+
|
| 248 |
+
def __init__(self, sock, debuglevel=0, method=None, url=None):
|
| 249 |
+
# If the response includes a content-length header, we need to
|
| 250 |
+
# make sure that the client doesn't read more than the
|
| 251 |
+
# specified number of bytes. If it does, it will block until
|
| 252 |
+
# the server times out and closes the connection. This will
|
| 253 |
+
# happen if a self.fp.read() is done (without a size) whether
|
| 254 |
+
# self.fp is buffered or not. So, no self.fp.read() by
|
| 255 |
+
# clients unless they know what they are doing.
|
| 256 |
+
self.fp = sock.makefile("rb")
|
| 257 |
+
self.debuglevel = debuglevel
|
| 258 |
+
self._method = method
|
| 259 |
+
|
| 260 |
+
# The HTTPResponse object is returned via urllib. The clients
|
| 261 |
+
# of http and urllib expect different attributes for the
|
| 262 |
+
# headers. headers is used here and supports urllib. msg is
|
| 263 |
+
# provided as a backwards compatibility layer for http
|
| 264 |
+
# clients.
|
| 265 |
+
|
| 266 |
+
self.headers = self.msg = None
|
| 267 |
+
|
| 268 |
+
# from the Status-Line of the response
|
| 269 |
+
self.version = _UNKNOWN # HTTP-Version
|
| 270 |
+
self.status = _UNKNOWN # Status-Code
|
| 271 |
+
self.reason = _UNKNOWN # Reason-Phrase
|
| 272 |
+
|
| 273 |
+
self.chunked = _UNKNOWN # is "chunked" being used?
|
| 274 |
+
self.chunk_left = _UNKNOWN # bytes left to read in current chunk
|
| 275 |
+
self.length = _UNKNOWN # number of bytes left in response
|
| 276 |
+
self.will_close = _UNKNOWN # conn will close at end of response
|
| 277 |
+
|
| 278 |
+
def _read_status(self):
|
| 279 |
+
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
|
| 280 |
+
if len(line) > _MAXLINE:
|
| 281 |
+
raise LineTooLong("status line")
|
| 282 |
+
if self.debuglevel > 0:
|
| 283 |
+
print("reply:", repr(line))
|
| 284 |
+
if not line:
|
| 285 |
+
# Presumably, the server closed the connection before
|
| 286 |
+
# sending a valid response.
|
| 287 |
+
raise RemoteDisconnected("Remote end closed connection without"
|
| 288 |
+
" response")
|
| 289 |
+
try:
|
| 290 |
+
version, status, reason = line.split(None, 2)
|
| 291 |
+
except ValueError:
|
| 292 |
+
try:
|
| 293 |
+
version, status = line.split(None, 1)
|
| 294 |
+
reason = ""
|
| 295 |
+
except ValueError:
|
| 296 |
+
# empty version will cause next test to fail.
|
| 297 |
+
version = ""
|
| 298 |
+
if not version.startswith("HTTP/"):
|
| 299 |
+
self._close_conn()
|
| 300 |
+
raise BadStatusLine(line)
|
| 301 |
+
|
| 302 |
+
# The status code is a three-digit number
|
| 303 |
+
try:
|
| 304 |
+
status = int(status)
|
| 305 |
+
if status < 100 or status > 999:
|
| 306 |
+
raise BadStatusLine(line)
|
| 307 |
+
except ValueError:
|
| 308 |
+
raise BadStatusLine(line)
|
| 309 |
+
return version, status, reason
|
| 310 |
+
|
| 311 |
+
def begin(self):
|
| 312 |
+
if self.headers is not None:
|
| 313 |
+
# we've already started reading the response
|
| 314 |
+
return
|
| 315 |
+
|
| 316 |
+
# read until we get a non-100 response
|
| 317 |
+
while True:
|
| 318 |
+
version, status, reason = self._read_status()
|
| 319 |
+
if status != CONTINUE:
|
| 320 |
+
break
|
| 321 |
+
# skip the header from the 100 response
|
| 322 |
+
skipped_headers = _read_headers(self.fp)
|
| 323 |
+
if self.debuglevel > 0:
|
| 324 |
+
print("headers:", skipped_headers)
|
| 325 |
+
del skipped_headers
|
| 326 |
+
|
| 327 |
+
self.code = self.status = status
|
| 328 |
+
self.reason = reason.strip()
|
| 329 |
+
if version in ("HTTP/1.0", "HTTP/0.9"):
|
| 330 |
+
# Some servers might still return "0.9", treat it as 1.0 anyway
|
| 331 |
+
self.version = 10
|
| 332 |
+
elif version.startswith("HTTP/1."):
|
| 333 |
+
self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
|
| 334 |
+
else:
|
| 335 |
+
raise UnknownProtocol(version)
|
| 336 |
+
|
| 337 |
+
self.headers = self.msg = parse_headers(self.fp)
|
| 338 |
+
|
| 339 |
+
if self.debuglevel > 0:
|
| 340 |
+
for hdr, val in self.headers.items():
|
| 341 |
+
print("header:", hdr + ":", val)
|
| 342 |
+
|
| 343 |
+
# are we using the chunked-style of transfer encoding?
|
| 344 |
+
tr_enc = self.headers.get("transfer-encoding")
|
| 345 |
+
if tr_enc and tr_enc.lower() == "chunked":
|
| 346 |
+
self.chunked = True
|
| 347 |
+
self.chunk_left = None
|
| 348 |
+
else:
|
| 349 |
+
self.chunked = False
|
| 350 |
+
|
| 351 |
+
# will the connection close at the end of the response?
|
| 352 |
+
self.will_close = self._check_close()
|
| 353 |
+
|
| 354 |
+
# do we have a Content-Length?
|
| 355 |
+
# NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
|
| 356 |
+
self.length = None
|
| 357 |
+
length = self.headers.get("content-length")
|
| 358 |
+
if length and not self.chunked:
|
| 359 |
+
try:
|
| 360 |
+
self.length = int(length)
|
| 361 |
+
except ValueError:
|
| 362 |
+
self.length = None
|
| 363 |
+
else:
|
| 364 |
+
if self.length < 0: # ignore nonsensical negative lengths
|
| 365 |
+
self.length = None
|
| 366 |
+
else:
|
| 367 |
+
self.length = None
|
| 368 |
+
|
| 369 |
+
# does the body have a fixed length? (of zero)
|
| 370 |
+
if (status == NO_CONTENT or status == NOT_MODIFIED or
|
| 371 |
+
100 <= status < 200 or # 1xx codes
|
| 372 |
+
self._method == "HEAD"):
|
| 373 |
+
self.length = 0
|
| 374 |
+
|
| 375 |
+
# if the connection remains open, and we aren't using chunked, and
|
| 376 |
+
# a content-length was not provided, then assume that the connection
|
| 377 |
+
# WILL close.
|
| 378 |
+
if (not self.will_close and
|
| 379 |
+
not self.chunked and
|
| 380 |
+
self.length is None):
|
| 381 |
+
self.will_close = True
|
| 382 |
+
|
| 383 |
+
def _check_close(self):
|
| 384 |
+
conn = self.headers.get("connection")
|
| 385 |
+
if self.version == 11:
|
| 386 |
+
# An HTTP/1.1 proxy is assumed to stay open unless
|
| 387 |
+
# explicitly closed.
|
| 388 |
+
if conn and "close" in conn.lower():
|
| 389 |
+
return True
|
| 390 |
+
return False
|
| 391 |
+
|
| 392 |
+
# Some HTTP/1.0 implementations have support for persistent
|
| 393 |
+
# connections, using rules different than HTTP/1.1.
|
| 394 |
+
|
| 395 |
+
# For older HTTP, Keep-Alive indicates persistent connection.
|
| 396 |
+
if self.headers.get("keep-alive"):
|
| 397 |
+
return False
|
| 398 |
+
|
| 399 |
+
# At least Akamai returns a "Connection: Keep-Alive" header,
|
| 400 |
+
# which was supposed to be sent by the client.
|
| 401 |
+
if conn and "keep-alive" in conn.lower():
|
| 402 |
+
return False
|
| 403 |
+
|
| 404 |
+
# Proxy-Connection is a netscape hack.
|
| 405 |
+
pconn = self.headers.get("proxy-connection")
|
| 406 |
+
if pconn and "keep-alive" in pconn.lower():
|
| 407 |
+
return False
|
| 408 |
+
|
| 409 |
+
# otherwise, assume it will close
|
| 410 |
+
return True
|
| 411 |
+
|
| 412 |
+
def _close_conn(self):
|
| 413 |
+
fp = self.fp
|
| 414 |
+
self.fp = None
|
| 415 |
+
fp.close()
|
| 416 |
+
|
| 417 |
+
def close(self):
|
| 418 |
+
try:
|
| 419 |
+
super().close() # set "closed" flag
|
| 420 |
+
finally:
|
| 421 |
+
if self.fp:
|
| 422 |
+
self._close_conn()
|
| 423 |
+
|
| 424 |
+
# These implementations are for the benefit of io.BufferedReader.
|
| 425 |
+
|
| 426 |
+
# XXX This class should probably be revised to act more like
|
| 427 |
+
# the "raw stream" that BufferedReader expects.
|
| 428 |
+
|
| 429 |
+
def flush(self):
|
| 430 |
+
super().flush()
|
| 431 |
+
if self.fp:
|
| 432 |
+
self.fp.flush()
|
| 433 |
+
|
| 434 |
+
def readable(self):
|
| 435 |
+
"""Always returns True"""
|
| 436 |
+
return True
|
| 437 |
+
|
| 438 |
+
# End of "raw stream" methods
|
| 439 |
+
|
| 440 |
+
def isclosed(self):
|
| 441 |
+
"""True if the connection is closed."""
|
| 442 |
+
# NOTE: it is possible that we will not ever call self.close(). This
|
| 443 |
+
# case occurs when will_close is TRUE, length is None, and we
|
| 444 |
+
# read up to the last byte, but NOT past it.
|
| 445 |
+
#
|
| 446 |
+
# IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
|
| 447 |
+
# called, meaning self.isclosed() is meaningful.
|
| 448 |
+
return self.fp is None
|
| 449 |
+
|
| 450 |
+
def read(self, amt=None):
|
| 451 |
+
"""Read and return the response body, or up to the next amt bytes."""
|
| 452 |
+
if self.fp is None:
|
| 453 |
+
return b""
|
| 454 |
+
|
| 455 |
+
if self._method == "HEAD":
|
| 456 |
+
self._close_conn()
|
| 457 |
+
return b""
|
| 458 |
+
|
| 459 |
+
if self.chunked:
|
| 460 |
+
return self._read_chunked(amt)
|
| 461 |
+
|
| 462 |
+
if amt is not None:
|
| 463 |
+
if self.length is not None and amt > self.length:
|
| 464 |
+
# clip the read to the "end of response"
|
| 465 |
+
amt = self.length
|
| 466 |
+
s = self.fp.read(amt)
|
| 467 |
+
if not s and amt:
|
| 468 |
+
# Ideally, we would raise IncompleteRead if the content-length
|
| 469 |
+
# wasn't satisfied, but it might break compatibility.
|
| 470 |
+
self._close_conn()
|
| 471 |
+
elif self.length is not None:
|
| 472 |
+
self.length -= len(s)
|
| 473 |
+
if not self.length:
|
| 474 |
+
self._close_conn()
|
| 475 |
+
return s
|
| 476 |
+
else:
|
| 477 |
+
# Amount is not given (unbounded read) so we must check self.length
|
| 478 |
+
if self.length is None:
|
| 479 |
+
s = self.fp.read()
|
| 480 |
+
else:
|
| 481 |
+
try:
|
| 482 |
+
s = self._safe_read(self.length)
|
| 483 |
+
except IncompleteRead:
|
| 484 |
+
self._close_conn()
|
| 485 |
+
raise
|
| 486 |
+
self.length = 0
|
| 487 |
+
self._close_conn() # we read everything
|
| 488 |
+
return s
|
| 489 |
+
|
| 490 |
+
def readinto(self, b):
|
| 491 |
+
"""Read up to len(b) bytes into bytearray b and return the number
|
| 492 |
+
of bytes read.
|
| 493 |
+
"""
|
| 494 |
+
|
| 495 |
+
if self.fp is None:
|
| 496 |
+
return 0
|
| 497 |
+
|
| 498 |
+
if self._method == "HEAD":
|
| 499 |
+
self._close_conn()
|
| 500 |
+
return 0
|
| 501 |
+
|
| 502 |
+
if self.chunked:
|
| 503 |
+
return self._readinto_chunked(b)
|
| 504 |
+
|
| 505 |
+
if self.length is not None:
|
| 506 |
+
if len(b) > self.length:
|
| 507 |
+
# clip the read to the "end of response"
|
| 508 |
+
b = memoryview(b)[0:self.length]
|
| 509 |
+
|
| 510 |
+
# we do not use _safe_read() here because this may be a .will_close
|
| 511 |
+
# connection, and the user is reading more bytes than will be provided
|
| 512 |
+
# (for example, reading in 1k chunks)
|
| 513 |
+
n = self.fp.readinto(b)
|
| 514 |
+
if not n and b:
|
| 515 |
+
# Ideally, we would raise IncompleteRead if the content-length
|
| 516 |
+
# wasn't satisfied, but it might break compatibility.
|
| 517 |
+
self._close_conn()
|
| 518 |
+
elif self.length is not None:
|
| 519 |
+
self.length -= n
|
| 520 |
+
if not self.length:
|
| 521 |
+
self._close_conn()
|
| 522 |
+
return n
|
| 523 |
+
|
| 524 |
+
def _read_next_chunk_size(self):
|
| 525 |
+
# Read the next chunk size from the file
|
| 526 |
+
line = self.fp.readline(_MAXLINE + 1)
|
| 527 |
+
if len(line) > _MAXLINE:
|
| 528 |
+
raise LineTooLong("chunk size")
|
| 529 |
+
i = line.find(b";")
|
| 530 |
+
if i >= 0:
|
| 531 |
+
line = line[:i] # strip chunk-extensions
|
| 532 |
+
try:
|
| 533 |
+
return int(line, 16)
|
| 534 |
+
except ValueError:
|
| 535 |
+
# close the connection as protocol synchronisation is
|
| 536 |
+
# probably lost
|
| 537 |
+
self._close_conn()
|
| 538 |
+
raise
|
| 539 |
+
|
| 540 |
+
def _read_and_discard_trailer(self):
|
| 541 |
+
# read and discard trailer up to the CRLF terminator
|
| 542 |
+
### note: we shouldn't have any trailers!
|
| 543 |
+
while True:
|
| 544 |
+
line = self.fp.readline(_MAXLINE + 1)
|
| 545 |
+
if len(line) > _MAXLINE:
|
| 546 |
+
raise LineTooLong("trailer line")
|
| 547 |
+
if not line:
|
| 548 |
+
# a vanishingly small number of sites EOF without
|
| 549 |
+
# sending the trailer
|
| 550 |
+
break
|
| 551 |
+
if line in (b'\r\n', b'\n', b''):
|
| 552 |
+
break
|
| 553 |
+
|
| 554 |
+
def _get_chunk_left(self):
|
| 555 |
+
# return self.chunk_left, reading a new chunk if necessary.
|
| 556 |
+
# chunk_left == 0: at the end of the current chunk, need to close it
|
| 557 |
+
# chunk_left == None: No current chunk, should read next.
|
| 558 |
+
# This function returns non-zero or None if the last chunk has
|
| 559 |
+
# been read.
|
| 560 |
+
chunk_left = self.chunk_left
|
| 561 |
+
if not chunk_left: # Can be 0 or None
|
| 562 |
+
if chunk_left is not None:
|
| 563 |
+
# We are at the end of chunk, discard chunk end
|
| 564 |
+
self._safe_read(2) # toss the CRLF at the end of the chunk
|
| 565 |
+
try:
|
| 566 |
+
chunk_left = self._read_next_chunk_size()
|
| 567 |
+
except ValueError:
|
| 568 |
+
raise IncompleteRead(b'')
|
| 569 |
+
if chunk_left == 0:
|
| 570 |
+
# last chunk: 1*("0") [ chunk-extension ] CRLF
|
| 571 |
+
self._read_and_discard_trailer()
|
| 572 |
+
# we read everything; close the "file"
|
| 573 |
+
self._close_conn()
|
| 574 |
+
chunk_left = None
|
| 575 |
+
self.chunk_left = chunk_left
|
| 576 |
+
return chunk_left
|
| 577 |
+
|
| 578 |
+
def _read_chunked(self, amt=None):
|
| 579 |
+
assert self.chunked != _UNKNOWN
|
| 580 |
+
value = []
|
| 581 |
+
try:
|
| 582 |
+
while True:
|
| 583 |
+
chunk_left = self._get_chunk_left()
|
| 584 |
+
if chunk_left is None:
|
| 585 |
+
break
|
| 586 |
+
|
| 587 |
+
if amt is not None and amt <= chunk_left:
|
| 588 |
+
value.append(self._safe_read(amt))
|
| 589 |
+
self.chunk_left = chunk_left - amt
|
| 590 |
+
break
|
| 591 |
+
|
| 592 |
+
value.append(self._safe_read(chunk_left))
|
| 593 |
+
if amt is not None:
|
| 594 |
+
amt -= chunk_left
|
| 595 |
+
self.chunk_left = 0
|
| 596 |
+
return b''.join(value)
|
| 597 |
+
except IncompleteRead:
|
| 598 |
+
raise IncompleteRead(b''.join(value))
|
| 599 |
+
|
| 600 |
+
def _readinto_chunked(self, b):
|
| 601 |
+
assert self.chunked != _UNKNOWN
|
| 602 |
+
total_bytes = 0
|
| 603 |
+
mvb = memoryview(b)
|
| 604 |
+
try:
|
| 605 |
+
while True:
|
| 606 |
+
chunk_left = self._get_chunk_left()
|
| 607 |
+
if chunk_left is None:
|
| 608 |
+
return total_bytes
|
| 609 |
+
|
| 610 |
+
if len(mvb) <= chunk_left:
|
| 611 |
+
n = self._safe_readinto(mvb)
|
| 612 |
+
self.chunk_left = chunk_left - n
|
| 613 |
+
return total_bytes + n
|
| 614 |
+
|
| 615 |
+
temp_mvb = mvb[:chunk_left]
|
| 616 |
+
n = self._safe_readinto(temp_mvb)
|
| 617 |
+
mvb = mvb[n:]
|
| 618 |
+
total_bytes += n
|
| 619 |
+
self.chunk_left = 0
|
| 620 |
+
|
| 621 |
+
except IncompleteRead:
|
| 622 |
+
raise IncompleteRead(bytes(b[0:total_bytes]))
|
| 623 |
+
|
| 624 |
+
def _safe_read(self, amt):
|
| 625 |
+
"""Read the number of bytes requested.
|
| 626 |
+
|
| 627 |
+
This function should be used when <amt> bytes "should" be present for
|
| 628 |
+
reading. If the bytes are truly not available (due to EOF), then the
|
| 629 |
+
IncompleteRead exception can be used to detect the problem.
|
| 630 |
+
"""
|
| 631 |
+
data = self.fp.read(amt)
|
| 632 |
+
if len(data) < amt:
|
| 633 |
+
raise IncompleteRead(data, amt-len(data))
|
| 634 |
+
return data
|
| 635 |
+
|
| 636 |
+
def _safe_readinto(self, b):
|
| 637 |
+
"""Same as _safe_read, but for reading into a buffer."""
|
| 638 |
+
amt = len(b)
|
| 639 |
+
n = self.fp.readinto(b)
|
| 640 |
+
if n < amt:
|
| 641 |
+
raise IncompleteRead(bytes(b[:n]), amt-n)
|
| 642 |
+
return n
|
| 643 |
+
|
| 644 |
+
def read1(self, n=-1):
|
| 645 |
+
"""Read with at most one underlying system call. If at least one
|
| 646 |
+
byte is buffered, return that instead.
|
| 647 |
+
"""
|
| 648 |
+
if self.fp is None or self._method == "HEAD":
|
| 649 |
+
return b""
|
| 650 |
+
if self.chunked:
|
| 651 |
+
return self._read1_chunked(n)
|
| 652 |
+
if self.length is not None and (n < 0 or n > self.length):
|
| 653 |
+
n = self.length
|
| 654 |
+
result = self.fp.read1(n)
|
| 655 |
+
if not result and n:
|
| 656 |
+
self._close_conn()
|
| 657 |
+
elif self.length is not None:
|
| 658 |
+
self.length -= len(result)
|
| 659 |
+
return result
|
| 660 |
+
|
| 661 |
+
def peek(self, n=-1):
|
| 662 |
+
# Having this enables IOBase.readline() to read more than one
|
| 663 |
+
# byte at a time
|
| 664 |
+
if self.fp is None or self._method == "HEAD":
|
| 665 |
+
return b""
|
| 666 |
+
if self.chunked:
|
| 667 |
+
return self._peek_chunked(n)
|
| 668 |
+
return self.fp.peek(n)
|
| 669 |
+
|
| 670 |
+
def readline(self, limit=-1):
|
| 671 |
+
if self.fp is None or self._method == "HEAD":
|
| 672 |
+
return b""
|
| 673 |
+
if self.chunked:
|
| 674 |
+
# Fallback to IOBase readline which uses peek() and read()
|
| 675 |
+
return super().readline(limit)
|
| 676 |
+
if self.length is not None and (limit < 0 or limit > self.length):
|
| 677 |
+
limit = self.length
|
| 678 |
+
result = self.fp.readline(limit)
|
| 679 |
+
if not result and limit:
|
| 680 |
+
self._close_conn()
|
| 681 |
+
elif self.length is not None:
|
| 682 |
+
self.length -= len(result)
|
| 683 |
+
return result
|
| 684 |
+
|
| 685 |
+
def _read1_chunked(self, n):
|
| 686 |
+
# Strictly speaking, _get_chunk_left() may cause more than one read,
|
| 687 |
+
# but that is ok, since that is to satisfy the chunked protocol.
|
| 688 |
+
chunk_left = self._get_chunk_left()
|
| 689 |
+
if chunk_left is None or n == 0:
|
| 690 |
+
return b''
|
| 691 |
+
if not (0 <= n <= chunk_left):
|
| 692 |
+
n = chunk_left # if n is negative or larger than chunk_left
|
| 693 |
+
read = self.fp.read1(n)
|
| 694 |
+
self.chunk_left -= len(read)
|
| 695 |
+
if not read:
|
| 696 |
+
raise IncompleteRead(b"")
|
| 697 |
+
return read
|
| 698 |
+
|
| 699 |
+
def _peek_chunked(self, n):
|
| 700 |
+
# Strictly speaking, _get_chunk_left() may cause more than one read,
|
| 701 |
+
# but that is ok, since that is to satisfy the chunked protocol.
|
| 702 |
+
try:
|
| 703 |
+
chunk_left = self._get_chunk_left()
|
| 704 |
+
except IncompleteRead:
|
| 705 |
+
return b'' # peek doesn't worry about protocol
|
| 706 |
+
if chunk_left is None:
|
| 707 |
+
return b'' # eof
|
| 708 |
+
# peek is allowed to return more than requested. Just request the
|
| 709 |
+
# entire chunk, and truncate what we get.
|
| 710 |
+
return self.fp.peek(chunk_left)[:chunk_left]
|
| 711 |
+
|
| 712 |
+
def fileno(self):
|
| 713 |
+
return self.fp.fileno()
|
| 714 |
+
|
| 715 |
+
def getheader(self, name, default=None):
|
| 716 |
+
'''Returns the value of the header matching *name*.
|
| 717 |
+
|
| 718 |
+
If there are multiple matching headers, the values are
|
| 719 |
+
combined into a single string separated by commas and spaces.
|
| 720 |
+
|
| 721 |
+
If no matching header is found, returns *default* or None if
|
| 722 |
+
the *default* is not specified.
|
| 723 |
+
|
| 724 |
+
If the headers are unknown, raises http.client.ResponseNotReady.
|
| 725 |
+
|
| 726 |
+
'''
|
| 727 |
+
if self.headers is None:
|
| 728 |
+
raise ResponseNotReady()
|
| 729 |
+
headers = self.headers.get_all(name) or default
|
| 730 |
+
if isinstance(headers, str) or not hasattr(headers, '__iter__'):
|
| 731 |
+
return headers
|
| 732 |
+
else:
|
| 733 |
+
return ', '.join(headers)
|
| 734 |
+
|
| 735 |
+
def getheaders(self):
|
| 736 |
+
"""Return list of (header, value) tuples."""
|
| 737 |
+
if self.headers is None:
|
| 738 |
+
raise ResponseNotReady()
|
| 739 |
+
return list(self.headers.items())
|
| 740 |
+
|
| 741 |
+
# We override IOBase.__iter__ so that it doesn't check for closed-ness
|
| 742 |
+
|
| 743 |
+
def __iter__(self):
|
| 744 |
+
return self
|
| 745 |
+
|
| 746 |
+
# For compatibility with old-style urllib responses.
|
| 747 |
+
|
| 748 |
+
def info(self):
|
| 749 |
+
'''Returns an instance of the class mimetools.Message containing
|
| 750 |
+
meta-information associated with the URL.
|
| 751 |
+
|
| 752 |
+
When the method is HTTP, these headers are those returned by
|
| 753 |
+
the server at the head of the retrieved HTML page (including
|
| 754 |
+
Content-Length and Content-Type).
|
| 755 |
+
|
| 756 |
+
When the method is FTP, a Content-Length header will be
|
| 757 |
+
present if (as is now usual) the server passed back a file
|
| 758 |
+
length in response to the FTP retrieval request. A
|
| 759 |
+
Content-Type header will be present if the MIME type can be
|
| 760 |
+
guessed.
|
| 761 |
+
|
| 762 |
+
When the method is local-file, returned headers will include
|
| 763 |
+
a Date representing the file's last-modified time, a
|
| 764 |
+
Content-Length giving file size, and a Content-Type
|
| 765 |
+
containing a guess at the file's type. See also the
|
| 766 |
+
description of the mimetools module.
|
| 767 |
+
|
| 768 |
+
'''
|
| 769 |
+
return self.headers
|
| 770 |
+
|
| 771 |
+
def geturl(self):
|
| 772 |
+
'''Return the real URL of the page.
|
| 773 |
+
|
| 774 |
+
In some cases, the HTTP server redirects a client to another
|
| 775 |
+
URL. The urlopen() function handles this transparently, but in
|
| 776 |
+
some cases the caller needs to know which URL the client was
|
| 777 |
+
redirected to. The geturl() method can be used to get at this
|
| 778 |
+
redirected URL.
|
| 779 |
+
|
| 780 |
+
'''
|
| 781 |
+
return self.url
|
| 782 |
+
|
| 783 |
+
def getcode(self):
|
| 784 |
+
'''Return the HTTP status code that was sent with the response,
|
| 785 |
+
or None if the URL is not an HTTP URL.
|
| 786 |
+
|
| 787 |
+
'''
|
| 788 |
+
return self.status
|
| 789 |
+
|
| 790 |
+
class HTTPConnection:
|
| 791 |
+
|
| 792 |
+
_http_vsn = 11
|
| 793 |
+
_http_vsn_str = 'HTTP/1.1'
|
| 794 |
+
|
| 795 |
+
response_class = HTTPResponse
|
| 796 |
+
default_port = HTTP_PORT
|
| 797 |
+
auto_open = 1
|
| 798 |
+
debuglevel = 0
|
| 799 |
+
|
| 800 |
+
@staticmethod
|
| 801 |
+
def _is_textIO(stream):
|
| 802 |
+
"""Test whether a file-like object is a text or a binary stream.
|
| 803 |
+
"""
|
| 804 |
+
return isinstance(stream, io.TextIOBase)
|
| 805 |
+
|
| 806 |
+
@staticmethod
|
| 807 |
+
def _get_content_length(body, method):
|
| 808 |
+
"""Get the content-length based on the body.
|
| 809 |
+
|
| 810 |
+
If the body is None, we set Content-Length: 0 for methods that expect
|
| 811 |
+
a body (RFC 7230, Section 3.3.2). We also set the Content-Length for
|
| 812 |
+
any method if the body is a str or bytes-like object and not a file.
|
| 813 |
+
"""
|
| 814 |
+
if body is None:
|
| 815 |
+
# do an explicit check for not None here to distinguish
|
| 816 |
+
# between unset and set but empty
|
| 817 |
+
if method.upper() in _METHODS_EXPECTING_BODY:
|
| 818 |
+
return 0
|
| 819 |
+
else:
|
| 820 |
+
return None
|
| 821 |
+
|
| 822 |
+
if hasattr(body, 'read'):
|
| 823 |
+
# file-like object.
|
| 824 |
+
return None
|
| 825 |
+
|
| 826 |
+
try:
|
| 827 |
+
# does it implement the buffer protocol (bytes, bytearray, array)?
|
| 828 |
+
mv = memoryview(body)
|
| 829 |
+
return mv.nbytes
|
| 830 |
+
except TypeError:
|
| 831 |
+
pass
|
| 832 |
+
|
| 833 |
+
if isinstance(body, str):
|
| 834 |
+
return len(body)
|
| 835 |
+
|
| 836 |
+
return None
|
| 837 |
+
|
| 838 |
+
def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
|
| 839 |
+
source_address=None, blocksize=8192):
|
| 840 |
+
self.timeout = timeout
|
| 841 |
+
self.source_address = source_address
|
| 842 |
+
self.blocksize = blocksize
|
| 843 |
+
self.sock = None
|
| 844 |
+
self._buffer = []
|
| 845 |
+
self.__response = None
|
| 846 |
+
self.__state = _CS_IDLE
|
| 847 |
+
self._method = None
|
| 848 |
+
self._tunnel_host = None
|
| 849 |
+
self._tunnel_port = None
|
| 850 |
+
self._tunnel_headers = {}
|
| 851 |
+
|
| 852 |
+
(self.host, self.port) = self._get_hostport(host, port)
|
| 853 |
+
|
| 854 |
+
self._validate_host(self.host)
|
| 855 |
+
|
| 856 |
+
# This is stored as an instance variable to allow unit
|
| 857 |
+
# tests to replace it with a suitable mockup
|
| 858 |
+
self._create_connection = socket.create_connection
|
| 859 |
+
|
| 860 |
+
def set_tunnel(self, host, port=None, headers=None):
|
| 861 |
+
"""Set up host and port for HTTP CONNECT tunnelling.
|
| 862 |
+
|
| 863 |
+
In a connection that uses HTTP CONNECT tunneling, the host passed to the
|
| 864 |
+
constructor is used as a proxy server that relays all communication to
|
| 865 |
+
the endpoint passed to `set_tunnel`. This done by sending an HTTP
|
| 866 |
+
CONNECT request to the proxy server when the connection is established.
|
| 867 |
+
|
| 868 |
+
This method must be called before the HTTP connection has been
|
| 869 |
+
established.
|
| 870 |
+
|
| 871 |
+
The headers argument should be a mapping of extra HTTP headers to send
|
| 872 |
+
with the CONNECT request.
|
| 873 |
+
"""
|
| 874 |
+
|
| 875 |
+
if self.sock:
|
| 876 |
+
raise RuntimeError("Can't set up tunnel for established connection")
|
| 877 |
+
|
| 878 |
+
self._tunnel_host, self._tunnel_port = self._get_hostport(host, port)
|
| 879 |
+
if headers:
|
| 880 |
+
self._tunnel_headers = headers
|
| 881 |
+
else:
|
| 882 |
+
self._tunnel_headers.clear()
|
| 883 |
+
|
| 884 |
+
def _get_hostport(self, host, port):
|
| 885 |
+
if port is None:
|
| 886 |
+
i = host.rfind(':')
|
| 887 |
+
j = host.rfind(']') # ipv6 addresses have [...]
|
| 888 |
+
if i > j:
|
| 889 |
+
try:
|
| 890 |
+
port = int(host[i+1:])
|
| 891 |
+
except ValueError:
|
| 892 |
+
if host[i+1:] == "": # http://foo.com:/ == http://foo.com/
|
| 893 |
+
port = self.default_port
|
| 894 |
+
else:
|
| 895 |
+
raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
|
| 896 |
+
host = host[:i]
|
| 897 |
+
else:
|
| 898 |
+
port = self.default_port
|
| 899 |
+
if host and host[0] == '[' and host[-1] == ']':
|
| 900 |
+
host = host[1:-1]
|
| 901 |
+
|
| 902 |
+
return (host, port)
|
| 903 |
+
|
| 904 |
+
def set_debuglevel(self, level):
|
| 905 |
+
self.debuglevel = level
|
| 906 |
+
|
| 907 |
+
def _tunnel(self):
|
| 908 |
+
connect = b"CONNECT %s:%d HTTP/1.0\r\n" % (
|
| 909 |
+
self._tunnel_host.encode("ascii"), self._tunnel_port)
|
| 910 |
+
headers = [connect]
|
| 911 |
+
for header, value in self._tunnel_headers.items():
|
| 912 |
+
headers.append(f"{header}: {value}\r\n".encode("latin-1"))
|
| 913 |
+
headers.append(b"\r\n")
|
| 914 |
+
# Making a single send() call instead of one per line encourages
|
| 915 |
+
# the host OS to use a more optimal packet size instead of
|
| 916 |
+
# potentially emitting a series of small packets.
|
| 917 |
+
self.send(b"".join(headers))
|
| 918 |
+
del headers
|
| 919 |
+
|
| 920 |
+
response = self.response_class(self.sock, method=self._method)
|
| 921 |
+
(version, code, message) = response._read_status()
|
| 922 |
+
|
| 923 |
+
if code != http.HTTPStatus.OK:
|
| 924 |
+
self.close()
|
| 925 |
+
raise OSError(f"Tunnel connection failed: {code} {message.strip()}")
|
| 926 |
+
while True:
|
| 927 |
+
line = response.fp.readline(_MAXLINE + 1)
|
| 928 |
+
if len(line) > _MAXLINE:
|
| 929 |
+
raise LineTooLong("header line")
|
| 930 |
+
if not line:
|
| 931 |
+
# for sites which EOF without sending a trailer
|
| 932 |
+
break
|
| 933 |
+
if line in (b'\r\n', b'\n', b''):
|
| 934 |
+
break
|
| 935 |
+
|
| 936 |
+
if self.debuglevel > 0:
|
| 937 |
+
print('header:', line.decode())
|
| 938 |
+
|
| 939 |
+
def connect(self):
|
| 940 |
+
"""Connect to the host and port specified in __init__."""
|
| 941 |
+
sys.audit("http.client.connect", self, self.host, self.port)
|
| 942 |
+
self.sock = self._create_connection(
|
| 943 |
+
(self.host,self.port), self.timeout, self.source_address)
|
| 944 |
+
# Might fail in OSs that don't implement TCP_NODELAY
|
| 945 |
+
try:
|
| 946 |
+
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
| 947 |
+
except OSError as e:
|
| 948 |
+
if e.errno != errno.ENOPROTOOPT:
|
| 949 |
+
raise
|
| 950 |
+
|
| 951 |
+
if self._tunnel_host:
|
| 952 |
+
self._tunnel()
|
| 953 |
+
|
| 954 |
+
def close(self):
|
| 955 |
+
"""Close the connection to the HTTP server."""
|
| 956 |
+
self.__state = _CS_IDLE
|
| 957 |
+
try:
|
| 958 |
+
sock = self.sock
|
| 959 |
+
if sock:
|
| 960 |
+
self.sock = None
|
| 961 |
+
sock.close() # close it manually... there may be other refs
|
| 962 |
+
finally:
|
| 963 |
+
response = self.__response
|
| 964 |
+
if response:
|
| 965 |
+
self.__response = None
|
| 966 |
+
response.close()
|
| 967 |
+
|
| 968 |
+
def send(self, data):
|
| 969 |
+
"""Send `data' to the server.
|
| 970 |
+
``data`` can be a string object, a bytes object, an array object, a
|
| 971 |
+
file-like object that supports a .read() method, or an iterable object.
|
| 972 |
+
"""
|
| 973 |
+
|
| 974 |
+
if self.sock is None:
|
| 975 |
+
if self.auto_open:
|
| 976 |
+
self.connect()
|
| 977 |
+
else:
|
| 978 |
+
raise NotConnected()
|
| 979 |
+
|
| 980 |
+
if self.debuglevel > 0:
|
| 981 |
+
print("send:", repr(data))
|
| 982 |
+
if hasattr(data, "read") :
|
| 983 |
+
if self.debuglevel > 0:
|
| 984 |
+
print("sendIng a read()able")
|
| 985 |
+
encode = self._is_textIO(data)
|
| 986 |
+
if encode and self.debuglevel > 0:
|
| 987 |
+
print("encoding file using iso-8859-1")
|
| 988 |
+
while 1:
|
| 989 |
+
datablock = data.read(self.blocksize)
|
| 990 |
+
if not datablock:
|
| 991 |
+
break
|
| 992 |
+
if encode:
|
| 993 |
+
datablock = datablock.encode("iso-8859-1")
|
| 994 |
+
sys.audit("http.client.send", self, datablock)
|
| 995 |
+
self.sock.sendall(datablock)
|
| 996 |
+
return
|
| 997 |
+
sys.audit("http.client.send", self, data)
|
| 998 |
+
try:
|
| 999 |
+
self.sock.sendall(data)
|
| 1000 |
+
except TypeError:
|
| 1001 |
+
if isinstance(data, collections.abc.Iterable):
|
| 1002 |
+
for d in data:
|
| 1003 |
+
self.sock.sendall(d)
|
| 1004 |
+
else:
|
| 1005 |
+
raise TypeError("data should be a bytes-like object "
|
| 1006 |
+
"or an iterable, got %r" % type(data))
|
| 1007 |
+
|
| 1008 |
+
def _output(self, s):
|
| 1009 |
+
"""Add a line of output to the current request buffer.
|
| 1010 |
+
|
| 1011 |
+
Assumes that the line does *not* end with \\r\\n.
|
| 1012 |
+
"""
|
| 1013 |
+
self._buffer.append(s)
|
| 1014 |
+
|
| 1015 |
+
def _read_readable(self, readable):
|
| 1016 |
+
if self.debuglevel > 0:
|
| 1017 |
+
print("sendIng a read()able")
|
| 1018 |
+
encode = self._is_textIO(readable)
|
| 1019 |
+
if encode and self.debuglevel > 0:
|
| 1020 |
+
print("encoding file using iso-8859-1")
|
| 1021 |
+
while True:
|
| 1022 |
+
datablock = readable.read(self.blocksize)
|
| 1023 |
+
if not datablock:
|
| 1024 |
+
break
|
| 1025 |
+
if encode:
|
| 1026 |
+
datablock = datablock.encode("iso-8859-1")
|
| 1027 |
+
yield datablock
|
| 1028 |
+
|
| 1029 |
+
def _send_output(self, message_body=None, encode_chunked=False):
|
| 1030 |
+
"""Send the currently buffered request and clear the buffer.
|
| 1031 |
+
|
| 1032 |
+
Appends an extra \\r\\n to the buffer.
|
| 1033 |
+
A message_body may be specified, to be appended to the request.
|
| 1034 |
+
"""
|
| 1035 |
+
self._buffer.extend((b"", b""))
|
| 1036 |
+
msg = b"\r\n".join(self._buffer)
|
| 1037 |
+
del self._buffer[:]
|
| 1038 |
+
self.send(msg)
|
| 1039 |
+
|
| 1040 |
+
if message_body is not None:
|
| 1041 |
+
|
| 1042 |
+
# create a consistent interface to message_body
|
| 1043 |
+
if hasattr(message_body, 'read'):
|
| 1044 |
+
# Let file-like take precedence over byte-like. This
|
| 1045 |
+
# is needed to allow the current position of mmap'ed
|
| 1046 |
+
# files to be taken into account.
|
| 1047 |
+
chunks = self._read_readable(message_body)
|
| 1048 |
+
else:
|
| 1049 |
+
try:
|
| 1050 |
+
# this is solely to check to see if message_body
|
| 1051 |
+
# implements the buffer API. it /would/ be easier
|
| 1052 |
+
# to capture if PyObject_CheckBuffer was exposed
|
| 1053 |
+
# to Python.
|
| 1054 |
+
memoryview(message_body)
|
| 1055 |
+
except TypeError:
|
| 1056 |
+
try:
|
| 1057 |
+
chunks = iter(message_body)
|
| 1058 |
+
except TypeError:
|
| 1059 |
+
raise TypeError("message_body should be a bytes-like "
|
| 1060 |
+
"object or an iterable, got %r"
|
| 1061 |
+
% type(message_body))
|
| 1062 |
+
else:
|
| 1063 |
+
# the object implements the buffer interface and
|
| 1064 |
+
# can be passed directly into socket methods
|
| 1065 |
+
chunks = (message_body,)
|
| 1066 |
+
|
| 1067 |
+
for chunk in chunks:
|
| 1068 |
+
if not chunk:
|
| 1069 |
+
if self.debuglevel > 0:
|
| 1070 |
+
print('Zero length chunk ignored')
|
| 1071 |
+
continue
|
| 1072 |
+
|
| 1073 |
+
if encode_chunked and self._http_vsn == 11:
|
| 1074 |
+
# chunked encoding
|
| 1075 |
+
chunk = f'{len(chunk):X}\r\n'.encode('ascii') + chunk \
|
| 1076 |
+
+ b'\r\n'
|
| 1077 |
+
self.send(chunk)
|
| 1078 |
+
|
| 1079 |
+
if encode_chunked and self._http_vsn == 11:
|
| 1080 |
+
# end chunked transfer
|
| 1081 |
+
self.send(b'0\r\n\r\n')
|
| 1082 |
+
|
| 1083 |
+
def putrequest(self, method, url, skip_host=False,
|
| 1084 |
+
skip_accept_encoding=False):
|
| 1085 |
+
"""Send a request to the server.
|
| 1086 |
+
|
| 1087 |
+
`method' specifies an HTTP request method, e.g. 'GET'.
|
| 1088 |
+
`url' specifies the object being requested, e.g. '/index.html'.
|
| 1089 |
+
`skip_host' if True does not add automatically a 'Host:' header
|
| 1090 |
+
`skip_accept_encoding' if True does not add automatically an
|
| 1091 |
+
'Accept-Encoding:' header
|
| 1092 |
+
"""
|
| 1093 |
+
|
| 1094 |
+
# if a prior response has been completed, then forget about it.
|
| 1095 |
+
if self.__response and self.__response.isclosed():
|
| 1096 |
+
self.__response = None
|
| 1097 |
+
|
| 1098 |
+
|
| 1099 |
+
# in certain cases, we cannot issue another request on this connection.
|
| 1100 |
+
# this occurs when:
|
| 1101 |
+
# 1) we are in the process of sending a request. (_CS_REQ_STARTED)
|
| 1102 |
+
# 2) a response to a previous request has signalled that it is going
|
| 1103 |
+
# to close the connection upon completion.
|
| 1104 |
+
# 3) the headers for the previous response have not been read, thus
|
| 1105 |
+
# we cannot determine whether point (2) is true. (_CS_REQ_SENT)
|
| 1106 |
+
#
|
| 1107 |
+
# if there is no prior response, then we can request at will.
|
| 1108 |
+
#
|
| 1109 |
+
# if point (2) is true, then we will have passed the socket to the
|
| 1110 |
+
# response (effectively meaning, "there is no prior response"), and
|
| 1111 |
+
# will open a new one when a new request is made.
|
| 1112 |
+
#
|
| 1113 |
+
# Note: if a prior response exists, then we *can* start a new request.
|
| 1114 |
+
# We are not allowed to begin fetching the response to this new
|
| 1115 |
+
# request, however, until that prior response is complete.
|
| 1116 |
+
#
|
| 1117 |
+
if self.__state == _CS_IDLE:
|
| 1118 |
+
self.__state = _CS_REQ_STARTED
|
| 1119 |
+
else:
|
| 1120 |
+
raise CannotSendRequest(self.__state)
|
| 1121 |
+
|
| 1122 |
+
self._validate_method(method)
|
| 1123 |
+
|
| 1124 |
+
# Save the method for use later in the response phase
|
| 1125 |
+
self._method = method
|
| 1126 |
+
|
| 1127 |
+
url = url or '/'
|
| 1128 |
+
self._validate_path(url)
|
| 1129 |
+
|
| 1130 |
+
request = '%s %s %s' % (method, url, self._http_vsn_str)
|
| 1131 |
+
|
| 1132 |
+
self._output(self._encode_request(request))
|
| 1133 |
+
|
| 1134 |
+
if self._http_vsn == 11:
|
| 1135 |
+
# Issue some standard headers for better HTTP/1.1 compliance
|
| 1136 |
+
|
| 1137 |
+
if not skip_host:
|
| 1138 |
+
# this header is issued *only* for HTTP/1.1
|
| 1139 |
+
# connections. more specifically, this means it is
|
| 1140 |
+
# only issued when the client uses the new
|
| 1141 |
+
# HTTPConnection() class. backwards-compat clients
|
| 1142 |
+
# will be using HTTP/1.0 and those clients may be
|
| 1143 |
+
# issuing this header themselves. we should NOT issue
|
| 1144 |
+
# it twice; some web servers (such as Apache) barf
|
| 1145 |
+
# when they see two Host: headers
|
| 1146 |
+
|
| 1147 |
+
# If we need a non-standard port,include it in the
|
| 1148 |
+
# header. If the request is going through a proxy,
|
| 1149 |
+
# but the host of the actual URL, not the host of the
|
| 1150 |
+
# proxy.
|
| 1151 |
+
|
| 1152 |
+
netloc = ''
|
| 1153 |
+
if url.startswith('http'):
|
| 1154 |
+
nil, netloc, nil, nil, nil = urlsplit(url)
|
| 1155 |
+
|
| 1156 |
+
if netloc:
|
| 1157 |
+
try:
|
| 1158 |
+
netloc_enc = netloc.encode("ascii")
|
| 1159 |
+
except UnicodeEncodeError:
|
| 1160 |
+
netloc_enc = netloc.encode("idna")
|
| 1161 |
+
self.putheader('Host', netloc_enc)
|
| 1162 |
+
else:
|
| 1163 |
+
if self._tunnel_host:
|
| 1164 |
+
host = self._tunnel_host
|
| 1165 |
+
port = self._tunnel_port
|
| 1166 |
+
else:
|
| 1167 |
+
host = self.host
|
| 1168 |
+
port = self.port
|
| 1169 |
+
|
| 1170 |
+
try:
|
| 1171 |
+
host_enc = host.encode("ascii")
|
| 1172 |
+
except UnicodeEncodeError:
|
| 1173 |
+
host_enc = host.encode("idna")
|
| 1174 |
+
|
| 1175 |
+
# As per RFC 273, IPv6 address should be wrapped with []
|
| 1176 |
+
# when used as Host header
|
| 1177 |
+
|
| 1178 |
+
if host.find(':') >= 0:
|
| 1179 |
+
host_enc = b'[' + host_enc + b']'
|
| 1180 |
+
|
| 1181 |
+
if port == self.default_port:
|
| 1182 |
+
self.putheader('Host', host_enc)
|
| 1183 |
+
else:
|
| 1184 |
+
host_enc = host_enc.decode("ascii")
|
| 1185 |
+
self.putheader('Host', "%s:%s" % (host_enc, port))
|
| 1186 |
+
|
| 1187 |
+
# note: we are assuming that clients will not attempt to set these
|
| 1188 |
+
# headers since *this* library must deal with the
|
| 1189 |
+
# consequences. this also means that when the supporting
|
| 1190 |
+
# libraries are updated to recognize other forms, then this
|
| 1191 |
+
# code should be changed (removed or updated).
|
| 1192 |
+
|
| 1193 |
+
# we only want a Content-Encoding of "identity" since we don't
|
| 1194 |
+
# support encodings such as x-gzip or x-deflate.
|
| 1195 |
+
if not skip_accept_encoding:
|
| 1196 |
+
self.putheader('Accept-Encoding', 'identity')
|
| 1197 |
+
|
| 1198 |
+
# we can accept "chunked" Transfer-Encodings, but no others
|
| 1199 |
+
# NOTE: no TE header implies *only* "chunked"
|
| 1200 |
+
#self.putheader('TE', 'chunked')
|
| 1201 |
+
|
| 1202 |
+
# if TE is supplied in the header, then it must appear in a
|
| 1203 |
+
# Connection header.
|
| 1204 |
+
#self.putheader('Connection', 'TE')
|
| 1205 |
+
|
| 1206 |
+
else:
|
| 1207 |
+
# For HTTP/1.0, the server will assume "not chunked"
|
| 1208 |
+
pass
|
| 1209 |
+
|
| 1210 |
+
def _encode_request(self, request):
|
| 1211 |
+
# ASCII also helps prevent CVE-2019-9740.
|
| 1212 |
+
return request.encode('ascii')
|
| 1213 |
+
|
| 1214 |
+
def _validate_method(self, method):
|
| 1215 |
+
"""Validate a method name for putrequest."""
|
| 1216 |
+
# prevent http header injection
|
| 1217 |
+
match = _contains_disallowed_method_pchar_re.search(method)
|
| 1218 |
+
if match:
|
| 1219 |
+
raise ValueError(
|
| 1220 |
+
f"method can't contain control characters. {method!r} "
|
| 1221 |
+
f"(found at least {match.group()!r})")
|
| 1222 |
+
|
| 1223 |
+
def _validate_path(self, url):
|
| 1224 |
+
"""Validate a url for putrequest."""
|
| 1225 |
+
# Prevent CVE-2019-9740.
|
| 1226 |
+
match = _contains_disallowed_url_pchar_re.search(url)
|
| 1227 |
+
if match:
|
| 1228 |
+
raise InvalidURL(f"URL can't contain control characters. {url!r} "
|
| 1229 |
+
f"(found at least {match.group()!r})")
|
| 1230 |
+
|
| 1231 |
+
def _validate_host(self, host):
|
| 1232 |
+
"""Validate a host so it doesn't contain control characters."""
|
| 1233 |
+
# Prevent CVE-2019-18348.
|
| 1234 |
+
match = _contains_disallowed_url_pchar_re.search(host)
|
| 1235 |
+
if match:
|
| 1236 |
+
raise InvalidURL(f"URL can't contain control characters. {host!r} "
|
| 1237 |
+
f"(found at least {match.group()!r})")
|
| 1238 |
+
|
| 1239 |
+
def putheader(self, header, *values):
|
| 1240 |
+
"""Send a request header line to the server.
|
| 1241 |
+
|
| 1242 |
+
For example: h.putheader('Accept', 'text/html')
|
| 1243 |
+
"""
|
| 1244 |
+
if self.__state != _CS_REQ_STARTED:
|
| 1245 |
+
raise CannotSendHeader()
|
| 1246 |
+
|
| 1247 |
+
if hasattr(header, 'encode'):
|
| 1248 |
+
header = header.encode('ascii')
|
| 1249 |
+
|
| 1250 |
+
if not _is_legal_header_name(header):
|
| 1251 |
+
raise ValueError('Invalid header name %r' % (header,))
|
| 1252 |
+
|
| 1253 |
+
values = list(values)
|
| 1254 |
+
for i, one_value in enumerate(values):
|
| 1255 |
+
if hasattr(one_value, 'encode'):
|
| 1256 |
+
values[i] = one_value.encode('latin-1')
|
| 1257 |
+
elif isinstance(one_value, int):
|
| 1258 |
+
values[i] = str(one_value).encode('ascii')
|
| 1259 |
+
|
| 1260 |
+
if _is_illegal_header_value(values[i]):
|
| 1261 |
+
raise ValueError('Invalid header value %r' % (values[i],))
|
| 1262 |
+
|
| 1263 |
+
value = b'\r\n\t'.join(values)
|
| 1264 |
+
header = header + b': ' + value
|
| 1265 |
+
self._output(header)
|
| 1266 |
+
|
| 1267 |
+
def endheaders(self, message_body=None, *, encode_chunked=False):
|
| 1268 |
+
"""Indicate that the last header line has been sent to the server.
|
| 1269 |
+
|
| 1270 |
+
This method sends the request to the server. The optional message_body
|
| 1271 |
+
argument can be used to pass a message body associated with the
|
| 1272 |
+
request.
|
| 1273 |
+
"""
|
| 1274 |
+
if self.__state == _CS_REQ_STARTED:
|
| 1275 |
+
self.__state = _CS_REQ_SENT
|
| 1276 |
+
else:
|
| 1277 |
+
raise CannotSendHeader()
|
| 1278 |
+
self._send_output(message_body, encode_chunked=encode_chunked)
|
| 1279 |
+
|
| 1280 |
+
def request(self, method, url, body=None, headers={}, *,
|
| 1281 |
+
encode_chunked=False):
|
| 1282 |
+
"""Send a complete request to the server."""
|
| 1283 |
+
self._send_request(method, url, body, headers, encode_chunked)
|
| 1284 |
+
|
| 1285 |
+
def _send_request(self, method, url, body, headers, encode_chunked):
|
| 1286 |
+
# Honor explicitly requested Host: and Accept-Encoding: headers.
|
| 1287 |
+
header_names = frozenset(k.lower() for k in headers)
|
| 1288 |
+
skips = {}
|
| 1289 |
+
if 'host' in header_names:
|
| 1290 |
+
skips['skip_host'] = 1
|
| 1291 |
+
if 'accept-encoding' in header_names:
|
| 1292 |
+
skips['skip_accept_encoding'] = 1
|
| 1293 |
+
|
| 1294 |
+
self.putrequest(method, url, **skips)
|
| 1295 |
+
|
| 1296 |
+
# chunked encoding will happen if HTTP/1.1 is used and either
|
| 1297 |
+
# the caller passes encode_chunked=True or the following
|
| 1298 |
+
# conditions hold:
|
| 1299 |
+
# 1. content-length has not been explicitly set
|
| 1300 |
+
# 2. the body is a file or iterable, but not a str or bytes-like
|
| 1301 |
+
# 3. Transfer-Encoding has NOT been explicitly set by the caller
|
| 1302 |
+
|
| 1303 |
+
if 'content-length' not in header_names:
|
| 1304 |
+
# only chunk body if not explicitly set for backwards
|
| 1305 |
+
# compatibility, assuming the client code is already handling the
|
| 1306 |
+
# chunking
|
| 1307 |
+
if 'transfer-encoding' not in header_names:
|
| 1308 |
+
# if content-length cannot be automatically determined, fall
|
| 1309 |
+
# back to chunked encoding
|
| 1310 |
+
encode_chunked = False
|
| 1311 |
+
content_length = self._get_content_length(body, method)
|
| 1312 |
+
if content_length is None:
|
| 1313 |
+
if body is not None:
|
| 1314 |
+
if self.debuglevel > 0:
|
| 1315 |
+
print('Unable to determine size of %r' % body)
|
| 1316 |
+
encode_chunked = True
|
| 1317 |
+
self.putheader('Transfer-Encoding', 'chunked')
|
| 1318 |
+
else:
|
| 1319 |
+
self.putheader('Content-Length', str(content_length))
|
| 1320 |
+
else:
|
| 1321 |
+
encode_chunked = False
|
| 1322 |
+
|
| 1323 |
+
for hdr, value in headers.items():
|
| 1324 |
+
self.putheader(hdr, value)
|
| 1325 |
+
if isinstance(body, str):
|
| 1326 |
+
# RFC 2616 Section 3.7.1 says that text default has a
|
| 1327 |
+
# default charset of iso-8859-1.
|
| 1328 |
+
body = _encode(body, 'body')
|
| 1329 |
+
self.endheaders(body, encode_chunked=encode_chunked)
|
| 1330 |
+
|
| 1331 |
+
def getresponse(self):
|
| 1332 |
+
"""Get the response from the server.
|
| 1333 |
+
|
| 1334 |
+
If the HTTPConnection is in the correct state, returns an
|
| 1335 |
+
instance of HTTPResponse or of whatever object is returned by
|
| 1336 |
+
the response_class variable.
|
| 1337 |
+
|
| 1338 |
+
If a request has not been sent or if a previous response has
|
| 1339 |
+
not be handled, ResponseNotReady is raised. If the HTTP
|
| 1340 |
+
response indicates that the connection should be closed, then
|
| 1341 |
+
it will be closed before the response is returned. When the
|
| 1342 |
+
connection is closed, the underlying socket is closed.
|
| 1343 |
+
"""
|
| 1344 |
+
|
| 1345 |
+
# if a prior response has been completed, then forget about it.
|
| 1346 |
+
if self.__response and self.__response.isclosed():
|
| 1347 |
+
self.__response = None
|
| 1348 |
+
|
| 1349 |
+
# if a prior response exists, then it must be completed (otherwise, we
|
| 1350 |
+
# cannot read this response's header to determine the connection-close
|
| 1351 |
+
# behavior)
|
| 1352 |
+
#
|
| 1353 |
+
# note: if a prior response existed, but was connection-close, then the
|
| 1354 |
+
# socket and response were made independent of this HTTPConnection
|
| 1355 |
+
# object since a new request requires that we open a whole new
|
| 1356 |
+
# connection
|
| 1357 |
+
#
|
| 1358 |
+
# this means the prior response had one of two states:
|
| 1359 |
+
# 1) will_close: this connection was reset and the prior socket and
|
| 1360 |
+
# response operate independently
|
| 1361 |
+
# 2) persistent: the response was retained and we await its
|
| 1362 |
+
# isclosed() status to become true.
|
| 1363 |
+
#
|
| 1364 |
+
if self.__state != _CS_REQ_SENT or self.__response:
|
| 1365 |
+
raise ResponseNotReady(self.__state)
|
| 1366 |
+
|
| 1367 |
+
if self.debuglevel > 0:
|
| 1368 |
+
response = self.response_class(self.sock, self.debuglevel,
|
| 1369 |
+
method=self._method)
|
| 1370 |
+
else:
|
| 1371 |
+
response = self.response_class(self.sock, method=self._method)
|
| 1372 |
+
|
| 1373 |
+
try:
|
| 1374 |
+
try:
|
| 1375 |
+
response.begin()
|
| 1376 |
+
except ConnectionError:
|
| 1377 |
+
self.close()
|
| 1378 |
+
raise
|
| 1379 |
+
assert response.will_close != _UNKNOWN
|
| 1380 |
+
self.__state = _CS_IDLE
|
| 1381 |
+
|
| 1382 |
+
if response.will_close:
|
| 1383 |
+
# this effectively passes the connection to the response
|
| 1384 |
+
self.close()
|
| 1385 |
+
else:
|
| 1386 |
+
# remember this, so we can tell when it is complete
|
| 1387 |
+
self.__response = response
|
| 1388 |
+
|
| 1389 |
+
return response
|
| 1390 |
+
except:
|
| 1391 |
+
response.close()
|
| 1392 |
+
raise
|
| 1393 |
+
|
| 1394 |
+
try:
|
| 1395 |
+
import ssl
|
| 1396 |
+
except ImportError:
|
| 1397 |
+
pass
|
| 1398 |
+
else:
|
| 1399 |
+
class HTTPSConnection(HTTPConnection):
|
| 1400 |
+
"This class allows communication via SSL."
|
| 1401 |
+
|
| 1402 |
+
default_port = HTTPS_PORT
|
| 1403 |
+
|
| 1404 |
+
# XXX Should key_file and cert_file be deprecated in favour of context?
|
| 1405 |
+
|
| 1406 |
+
def __init__(self, host, port=None, key_file=None, cert_file=None,
|
| 1407 |
+
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
|
| 1408 |
+
source_address=None, *, context=None,
|
| 1409 |
+
check_hostname=None, blocksize=8192):
|
| 1410 |
+
super(HTTPSConnection, self).__init__(host, port, timeout,
|
| 1411 |
+
source_address,
|
| 1412 |
+
blocksize=blocksize)
|
| 1413 |
+
if (key_file is not None or cert_file is not None or
|
| 1414 |
+
check_hostname is not None):
|
| 1415 |
+
import warnings
|
| 1416 |
+
warnings.warn("key_file, cert_file and check_hostname are "
|
| 1417 |
+
"deprecated, use a custom context instead.",
|
| 1418 |
+
DeprecationWarning, 2)
|
| 1419 |
+
self.key_file = key_file
|
| 1420 |
+
self.cert_file = cert_file
|
| 1421 |
+
if context is None:
|
| 1422 |
+
context = ssl._create_default_https_context()
|
| 1423 |
+
# send ALPN extension to indicate HTTP/1.1 protocol
|
| 1424 |
+
if self._http_vsn == 11:
|
| 1425 |
+
context.set_alpn_protocols(['http/1.1'])
|
| 1426 |
+
# enable PHA for TLS 1.3 connections if available
|
| 1427 |
+
if context.post_handshake_auth is not None:
|
| 1428 |
+
context.post_handshake_auth = True
|
| 1429 |
+
will_verify = context.verify_mode != ssl.CERT_NONE
|
| 1430 |
+
if check_hostname is None:
|
| 1431 |
+
check_hostname = context.check_hostname
|
| 1432 |
+
if check_hostname and not will_verify:
|
| 1433 |
+
raise ValueError("check_hostname needs a SSL context with "
|
| 1434 |
+
"either CERT_OPTIONAL or CERT_REQUIRED")
|
| 1435 |
+
if key_file or cert_file:
|
| 1436 |
+
context.load_cert_chain(cert_file, key_file)
|
| 1437 |
+
# cert and key file means the user wants to authenticate.
|
| 1438 |
+
# enable TLS 1.3 PHA implicitly even for custom contexts.
|
| 1439 |
+
if context.post_handshake_auth is not None:
|
| 1440 |
+
context.post_handshake_auth = True
|
| 1441 |
+
self._context = context
|
| 1442 |
+
if check_hostname is not None:
|
| 1443 |
+
self._context.check_hostname = check_hostname
|
| 1444 |
+
|
| 1445 |
+
def connect(self):
|
| 1446 |
+
"Connect to a host on a given (SSL) port."
|
| 1447 |
+
|
| 1448 |
+
super().connect()
|
| 1449 |
+
|
| 1450 |
+
if self._tunnel_host:
|
| 1451 |
+
server_hostname = self._tunnel_host
|
| 1452 |
+
else:
|
| 1453 |
+
server_hostname = self.host
|
| 1454 |
+
|
| 1455 |
+
self.sock = self._context.wrap_socket(self.sock,
|
| 1456 |
+
server_hostname=server_hostname)
|
| 1457 |
+
|
| 1458 |
+
__all__.append("HTTPSConnection")
|
| 1459 |
+
|
| 1460 |
+
class HTTPException(Exception):
|
| 1461 |
+
# Subclasses that define an __init__ must call Exception.__init__
|
| 1462 |
+
# or define self.args. Otherwise, str() will fail.
|
| 1463 |
+
pass
|
| 1464 |
+
|
| 1465 |
+
class NotConnected(HTTPException):
|
| 1466 |
+
pass
|
| 1467 |
+
|
| 1468 |
+
class InvalidURL(HTTPException):
|
| 1469 |
+
pass
|
| 1470 |
+
|
| 1471 |
+
class UnknownProtocol(HTTPException):
|
| 1472 |
+
def __init__(self, version):
|
| 1473 |
+
self.args = version,
|
| 1474 |
+
self.version = version
|
| 1475 |
+
|
| 1476 |
+
class UnknownTransferEncoding(HTTPException):
|
| 1477 |
+
pass
|
| 1478 |
+
|
| 1479 |
+
class UnimplementedFileMode(HTTPException):
|
| 1480 |
+
pass
|
| 1481 |
+
|
| 1482 |
+
class IncompleteRead(HTTPException):
|
| 1483 |
+
def __init__(self, partial, expected=None):
|
| 1484 |
+
self.args = partial,
|
| 1485 |
+
self.partial = partial
|
| 1486 |
+
self.expected = expected
|
| 1487 |
+
def __repr__(self):
|
| 1488 |
+
if self.expected is not None:
|
| 1489 |
+
e = ', %i more expected' % self.expected
|
| 1490 |
+
else:
|
| 1491 |
+
e = ''
|
| 1492 |
+
return '%s(%i bytes read%s)' % (self.__class__.__name__,
|
| 1493 |
+
len(self.partial), e)
|
| 1494 |
+
__str__ = object.__str__
|
| 1495 |
+
|
| 1496 |
+
class ImproperConnectionState(HTTPException):
|
| 1497 |
+
pass
|
| 1498 |
+
|
| 1499 |
+
class CannotSendRequest(ImproperConnectionState):
|
| 1500 |
+
pass
|
| 1501 |
+
|
| 1502 |
+
class CannotSendHeader(ImproperConnectionState):
|
| 1503 |
+
pass
|
| 1504 |
+
|
| 1505 |
+
class ResponseNotReady(ImproperConnectionState):
|
| 1506 |
+
pass
|
| 1507 |
+
|
| 1508 |
+
class BadStatusLine(HTTPException):
|
| 1509 |
+
def __init__(self, line):
|
| 1510 |
+
if not line:
|
| 1511 |
+
line = repr(line)
|
| 1512 |
+
self.args = line,
|
| 1513 |
+
self.line = line
|
| 1514 |
+
|
| 1515 |
+
class LineTooLong(HTTPException):
|
| 1516 |
+
def __init__(self, line_type):
|
| 1517 |
+
HTTPException.__init__(self, "got more than %d bytes when reading %s"
|
| 1518 |
+
% (_MAXLINE, line_type))
|
| 1519 |
+
|
| 1520 |
+
class RemoteDisconnected(ConnectionResetError, BadStatusLine):
|
| 1521 |
+
def __init__(self, *pos, **kw):
|
| 1522 |
+
BadStatusLine.__init__(self, "")
|
| 1523 |
+
ConnectionResetError.__init__(self, *pos, **kw)
|
| 1524 |
+
|
| 1525 |
+
#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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""HTTP cookie handling for web clients.
|
| 2 |
+
|
| 3 |
+
This module has (now fairly distant) origins in Gisle Aas' Perl module
|
| 4 |
+
HTTP::Cookies, from the libwww-perl library.
|
| 5 |
+
|
| 6 |
+
Docstrings, comments and debug strings in this code refer to the
|
| 7 |
+
attributes of the HTTP cookie system as cookie-attributes, to distinguish
|
| 8 |
+
them clearly from Python attributes.
|
| 9 |
+
|
| 10 |
+
Class diagram (note that BSDDBCookieJar and the MSIE* classes are not
|
| 11 |
+
distributed with the Python standard library, but are available from
|
| 12 |
+
http://wwwsearch.sf.net/):
|
| 13 |
+
|
| 14 |
+
CookieJar____
|
| 15 |
+
/ \ \
|
| 16 |
+
FileCookieJar \ \
|
| 17 |
+
/ | \ \ \
|
| 18 |
+
MozillaCookieJar | LWPCookieJar \ \
|
| 19 |
+
| | \
|
| 20 |
+
| ---MSIEBase | \
|
| 21 |
+
| / | | \
|
| 22 |
+
| / MSIEDBCookieJar BSDDBCookieJar
|
| 23 |
+
|/
|
| 24 |
+
MSIECookieJar
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
__all__ = ['Cookie', 'CookieJar', 'CookiePolicy', 'DefaultCookiePolicy',
|
| 29 |
+
'FileCookieJar', 'LWPCookieJar', 'LoadError', 'MozillaCookieJar']
|
| 30 |
+
|
| 31 |
+
import os
|
| 32 |
+
import copy
|
| 33 |
+
import datetime
|
| 34 |
+
import re
|
| 35 |
+
import time
|
| 36 |
+
import urllib.parse, urllib.request
|
| 37 |
+
import threading as _threading
|
| 38 |
+
import http.client # only for the default HTTP port
|
| 39 |
+
from calendar import timegm
|
| 40 |
+
|
| 41 |
+
debug = False # set to True to enable debugging via the logging module
|
| 42 |
+
logger = None
|
| 43 |
+
|
| 44 |
+
def _debug(*args):
|
| 45 |
+
if not debug:
|
| 46 |
+
return
|
| 47 |
+
global logger
|
| 48 |
+
if not logger:
|
| 49 |
+
import logging
|
| 50 |
+
logger = logging.getLogger("http.cookiejar")
|
| 51 |
+
return logger.debug(*args)
|
| 52 |
+
|
| 53 |
+
HTTPONLY_ATTR = "HTTPOnly"
|
| 54 |
+
HTTPONLY_PREFIX = "#HttpOnly_"
|
| 55 |
+
DEFAULT_HTTP_PORT = str(http.client.HTTP_PORT)
|
| 56 |
+
NETSCAPE_MAGIC_RGX = re.compile("#( Netscape)? HTTP Cookie File")
|
| 57 |
+
MISSING_FILENAME_TEXT = ("a filename was not supplied (nor was the CookieJar "
|
| 58 |
+
"instance initialised with one)")
|
| 59 |
+
NETSCAPE_HEADER_TEXT = """\
|
| 60 |
+
# Netscape HTTP Cookie File
|
| 61 |
+
# http://curl.haxx.se/rfc/cookie_spec.html
|
| 62 |
+
# This is a generated file! Do not edit.
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
def _warn_unhandled_exception():
|
| 67 |
+
# There are a few catch-all except: statements in this module, for
|
| 68 |
+
# catching input that's bad in unexpected ways. Warn if any
|
| 69 |
+
# exceptions are caught there.
|
| 70 |
+
import io, warnings, traceback
|
| 71 |
+
f = io.StringIO()
|
| 72 |
+
traceback.print_exc(None, f)
|
| 73 |
+
msg = f.getvalue()
|
| 74 |
+
warnings.warn("http.cookiejar bug!\n%s" % msg, stacklevel=2)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# Date/time conversion
|
| 78 |
+
# -----------------------------------------------------------------------------
|
| 79 |
+
|
| 80 |
+
EPOCH_YEAR = 1970
|
| 81 |
+
def _timegm(tt):
|
| 82 |
+
year, month, mday, hour, min, sec = tt[:6]
|
| 83 |
+
if ((year >= EPOCH_YEAR) and (1 <= month <= 12) and (1 <= mday <= 31) and
|
| 84 |
+
(0 <= hour <= 24) and (0 <= min <= 59) and (0 <= sec <= 61)):
|
| 85 |
+
return timegm(tt)
|
| 86 |
+
else:
|
| 87 |
+
return None
|
| 88 |
+
|
| 89 |
+
DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
| 90 |
+
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
| 91 |
+
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
|
| 92 |
+
MONTHS_LOWER = []
|
| 93 |
+
for month in MONTHS: MONTHS_LOWER.append(month.lower())
|
| 94 |
+
|
| 95 |
+
def time2isoz(t=None):
|
| 96 |
+
"""Return a string representing time in seconds since epoch, t.
|
| 97 |
+
|
| 98 |
+
If the function is called without an argument, it will use the current
|
| 99 |
+
time.
|
| 100 |
+
|
| 101 |
+
The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ",
|
| 102 |
+
representing Universal Time (UTC, aka GMT). An example of this format is:
|
| 103 |
+
|
| 104 |
+
1994-11-24 08:49:37Z
|
| 105 |
+
|
| 106 |
+
"""
|
| 107 |
+
if t is None:
|
| 108 |
+
dt = datetime.datetime.utcnow()
|
| 109 |
+
else:
|
| 110 |
+
dt = datetime.datetime.utcfromtimestamp(t)
|
| 111 |
+
return "%04d-%02d-%02d %02d:%02d:%02dZ" % (
|
| 112 |
+
dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
|
| 113 |
+
|
| 114 |
+
def time2netscape(t=None):
|
| 115 |
+
"""Return a string representing time in seconds since epoch, t.
|
| 116 |
+
|
| 117 |
+
If the function is called without an argument, it will use the current
|
| 118 |
+
time.
|
| 119 |
+
|
| 120 |
+
The format of the returned string is like this:
|
| 121 |
+
|
| 122 |
+
Wed, DD-Mon-YYYY HH:MM:SS GMT
|
| 123 |
+
|
| 124 |
+
"""
|
| 125 |
+
if t is None:
|
| 126 |
+
dt = datetime.datetime.utcnow()
|
| 127 |
+
else:
|
| 128 |
+
dt = datetime.datetime.utcfromtimestamp(t)
|
| 129 |
+
return "%s, %02d-%s-%04d %02d:%02d:%02d GMT" % (
|
| 130 |
+
DAYS[dt.weekday()], dt.day, MONTHS[dt.month-1],
|
| 131 |
+
dt.year, dt.hour, dt.minute, dt.second)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
UTC_ZONES = {"GMT": None, "UTC": None, "UT": None, "Z": None}
|
| 135 |
+
|
| 136 |
+
TIMEZONE_RE = re.compile(r"^([-+])?(\d\d?):?(\d\d)?$", re.ASCII)
|
| 137 |
+
def offset_from_tz_string(tz):
|
| 138 |
+
offset = None
|
| 139 |
+
if tz in UTC_ZONES:
|
| 140 |
+
offset = 0
|
| 141 |
+
else:
|
| 142 |
+
m = TIMEZONE_RE.search(tz)
|
| 143 |
+
if m:
|
| 144 |
+
offset = 3600 * int(m.group(2))
|
| 145 |
+
if m.group(3):
|
| 146 |
+
offset = offset + 60 * int(m.group(3))
|
| 147 |
+
if m.group(1) == '-':
|
| 148 |
+
offset = -offset
|
| 149 |
+
return offset
|
| 150 |
+
|
| 151 |
+
def _str2time(day, mon, yr, hr, min, sec, tz):
|
| 152 |
+
yr = int(yr)
|
| 153 |
+
if yr > datetime.MAXYEAR:
|
| 154 |
+
return None
|
| 155 |
+
|
| 156 |
+
# translate month name to number
|
| 157 |
+
# month numbers start with 1 (January)
|
| 158 |
+
try:
|
| 159 |
+
mon = MONTHS_LOWER.index(mon.lower())+1
|
| 160 |
+
except ValueError:
|
| 161 |
+
# maybe it's already a number
|
| 162 |
+
try:
|
| 163 |
+
imon = int(mon)
|
| 164 |
+
except ValueError:
|
| 165 |
+
return None
|
| 166 |
+
if 1 <= imon <= 12:
|
| 167 |
+
mon = imon
|
| 168 |
+
else:
|
| 169 |
+
return None
|
| 170 |
+
|
| 171 |
+
# make sure clock elements are defined
|
| 172 |
+
if hr is None: hr = 0
|
| 173 |
+
if min is None: min = 0
|
| 174 |
+
if sec is None: sec = 0
|
| 175 |
+
|
| 176 |
+
day = int(day)
|
| 177 |
+
hr = int(hr)
|
| 178 |
+
min = int(min)
|
| 179 |
+
sec = int(sec)
|
| 180 |
+
|
| 181 |
+
if yr < 1000:
|
| 182 |
+
# find "obvious" year
|
| 183 |
+
cur_yr = time.localtime(time.time())[0]
|
| 184 |
+
m = cur_yr % 100
|
| 185 |
+
tmp = yr
|
| 186 |
+
yr = yr + cur_yr - m
|
| 187 |
+
m = m - tmp
|
| 188 |
+
if abs(m) > 50:
|
| 189 |
+
if m > 0: yr = yr + 100
|
| 190 |
+
else: yr = yr - 100
|
| 191 |
+
|
| 192 |
+
# convert UTC time tuple to seconds since epoch (not timezone-adjusted)
|
| 193 |
+
t = _timegm((yr, mon, day, hr, min, sec, tz))
|
| 194 |
+
|
| 195 |
+
if t is not None:
|
| 196 |
+
# adjust time using timezone string, to get absolute time since epoch
|
| 197 |
+
if tz is None:
|
| 198 |
+
tz = "UTC"
|
| 199 |
+
tz = tz.upper()
|
| 200 |
+
offset = offset_from_tz_string(tz)
|
| 201 |
+
if offset is None:
|
| 202 |
+
return None
|
| 203 |
+
t = t - offset
|
| 204 |
+
|
| 205 |
+
return t
|
| 206 |
+
|
| 207 |
+
STRICT_DATE_RE = re.compile(
|
| 208 |
+
r"^[SMTWF][a-z][a-z], (\d\d) ([JFMASOND][a-z][a-z]) "
|
| 209 |
+
r"(\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$", re.ASCII)
|
| 210 |
+
WEEKDAY_RE = re.compile(
|
| 211 |
+
r"^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\s*", re.I | re.ASCII)
|
| 212 |
+
LOOSE_HTTP_DATE_RE = re.compile(
|
| 213 |
+
r"""^
|
| 214 |
+
(\d\d?) # day
|
| 215 |
+
(?:\s+|[-\/])
|
| 216 |
+
(\w+) # month
|
| 217 |
+
(?:\s+|[-\/])
|
| 218 |
+
(\d+) # year
|
| 219 |
+
(?:
|
| 220 |
+
(?:\s+|:) # separator before clock
|
| 221 |
+
(\d\d?):(\d\d) # hour:min
|
| 222 |
+
(?::(\d\d))? # optional seconds
|
| 223 |
+
)? # optional clock
|
| 224 |
+
\s*
|
| 225 |
+
(?:
|
| 226 |
+
([-+]?\d{2,4}|(?![APap][Mm]\b)[A-Za-z]+) # timezone
|
| 227 |
+
\s*
|
| 228 |
+
)?
|
| 229 |
+
(?:
|
| 230 |
+
\(\w+\) # ASCII representation of timezone in parens.
|
| 231 |
+
\s*
|
| 232 |
+
)?$""", re.X | re.ASCII)
|
| 233 |
+
def http2time(text):
|
| 234 |
+
"""Returns time in seconds since epoch of time represented by a string.
|
| 235 |
+
|
| 236 |
+
Return value is an integer.
|
| 237 |
+
|
| 238 |
+
None is returned if the format of str is unrecognized, the time is outside
|
| 239 |
+
the representable range, or the timezone string is not recognized. If the
|
| 240 |
+
string contains no timezone, UTC is assumed.
|
| 241 |
+
|
| 242 |
+
The timezone in the string may be numerical (like "-0800" or "+0100") or a
|
| 243 |
+
string timezone (like "UTC", "GMT", "BST" or "EST"). Currently, only the
|
| 244 |
+
timezone strings equivalent to UTC (zero offset) are known to the function.
|
| 245 |
+
|
| 246 |
+
The function loosely parses the following formats:
|
| 247 |
+
|
| 248 |
+
Wed, 09 Feb 1994 22:23:32 GMT -- HTTP format
|
| 249 |
+
Tuesday, 08-Feb-94 14:15:29 GMT -- old rfc850 HTTP format
|
| 250 |
+
Tuesday, 08-Feb-1994 14:15:29 GMT -- broken rfc850 HTTP format
|
| 251 |
+
09 Feb 1994 22:23:32 GMT -- HTTP format (no weekday)
|
| 252 |
+
08-Feb-94 14:15:29 GMT -- rfc850 format (no weekday)
|
| 253 |
+
08-Feb-1994 14:15:29 GMT -- broken rfc850 format (no weekday)
|
| 254 |
+
|
| 255 |
+
The parser ignores leading and trailing whitespace. The time may be
|
| 256 |
+
absent.
|
| 257 |
+
|
| 258 |
+
If the year is given with only 2 digits, the function will select the
|
| 259 |
+
century that makes the year closest to the current date.
|
| 260 |
+
|
| 261 |
+
"""
|
| 262 |
+
# fast exit for strictly conforming string
|
| 263 |
+
m = STRICT_DATE_RE.search(text)
|
| 264 |
+
if m:
|
| 265 |
+
g = m.groups()
|
| 266 |
+
mon = MONTHS_LOWER.index(g[1].lower()) + 1
|
| 267 |
+
tt = (int(g[2]), mon, int(g[0]),
|
| 268 |
+
int(g[3]), int(g[4]), float(g[5]))
|
| 269 |
+
return _timegm(tt)
|
| 270 |
+
|
| 271 |
+
# No, we need some messy parsing...
|
| 272 |
+
|
| 273 |
+
# clean up
|
| 274 |
+
text = text.lstrip()
|
| 275 |
+
text = WEEKDAY_RE.sub("", text, 1) # Useless weekday
|
| 276 |
+
|
| 277 |
+
# tz is time zone specifier string
|
| 278 |
+
day, mon, yr, hr, min, sec, tz = [None]*7
|
| 279 |
+
|
| 280 |
+
# loose regexp parse
|
| 281 |
+
m = LOOSE_HTTP_DATE_RE.search(text)
|
| 282 |
+
if m is not None:
|
| 283 |
+
day, mon, yr, hr, min, sec, tz = m.groups()
|
| 284 |
+
else:
|
| 285 |
+
return None # bad format
|
| 286 |
+
|
| 287 |
+
return _str2time(day, mon, yr, hr, min, sec, tz)
|
| 288 |
+
|
| 289 |
+
ISO_DATE_RE = re.compile(
|
| 290 |
+
r"""^
|
| 291 |
+
(\d{4}) # year
|
| 292 |
+
[-\/]?
|
| 293 |
+
(\d\d?) # numerical month
|
| 294 |
+
[-\/]?
|
| 295 |
+
(\d\d?) # day
|
| 296 |
+
(?:
|
| 297 |
+
(?:\s+|[-:Tt]) # separator before clock
|
| 298 |
+
(\d\d?):?(\d\d) # hour:min
|
| 299 |
+
(?::?(\d\d(?:\.\d*)?))? # optional seconds (and fractional)
|
| 300 |
+
)? # optional clock
|
| 301 |
+
\s*
|
| 302 |
+
(?:
|
| 303 |
+
([-+]?\d\d?:?(:?\d\d)?
|
| 304 |
+
|Z|z) # timezone (Z is "zero meridian", i.e. GMT)
|
| 305 |
+
\s*
|
| 306 |
+
)?$""", re.X | re. ASCII)
|
| 307 |
+
def iso2time(text):
|
| 308 |
+
"""
|
| 309 |
+
As for http2time, but parses the ISO 8601 formats:
|
| 310 |
+
|
| 311 |
+
1994-02-03 14:15:29 -0100 -- ISO 8601 format
|
| 312 |
+
1994-02-03 14:15:29 -- zone is optional
|
| 313 |
+
1994-02-03 -- only date
|
| 314 |
+
1994-02-03T14:15:29 -- Use T as separator
|
| 315 |
+
19940203T141529Z -- ISO 8601 compact format
|
| 316 |
+
19940203 -- only date
|
| 317 |
+
|
| 318 |
+
"""
|
| 319 |
+
# clean up
|
| 320 |
+
text = text.lstrip()
|
| 321 |
+
|
| 322 |
+
# tz is time zone specifier string
|
| 323 |
+
day, mon, yr, hr, min, sec, tz = [None]*7
|
| 324 |
+
|
| 325 |
+
# loose regexp parse
|
| 326 |
+
m = ISO_DATE_RE.search(text)
|
| 327 |
+
if m is not None:
|
| 328 |
+
# XXX there's an extra bit of the timezone I'm ignoring here: is
|
| 329 |
+
# this the right thing to do?
|
| 330 |
+
yr, mon, day, hr, min, sec, tz, _ = m.groups()
|
| 331 |
+
else:
|
| 332 |
+
return None # bad format
|
| 333 |
+
|
| 334 |
+
return _str2time(day, mon, yr, hr, min, sec, tz)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
# Header parsing
|
| 338 |
+
# -----------------------------------------------------------------------------
|
| 339 |
+
|
| 340 |
+
def unmatched(match):
|
| 341 |
+
"""Return unmatched part of re.Match object."""
|
| 342 |
+
start, end = match.span(0)
|
| 343 |
+
return match.string[:start]+match.string[end:]
|
| 344 |
+
|
| 345 |
+
HEADER_TOKEN_RE = re.compile(r"^\s*([^=\s;,]+)")
|
| 346 |
+
HEADER_QUOTED_VALUE_RE = re.compile(r"^\s*=\s*\"([^\"\\]*(?:\\.[^\"\\]*)*)\"")
|
| 347 |
+
HEADER_VALUE_RE = re.compile(r"^\s*=\s*([^\s;,]*)")
|
| 348 |
+
HEADER_ESCAPE_RE = re.compile(r"\\(.)")
|
| 349 |
+
def split_header_words(header_values):
|
| 350 |
+
r"""Parse header values into a list of lists containing key,value pairs.
|
| 351 |
+
|
| 352 |
+
The function knows how to deal with ",", ";" and "=" as well as quoted
|
| 353 |
+
values after "=". A list of space separated tokens are parsed as if they
|
| 354 |
+
were separated by ";".
|
| 355 |
+
|
| 356 |
+
If the header_values passed as argument contains multiple values, then they
|
| 357 |
+
are treated as if they were a single value separated by comma ",".
|
| 358 |
+
|
| 359 |
+
This means that this function is useful for parsing header fields that
|
| 360 |
+
follow this syntax (BNF as from the HTTP/1.1 specification, but we relax
|
| 361 |
+
the requirement for tokens).
|
| 362 |
+
|
| 363 |
+
headers = #header
|
| 364 |
+
header = (token | parameter) *( [";"] (token | parameter))
|
| 365 |
+
|
| 366 |
+
token = 1*<any CHAR except CTLs or separators>
|
| 367 |
+
separators = "(" | ")" | "<" | ">" | "@"
|
| 368 |
+
| "," | ";" | ":" | "\" | <">
|
| 369 |
+
| "/" | "[" | "]" | "?" | "="
|
| 370 |
+
| "{" | "}" | SP | HT
|
| 371 |
+
|
| 372 |
+
quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
|
| 373 |
+
qdtext = <any TEXT except <">>
|
| 374 |
+
quoted-pair = "\" CHAR
|
| 375 |
+
|
| 376 |
+
parameter = attribute "=" value
|
| 377 |
+
attribute = token
|
| 378 |
+
value = token | quoted-string
|
| 379 |
+
|
| 380 |
+
Each header is represented by a list of key/value pairs. The value for a
|
| 381 |
+
simple token (not part of a parameter) is None. Syntactically incorrect
|
| 382 |
+
headers will not necessarily be parsed as you would want.
|
| 383 |
+
|
| 384 |
+
This is easier to describe with some examples:
|
| 385 |
+
|
| 386 |
+
>>> split_header_words(['foo="bar"; port="80,81"; discard, bar=baz'])
|
| 387 |
+
[[('foo', 'bar'), ('port', '80,81'), ('discard', None)], [('bar', 'baz')]]
|
| 388 |
+
>>> split_header_words(['text/html; charset="iso-8859-1"'])
|
| 389 |
+
[[('text/html', None), ('charset', 'iso-8859-1')]]
|
| 390 |
+
>>> split_header_words([r'Basic realm="\"foo\bar\""'])
|
| 391 |
+
[[('Basic', None), ('realm', '"foobar"')]]
|
| 392 |
+
|
| 393 |
+
"""
|
| 394 |
+
assert not isinstance(header_values, str)
|
| 395 |
+
result = []
|
| 396 |
+
for text in header_values:
|
| 397 |
+
orig_text = text
|
| 398 |
+
pairs = []
|
| 399 |
+
while text:
|
| 400 |
+
m = HEADER_TOKEN_RE.search(text)
|
| 401 |
+
if m:
|
| 402 |
+
text = unmatched(m)
|
| 403 |
+
name = m.group(1)
|
| 404 |
+
m = HEADER_QUOTED_VALUE_RE.search(text)
|
| 405 |
+
if m: # quoted value
|
| 406 |
+
text = unmatched(m)
|
| 407 |
+
value = m.group(1)
|
| 408 |
+
value = HEADER_ESCAPE_RE.sub(r"\1", value)
|
| 409 |
+
else:
|
| 410 |
+
m = HEADER_VALUE_RE.search(text)
|
| 411 |
+
if m: # unquoted value
|
| 412 |
+
text = unmatched(m)
|
| 413 |
+
value = m.group(1)
|
| 414 |
+
value = value.rstrip()
|
| 415 |
+
else:
|
| 416 |
+
# no value, a lone token
|
| 417 |
+
value = None
|
| 418 |
+
pairs.append((name, value))
|
| 419 |
+
elif text.lstrip().startswith(","):
|
| 420 |
+
# concatenated headers, as per RFC 2616 section 4.2
|
| 421 |
+
text = text.lstrip()[1:]
|
| 422 |
+
if pairs: result.append(pairs)
|
| 423 |
+
pairs = []
|
| 424 |
+
else:
|
| 425 |
+
# skip junk
|
| 426 |
+
non_junk, nr_junk_chars = re.subn(r"^[=\s;]*", "", text)
|
| 427 |
+
assert nr_junk_chars > 0, (
|
| 428 |
+
"split_header_words bug: '%s', '%s', %s" %
|
| 429 |
+
(orig_text, text, pairs))
|
| 430 |
+
text = non_junk
|
| 431 |
+
if pairs: result.append(pairs)
|
| 432 |
+
return result
|
| 433 |
+
|
| 434 |
+
HEADER_JOIN_ESCAPE_RE = re.compile(r"([\"\\])")
|
| 435 |
+
def join_header_words(lists):
|
| 436 |
+
"""Do the inverse (almost) of the conversion done by split_header_words.
|
| 437 |
+
|
| 438 |
+
Takes a list of lists of (key, value) pairs and produces a single header
|
| 439 |
+
value. Attribute values are quoted if needed.
|
| 440 |
+
|
| 441 |
+
>>> join_header_words([[("text/plain", None), ("charset", "iso-8859-1")]])
|
| 442 |
+
'text/plain; charset="iso-8859-1"'
|
| 443 |
+
>>> join_header_words([[("text/plain", None)], [("charset", "iso-8859-1")]])
|
| 444 |
+
'text/plain, charset="iso-8859-1"'
|
| 445 |
+
|
| 446 |
+
"""
|
| 447 |
+
headers = []
|
| 448 |
+
for pairs in lists:
|
| 449 |
+
attr = []
|
| 450 |
+
for k, v in pairs:
|
| 451 |
+
if v is not None:
|
| 452 |
+
if not re.search(r"^\w+$", v):
|
| 453 |
+
v = HEADER_JOIN_ESCAPE_RE.sub(r"\\\1", v) # escape " and \
|
| 454 |
+
v = '"%s"' % v
|
| 455 |
+
k = "%s=%s" % (k, v)
|
| 456 |
+
attr.append(k)
|
| 457 |
+
if attr: headers.append("; ".join(attr))
|
| 458 |
+
return ", ".join(headers)
|
| 459 |
+
|
| 460 |
+
def strip_quotes(text):
|
| 461 |
+
if text.startswith('"'):
|
| 462 |
+
text = text[1:]
|
| 463 |
+
if text.endswith('"'):
|
| 464 |
+
text = text[:-1]
|
| 465 |
+
return text
|
| 466 |
+
|
| 467 |
+
def parse_ns_headers(ns_headers):
|
| 468 |
+
"""Ad-hoc parser for Netscape protocol cookie-attributes.
|
| 469 |
+
|
| 470 |
+
The old Netscape cookie format for Set-Cookie can for instance contain
|
| 471 |
+
an unquoted "," in the expires field, so we have to use this ad-hoc
|
| 472 |
+
parser instead of split_header_words.
|
| 473 |
+
|
| 474 |
+
XXX This may not make the best possible effort to parse all the crap
|
| 475 |
+
that Netscape Cookie headers contain. Ronald Tschalar's HTTPClient
|
| 476 |
+
parser is probably better, so could do worse than following that if
|
| 477 |
+
this ever gives any trouble.
|
| 478 |
+
|
| 479 |
+
Currently, this is also used for parsing RFC 2109 cookies.
|
| 480 |
+
|
| 481 |
+
"""
|
| 482 |
+
known_attrs = ("expires", "domain", "path", "secure",
|
| 483 |
+
# RFC 2109 attrs (may turn up in Netscape cookies, too)
|
| 484 |
+
"version", "port", "max-age")
|
| 485 |
+
|
| 486 |
+
result = []
|
| 487 |
+
for ns_header in ns_headers:
|
| 488 |
+
pairs = []
|
| 489 |
+
version_set = False
|
| 490 |
+
|
| 491 |
+
# XXX: The following does not strictly adhere to RFCs in that empty
|
| 492 |
+
# names and values are legal (the former will only appear once and will
|
| 493 |
+
# be overwritten if multiple occurrences are present). This is
|
| 494 |
+
# mostly to deal with backwards compatibility.
|
| 495 |
+
for ii, param in enumerate(ns_header.split(';')):
|
| 496 |
+
param = param.strip()
|
| 497 |
+
|
| 498 |
+
key, sep, val = param.partition('=')
|
| 499 |
+
key = key.strip()
|
| 500 |
+
|
| 501 |
+
if not key:
|
| 502 |
+
if ii == 0:
|
| 503 |
+
break
|
| 504 |
+
else:
|
| 505 |
+
continue
|
| 506 |
+
|
| 507 |
+
# allow for a distinction between present and empty and missing
|
| 508 |
+
# altogether
|
| 509 |
+
val = val.strip() if sep else None
|
| 510 |
+
|
| 511 |
+
if ii != 0:
|
| 512 |
+
lc = key.lower()
|
| 513 |
+
if lc in known_attrs:
|
| 514 |
+
key = lc
|
| 515 |
+
|
| 516 |
+
if key == "version":
|
| 517 |
+
# This is an RFC 2109 cookie.
|
| 518 |
+
if val is not None:
|
| 519 |
+
val = strip_quotes(val)
|
| 520 |
+
version_set = True
|
| 521 |
+
elif key == "expires":
|
| 522 |
+
# convert expires date to seconds since epoch
|
| 523 |
+
if val is not None:
|
| 524 |
+
val = http2time(strip_quotes(val)) # None if invalid
|
| 525 |
+
pairs.append((key, val))
|
| 526 |
+
|
| 527 |
+
if pairs:
|
| 528 |
+
if not version_set:
|
| 529 |
+
pairs.append(("version", "0"))
|
| 530 |
+
result.append(pairs)
|
| 531 |
+
|
| 532 |
+
return result
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
IPV4_RE = re.compile(r"\.\d+$", re.ASCII)
|
| 536 |
+
def is_HDN(text):
|
| 537 |
+
"""Return True if text is a host domain name."""
|
| 538 |
+
# XXX
|
| 539 |
+
# This may well be wrong. Which RFC is HDN defined in, if any (for
|
| 540 |
+
# the purposes of RFC 2965)?
|
| 541 |
+
# For the current implementation, what about IPv6? Remember to look
|
| 542 |
+
# at other uses of IPV4_RE also, if change this.
|
| 543 |
+
if IPV4_RE.search(text):
|
| 544 |
+
return False
|
| 545 |
+
if text == "":
|
| 546 |
+
return False
|
| 547 |
+
if text[0] == "." or text[-1] == ".":
|
| 548 |
+
return False
|
| 549 |
+
return True
|
| 550 |
+
|
| 551 |
+
def domain_match(A, B):
|
| 552 |
+
"""Return True if domain A domain-matches domain B, according to RFC 2965.
|
| 553 |
+
|
| 554 |
+
A and B may be host domain names or IP addresses.
|
| 555 |
+
|
| 556 |
+
RFC 2965, section 1:
|
| 557 |
+
|
| 558 |
+
Host names can be specified either as an IP address or a HDN string.
|
| 559 |
+
Sometimes we compare one host name with another. (Such comparisons SHALL
|
| 560 |
+
be case-insensitive.) Host A's name domain-matches host B's if
|
| 561 |
+
|
| 562 |
+
* their host name strings string-compare equal; or
|
| 563 |
+
|
| 564 |
+
* A is a HDN string and has the form NB, where N is a non-empty
|
| 565 |
+
name string, B has the form .B', and B' is a HDN string. (So,
|
| 566 |
+
x.y.com domain-matches .Y.com but not Y.com.)
|
| 567 |
+
|
| 568 |
+
Note that domain-match is not a commutative operation: a.b.c.com
|
| 569 |
+
domain-matches .c.com, but not the reverse.
|
| 570 |
+
|
| 571 |
+
"""
|
| 572 |
+
# Note that, if A or B are IP addresses, the only relevant part of the
|
| 573 |
+
# definition of the domain-match algorithm is the direct string-compare.
|
| 574 |
+
A = A.lower()
|
| 575 |
+
B = B.lower()
|
| 576 |
+
if A == B:
|
| 577 |
+
return True
|
| 578 |
+
if not is_HDN(A):
|
| 579 |
+
return False
|
| 580 |
+
i = A.rfind(B)
|
| 581 |
+
if i == -1 or i == 0:
|
| 582 |
+
# A does not have form NB, or N is the empty string
|
| 583 |
+
return False
|
| 584 |
+
if not B.startswith("."):
|
| 585 |
+
return False
|
| 586 |
+
if not is_HDN(B[1:]):
|
| 587 |
+
return False
|
| 588 |
+
return True
|
| 589 |
+
|
| 590 |
+
def liberal_is_HDN(text):
|
| 591 |
+
"""Return True if text is a sort-of-like a host domain name.
|
| 592 |
+
|
| 593 |
+
For accepting/blocking domains.
|
| 594 |
+
|
| 595 |
+
"""
|
| 596 |
+
if IPV4_RE.search(text):
|
| 597 |
+
return False
|
| 598 |
+
return True
|
| 599 |
+
|
| 600 |
+
def user_domain_match(A, B):
|
| 601 |
+
"""For blocking/accepting domains.
|
| 602 |
+
|
| 603 |
+
A and B may be host domain names or IP addresses.
|
| 604 |
+
|
| 605 |
+
"""
|
| 606 |
+
A = A.lower()
|
| 607 |
+
B = B.lower()
|
| 608 |
+
if not (liberal_is_HDN(A) and liberal_is_HDN(B)):
|
| 609 |
+
if A == B:
|
| 610 |
+
# equal IP addresses
|
| 611 |
+
return True
|
| 612 |
+
return False
|
| 613 |
+
initial_dot = B.startswith(".")
|
| 614 |
+
if initial_dot and A.endswith(B):
|
| 615 |
+
return True
|
| 616 |
+
if not initial_dot and A == B:
|
| 617 |
+
return True
|
| 618 |
+
return False
|
| 619 |
+
|
| 620 |
+
cut_port_re = re.compile(r":\d+$", re.ASCII)
|
| 621 |
+
def request_host(request):
|
| 622 |
+
"""Return request-host, as defined by RFC 2965.
|
| 623 |
+
|
| 624 |
+
Variation from RFC: returned value is lowercased, for convenient
|
| 625 |
+
comparison.
|
| 626 |
+
|
| 627 |
+
"""
|
| 628 |
+
url = request.get_full_url()
|
| 629 |
+
host = urllib.parse.urlparse(url)[1]
|
| 630 |
+
if host == "":
|
| 631 |
+
host = request.get_header("Host", "")
|
| 632 |
+
|
| 633 |
+
# remove port, if present
|
| 634 |
+
host = cut_port_re.sub("", host, 1)
|
| 635 |
+
return host.lower()
|
| 636 |
+
|
| 637 |
+
def eff_request_host(request):
|
| 638 |
+
"""Return a tuple (request-host, effective request-host name).
|
| 639 |
+
|
| 640 |
+
As defined by RFC 2965, except both are lowercased.
|
| 641 |
+
|
| 642 |
+
"""
|
| 643 |
+
erhn = req_host = request_host(request)
|
| 644 |
+
if req_host.find(".") == -1 and not IPV4_RE.search(req_host):
|
| 645 |
+
erhn = req_host + ".local"
|
| 646 |
+
return req_host, erhn
|
| 647 |
+
|
| 648 |
+
def request_path(request):
|
| 649 |
+
"""Path component of request-URI, as defined by RFC 2965."""
|
| 650 |
+
url = request.get_full_url()
|
| 651 |
+
parts = urllib.parse.urlsplit(url)
|
| 652 |
+
path = escape_path(parts.path)
|
| 653 |
+
if not path.startswith("/"):
|
| 654 |
+
# fix bad RFC 2396 absoluteURI
|
| 655 |
+
path = "/" + path
|
| 656 |
+
return path
|
| 657 |
+
|
| 658 |
+
def request_port(request):
|
| 659 |
+
host = request.host
|
| 660 |
+
i = host.find(':')
|
| 661 |
+
if i >= 0:
|
| 662 |
+
port = host[i+1:]
|
| 663 |
+
try:
|
| 664 |
+
int(port)
|
| 665 |
+
except ValueError:
|
| 666 |
+
_debug("nonnumeric port: '%s'", port)
|
| 667 |
+
return None
|
| 668 |
+
else:
|
| 669 |
+
port = DEFAULT_HTTP_PORT
|
| 670 |
+
return port
|
| 671 |
+
|
| 672 |
+
# Characters in addition to A-Z, a-z, 0-9, '_', '.', and '-' that don't
|
| 673 |
+
# need to be escaped to form a valid HTTP URL (RFCs 2396 and 1738).
|
| 674 |
+
HTTP_PATH_SAFE = "%/;:@&=+$,!~*'()"
|
| 675 |
+
ESCAPED_CHAR_RE = re.compile(r"%([0-9a-fA-F][0-9a-fA-F])")
|
| 676 |
+
def uppercase_escaped_char(match):
|
| 677 |
+
return "%%%s" % match.group(1).upper()
|
| 678 |
+
def escape_path(path):
|
| 679 |
+
"""Escape any invalid characters in HTTP URL, and uppercase all escapes."""
|
| 680 |
+
# There's no knowing what character encoding was used to create URLs
|
| 681 |
+
# containing %-escapes, but since we have to pick one to escape invalid
|
| 682 |
+
# path characters, we pick UTF-8, as recommended in the HTML 4.0
|
| 683 |
+
# specification:
|
| 684 |
+
# http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.2.1
|
| 685 |
+
# And here, kind of: draft-fielding-uri-rfc2396bis-03
|
| 686 |
+
# (And in draft IRI specification: draft-duerst-iri-05)
|
| 687 |
+
# (And here, for new URI schemes: RFC 2718)
|
| 688 |
+
path = urllib.parse.quote(path, HTTP_PATH_SAFE)
|
| 689 |
+
path = ESCAPED_CHAR_RE.sub(uppercase_escaped_char, path)
|
| 690 |
+
return path
|
| 691 |
+
|
| 692 |
+
def reach(h):
|
| 693 |
+
"""Return reach of host h, as defined by RFC 2965, section 1.
|
| 694 |
+
|
| 695 |
+
The reach R of a host name H is defined as follows:
|
| 696 |
+
|
| 697 |
+
* If
|
| 698 |
+
|
| 699 |
+
- H is the host domain name of a host; and,
|
| 700 |
+
|
| 701 |
+
- H has the form A.B; and
|
| 702 |
+
|
| 703 |
+
- A has no embedded (that is, interior) dots; and
|
| 704 |
+
|
| 705 |
+
- B has at least one embedded dot, or B is the string "local".
|
| 706 |
+
then the reach of H is .B.
|
| 707 |
+
|
| 708 |
+
* Otherwise, the reach of H is H.
|
| 709 |
+
|
| 710 |
+
>>> reach("www.acme.com")
|
| 711 |
+
'.acme.com'
|
| 712 |
+
>>> reach("acme.com")
|
| 713 |
+
'acme.com'
|
| 714 |
+
>>> reach("acme.local")
|
| 715 |
+
'.local'
|
| 716 |
+
|
| 717 |
+
"""
|
| 718 |
+
i = h.find(".")
|
| 719 |
+
if i >= 0:
|
| 720 |
+
#a = h[:i] # this line is only here to show what a is
|
| 721 |
+
b = h[i+1:]
|
| 722 |
+
i = b.find(".")
|
| 723 |
+
if is_HDN(h) and (i >= 0 or b == "local"):
|
| 724 |
+
return "."+b
|
| 725 |
+
return h
|
| 726 |
+
|
| 727 |
+
def is_third_party(request):
|
| 728 |
+
"""
|
| 729 |
+
|
| 730 |
+
RFC 2965, section 3.3.6:
|
| 731 |
+
|
| 732 |
+
An unverifiable transaction is to a third-party host if its request-
|
| 733 |
+
host U does not domain-match the reach R of the request-host O in the
|
| 734 |
+
origin transaction.
|
| 735 |
+
|
| 736 |
+
"""
|
| 737 |
+
req_host = request_host(request)
|
| 738 |
+
if not domain_match(req_host, reach(request.origin_req_host)):
|
| 739 |
+
return True
|
| 740 |
+
else:
|
| 741 |
+
return False
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
class Cookie:
|
| 745 |
+
"""HTTP Cookie.
|
| 746 |
+
|
| 747 |
+
This class represents both Netscape and RFC 2965 cookies.
|
| 748 |
+
|
| 749 |
+
This is deliberately a very simple class. It just holds attributes. It's
|
| 750 |
+
possible to construct Cookie instances that don't comply with the cookie
|
| 751 |
+
standards. CookieJar.make_cookies is the factory function for Cookie
|
| 752 |
+
objects -- it deals with cookie parsing, supplying defaults, and
|
| 753 |
+
normalising to the representation used in this class. CookiePolicy is
|
| 754 |
+
responsible for checking them to see whether they should be accepted from
|
| 755 |
+
and returned to the server.
|
| 756 |
+
|
| 757 |
+
Note that the port may be present in the headers, but unspecified ("Port"
|
| 758 |
+
rather than"Port=80", for example); if this is the case, port is None.
|
| 759 |
+
|
| 760 |
+
"""
|
| 761 |
+
|
| 762 |
+
def __init__(self, version, name, value,
|
| 763 |
+
port, port_specified,
|
| 764 |
+
domain, domain_specified, domain_initial_dot,
|
| 765 |
+
path, path_specified,
|
| 766 |
+
secure,
|
| 767 |
+
expires,
|
| 768 |
+
discard,
|
| 769 |
+
comment,
|
| 770 |
+
comment_url,
|
| 771 |
+
rest,
|
| 772 |
+
rfc2109=False,
|
| 773 |
+
):
|
| 774 |
+
|
| 775 |
+
if version is not None: version = int(version)
|
| 776 |
+
if expires is not None: expires = int(float(expires))
|
| 777 |
+
if port is None and port_specified is True:
|
| 778 |
+
raise ValueError("if port is None, port_specified must be false")
|
| 779 |
+
|
| 780 |
+
self.version = version
|
| 781 |
+
self.name = name
|
| 782 |
+
self.value = value
|
| 783 |
+
self.port = port
|
| 784 |
+
self.port_specified = port_specified
|
| 785 |
+
# normalise case, as per RFC 2965 section 3.3.3
|
| 786 |
+
self.domain = domain.lower()
|
| 787 |
+
self.domain_specified = domain_specified
|
| 788 |
+
# Sigh. We need to know whether the domain given in the
|
| 789 |
+
# cookie-attribute had an initial dot, in order to follow RFC 2965
|
| 790 |
+
# (as clarified in draft errata). Needed for the returned $Domain
|
| 791 |
+
# value.
|
| 792 |
+
self.domain_initial_dot = domain_initial_dot
|
| 793 |
+
self.path = path
|
| 794 |
+
self.path_specified = path_specified
|
| 795 |
+
self.secure = secure
|
| 796 |
+
self.expires = expires
|
| 797 |
+
self.discard = discard
|
| 798 |
+
self.comment = comment
|
| 799 |
+
self.comment_url = comment_url
|
| 800 |
+
self.rfc2109 = rfc2109
|
| 801 |
+
|
| 802 |
+
self._rest = copy.copy(rest)
|
| 803 |
+
|
| 804 |
+
def has_nonstandard_attr(self, name):
|
| 805 |
+
return name in self._rest
|
| 806 |
+
def get_nonstandard_attr(self, name, default=None):
|
| 807 |
+
return self._rest.get(name, default)
|
| 808 |
+
def set_nonstandard_attr(self, name, value):
|
| 809 |
+
self._rest[name] = value
|
| 810 |
+
|
| 811 |
+
def is_expired(self, now=None):
|
| 812 |
+
if now is None: now = time.time()
|
| 813 |
+
if (self.expires is not None) and (self.expires <= now):
|
| 814 |
+
return True
|
| 815 |
+
return False
|
| 816 |
+
|
| 817 |
+
def __str__(self):
|
| 818 |
+
if self.port is None: p = ""
|
| 819 |
+
else: p = ":"+self.port
|
| 820 |
+
limit = self.domain + p + self.path
|
| 821 |
+
if self.value is not None:
|
| 822 |
+
namevalue = "%s=%s" % (self.name, self.value)
|
| 823 |
+
else:
|
| 824 |
+
namevalue = self.name
|
| 825 |
+
return "<Cookie %s for %s>" % (namevalue, limit)
|
| 826 |
+
|
| 827 |
+
def __repr__(self):
|
| 828 |
+
args = []
|
| 829 |
+
for name in ("version", "name", "value",
|
| 830 |
+
"port", "port_specified",
|
| 831 |
+
"domain", "domain_specified", "domain_initial_dot",
|
| 832 |
+
"path", "path_specified",
|
| 833 |
+
"secure", "expires", "discard", "comment", "comment_url",
|
| 834 |
+
):
|
| 835 |
+
attr = getattr(self, name)
|
| 836 |
+
args.append("%s=%s" % (name, repr(attr)))
|
| 837 |
+
args.append("rest=%s" % repr(self._rest))
|
| 838 |
+
args.append("rfc2109=%s" % repr(self.rfc2109))
|
| 839 |
+
return "%s(%s)" % (self.__class__.__name__, ", ".join(args))
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
class CookiePolicy:
|
| 843 |
+
"""Defines which cookies get accepted from and returned to server.
|
| 844 |
+
|
| 845 |
+
May also modify cookies, though this is probably a bad idea.
|
| 846 |
+
|
| 847 |
+
The subclass DefaultCookiePolicy defines the standard rules for Netscape
|
| 848 |
+
and RFC 2965 cookies -- override that if you want a customized policy.
|
| 849 |
+
|
| 850 |
+
"""
|
| 851 |
+
def set_ok(self, cookie, request):
|
| 852 |
+
"""Return true if (and only if) cookie should be accepted from server.
|
| 853 |
+
|
| 854 |
+
Currently, pre-expired cookies never get this far -- the CookieJar
|
| 855 |
+
class deletes such cookies itself.
|
| 856 |
+
|
| 857 |
+
"""
|
| 858 |
+
raise NotImplementedError()
|
| 859 |
+
|
| 860 |
+
def return_ok(self, cookie, request):
|
| 861 |
+
"""Return true if (and only if) cookie should be returned to server."""
|
| 862 |
+
raise NotImplementedError()
|
| 863 |
+
|
| 864 |
+
def domain_return_ok(self, domain, request):
|
| 865 |
+
"""Return false if cookies should not be returned, given cookie domain.
|
| 866 |
+
"""
|
| 867 |
+
return True
|
| 868 |
+
|
| 869 |
+
def path_return_ok(self, path, request):
|
| 870 |
+
"""Return false if cookies should not be returned, given cookie path.
|
| 871 |
+
"""
|
| 872 |
+
return True
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
class DefaultCookiePolicy(CookiePolicy):
|
| 876 |
+
"""Implements the standard rules for accepting and returning cookies."""
|
| 877 |
+
|
| 878 |
+
DomainStrictNoDots = 1
|
| 879 |
+
DomainStrictNonDomain = 2
|
| 880 |
+
DomainRFC2965Match = 4
|
| 881 |
+
|
| 882 |
+
DomainLiberal = 0
|
| 883 |
+
DomainStrict = DomainStrictNoDots|DomainStrictNonDomain
|
| 884 |
+
|
| 885 |
+
def __init__(self,
|
| 886 |
+
blocked_domains=None, allowed_domains=None,
|
| 887 |
+
netscape=True, rfc2965=False,
|
| 888 |
+
rfc2109_as_netscape=None,
|
| 889 |
+
hide_cookie2=False,
|
| 890 |
+
strict_domain=False,
|
| 891 |
+
strict_rfc2965_unverifiable=True,
|
| 892 |
+
strict_ns_unverifiable=False,
|
| 893 |
+
strict_ns_domain=DomainLiberal,
|
| 894 |
+
strict_ns_set_initial_dollar=False,
|
| 895 |
+
strict_ns_set_path=False,
|
| 896 |
+
secure_protocols=("https", "wss")
|
| 897 |
+
):
|
| 898 |
+
"""Constructor arguments should be passed as keyword arguments only."""
|
| 899 |
+
self.netscape = netscape
|
| 900 |
+
self.rfc2965 = rfc2965
|
| 901 |
+
self.rfc2109_as_netscape = rfc2109_as_netscape
|
| 902 |
+
self.hide_cookie2 = hide_cookie2
|
| 903 |
+
self.strict_domain = strict_domain
|
| 904 |
+
self.strict_rfc2965_unverifiable = strict_rfc2965_unverifiable
|
| 905 |
+
self.strict_ns_unverifiable = strict_ns_unverifiable
|
| 906 |
+
self.strict_ns_domain = strict_ns_domain
|
| 907 |
+
self.strict_ns_set_initial_dollar = strict_ns_set_initial_dollar
|
| 908 |
+
self.strict_ns_set_path = strict_ns_set_path
|
| 909 |
+
self.secure_protocols = secure_protocols
|
| 910 |
+
|
| 911 |
+
if blocked_domains is not None:
|
| 912 |
+
self._blocked_domains = tuple(blocked_domains)
|
| 913 |
+
else:
|
| 914 |
+
self._blocked_domains = ()
|
| 915 |
+
|
| 916 |
+
if allowed_domains is not None:
|
| 917 |
+
allowed_domains = tuple(allowed_domains)
|
| 918 |
+
self._allowed_domains = allowed_domains
|
| 919 |
+
|
| 920 |
+
def blocked_domains(self):
|
| 921 |
+
"""Return the sequence of blocked domains (as a tuple)."""
|
| 922 |
+
return self._blocked_domains
|
| 923 |
+
def set_blocked_domains(self, blocked_domains):
|
| 924 |
+
"""Set the sequence of blocked domains."""
|
| 925 |
+
self._blocked_domains = tuple(blocked_domains)
|
| 926 |
+
|
| 927 |
+
def is_blocked(self, domain):
|
| 928 |
+
for blocked_domain in self._blocked_domains:
|
| 929 |
+
if user_domain_match(domain, blocked_domain):
|
| 930 |
+
return True
|
| 931 |
+
return False
|
| 932 |
+
|
| 933 |
+
def allowed_domains(self):
|
| 934 |
+
"""Return None, or the sequence of allowed domains (as a tuple)."""
|
| 935 |
+
return self._allowed_domains
|
| 936 |
+
def set_allowed_domains(self, allowed_domains):
|
| 937 |
+
"""Set the sequence of allowed domains, or None."""
|
| 938 |
+
if allowed_domains is not None:
|
| 939 |
+
allowed_domains = tuple(allowed_domains)
|
| 940 |
+
self._allowed_domains = allowed_domains
|
| 941 |
+
|
| 942 |
+
def is_not_allowed(self, domain):
|
| 943 |
+
if self._allowed_domains is None:
|
| 944 |
+
return False
|
| 945 |
+
for allowed_domain in self._allowed_domains:
|
| 946 |
+
if user_domain_match(domain, allowed_domain):
|
| 947 |
+
return False
|
| 948 |
+
return True
|
| 949 |
+
|
| 950 |
+
def set_ok(self, cookie, request):
|
| 951 |
+
"""
|
| 952 |
+
If you override .set_ok(), be sure to call this method. If it returns
|
| 953 |
+
false, so should your subclass (assuming your subclass wants to be more
|
| 954 |
+
strict about which cookies to accept).
|
| 955 |
+
|
| 956 |
+
"""
|
| 957 |
+
_debug(" - checking cookie %s=%s", cookie.name, cookie.value)
|
| 958 |
+
|
| 959 |
+
assert cookie.name is not None
|
| 960 |
+
|
| 961 |
+
for n in "version", "verifiability", "name", "path", "domain", "port":
|
| 962 |
+
fn_name = "set_ok_"+n
|
| 963 |
+
fn = getattr(self, fn_name)
|
| 964 |
+
if not fn(cookie, request):
|
| 965 |
+
return False
|
| 966 |
+
|
| 967 |
+
return True
|
| 968 |
+
|
| 969 |
+
def set_ok_version(self, cookie, request):
|
| 970 |
+
if cookie.version is None:
|
| 971 |
+
# Version is always set to 0 by parse_ns_headers if it's a Netscape
|
| 972 |
+
# cookie, so this must be an invalid RFC 2965 cookie.
|
| 973 |
+
_debug(" Set-Cookie2 without version attribute (%s=%s)",
|
| 974 |
+
cookie.name, cookie.value)
|
| 975 |
+
return False
|
| 976 |
+
if cookie.version > 0 and not self.rfc2965:
|
| 977 |
+
_debug(" RFC 2965 cookies are switched off")
|
| 978 |
+
return False
|
| 979 |
+
elif cookie.version == 0 and not self.netscape:
|
| 980 |
+
_debug(" Netscape cookies are switched off")
|
| 981 |
+
return False
|
| 982 |
+
return True
|
| 983 |
+
|
| 984 |
+
def set_ok_verifiability(self, cookie, request):
|
| 985 |
+
if request.unverifiable and is_third_party(request):
|
| 986 |
+
if cookie.version > 0 and self.strict_rfc2965_unverifiable:
|
| 987 |
+
_debug(" third-party RFC 2965 cookie during "
|
| 988 |
+
"unverifiable transaction")
|
| 989 |
+
return False
|
| 990 |
+
elif cookie.version == 0 and self.strict_ns_unverifiable:
|
| 991 |
+
_debug(" third-party Netscape cookie during "
|
| 992 |
+
"unverifiable transaction")
|
| 993 |
+
return False
|
| 994 |
+
return True
|
| 995 |
+
|
| 996 |
+
def set_ok_name(self, cookie, request):
|
| 997 |
+
# Try and stop servers setting V0 cookies designed to hack other
|
| 998 |
+
# servers that know both V0 and V1 protocols.
|
| 999 |
+
if (cookie.version == 0 and self.strict_ns_set_initial_dollar and
|
| 1000 |
+
cookie.name.startswith("$")):
|
| 1001 |
+
_debug(" illegal name (starts with '$'): '%s'", cookie.name)
|
| 1002 |
+
return False
|
| 1003 |
+
return True
|
| 1004 |
+
|
| 1005 |
+
def set_ok_path(self, cookie, request):
|
| 1006 |
+
if cookie.path_specified:
|
| 1007 |
+
req_path = request_path(request)
|
| 1008 |
+
if ((cookie.version > 0 or
|
| 1009 |
+
(cookie.version == 0 and self.strict_ns_set_path)) and
|
| 1010 |
+
not self.path_return_ok(cookie.path, request)):
|
| 1011 |
+
_debug(" path attribute %s is not a prefix of request "
|
| 1012 |
+
"path %s", cookie.path, req_path)
|
| 1013 |
+
return False
|
| 1014 |
+
return True
|
| 1015 |
+
|
| 1016 |
+
def set_ok_domain(self, cookie, request):
|
| 1017 |
+
if self.is_blocked(cookie.domain):
|
| 1018 |
+
_debug(" domain %s is in user block-list", cookie.domain)
|
| 1019 |
+
return False
|
| 1020 |
+
if self.is_not_allowed(cookie.domain):
|
| 1021 |
+
_debug(" domain %s is not in user allow-list", cookie.domain)
|
| 1022 |
+
return False
|
| 1023 |
+
if cookie.domain_specified:
|
| 1024 |
+
req_host, erhn = eff_request_host(request)
|
| 1025 |
+
domain = cookie.domain
|
| 1026 |
+
if self.strict_domain and (domain.count(".") >= 2):
|
| 1027 |
+
# XXX This should probably be compared with the Konqueror
|
| 1028 |
+
# (kcookiejar.cpp) and Mozilla implementations, but it's a
|
| 1029 |
+
# losing battle.
|
| 1030 |
+
i = domain.rfind(".")
|
| 1031 |
+
j = domain.rfind(".", 0, i)
|
| 1032 |
+
if j == 0: # domain like .foo.bar
|
| 1033 |
+
tld = domain[i+1:]
|
| 1034 |
+
sld = domain[j+1:i]
|
| 1035 |
+
if sld.lower() in ("co", "ac", "com", "edu", "org", "net",
|
| 1036 |
+
"gov", "mil", "int", "aero", "biz", "cat", "coop",
|
| 1037 |
+
"info", "jobs", "mobi", "museum", "name", "pro",
|
| 1038 |
+
"travel", "eu") and len(tld) == 2:
|
| 1039 |
+
# domain like .co.uk
|
| 1040 |
+
_debug(" country-code second level domain %s", domain)
|
| 1041 |
+
return False
|
| 1042 |
+
if domain.startswith("."):
|
| 1043 |
+
undotted_domain = domain[1:]
|
| 1044 |
+
else:
|
| 1045 |
+
undotted_domain = domain
|
| 1046 |
+
embedded_dots = (undotted_domain.find(".") >= 0)
|
| 1047 |
+
if not embedded_dots and domain != ".local":
|
| 1048 |
+
_debug(" non-local domain %s contains no embedded dot",
|
| 1049 |
+
domain)
|
| 1050 |
+
return False
|
| 1051 |
+
if cookie.version == 0:
|
| 1052 |
+
if (not erhn.endswith(domain) and
|
| 1053 |
+
(not erhn.startswith(".") and
|
| 1054 |
+
not ("."+erhn).endswith(domain))):
|
| 1055 |
+
_debug(" effective request-host %s (even with added "
|
| 1056 |
+
"initial dot) does not end with %s",
|
| 1057 |
+
erhn, domain)
|
| 1058 |
+
return False
|
| 1059 |
+
if (cookie.version > 0 or
|
| 1060 |
+
(self.strict_ns_domain & self.DomainRFC2965Match)):
|
| 1061 |
+
if not domain_match(erhn, domain):
|
| 1062 |
+
_debug(" effective request-host %s does not domain-match "
|
| 1063 |
+
"%s", erhn, domain)
|
| 1064 |
+
return False
|
| 1065 |
+
if (cookie.version > 0 or
|
| 1066 |
+
(self.strict_ns_domain & self.DomainStrictNoDots)):
|
| 1067 |
+
host_prefix = req_host[:-len(domain)]
|
| 1068 |
+
if (host_prefix.find(".") >= 0 and
|
| 1069 |
+
not IPV4_RE.search(req_host)):
|
| 1070 |
+
_debug(" host prefix %s for domain %s contains a dot",
|
| 1071 |
+
host_prefix, domain)
|
| 1072 |
+
return False
|
| 1073 |
+
return True
|
| 1074 |
+
|
| 1075 |
+
def set_ok_port(self, cookie, request):
|
| 1076 |
+
if cookie.port_specified:
|
| 1077 |
+
req_port = request_port(request)
|
| 1078 |
+
if req_port is None:
|
| 1079 |
+
req_port = "80"
|
| 1080 |
+
else:
|
| 1081 |
+
req_port = str(req_port)
|
| 1082 |
+
for p in cookie.port.split(","):
|
| 1083 |
+
try:
|
| 1084 |
+
int(p)
|
| 1085 |
+
except ValueError:
|
| 1086 |
+
_debug(" bad port %s (not numeric)", p)
|
| 1087 |
+
return False
|
| 1088 |
+
if p == req_port:
|
| 1089 |
+
break
|
| 1090 |
+
else:
|
| 1091 |
+
_debug(" request port (%s) not found in %s",
|
| 1092 |
+
req_port, cookie.port)
|
| 1093 |
+
return False
|
| 1094 |
+
return True
|
| 1095 |
+
|
| 1096 |
+
def return_ok(self, cookie, request):
|
| 1097 |
+
"""
|
| 1098 |
+
If you override .return_ok(), be sure to call this method. If it
|
| 1099 |
+
returns false, so should your subclass (assuming your subclass wants to
|
| 1100 |
+
be more strict about which cookies to return).
|
| 1101 |
+
|
| 1102 |
+
"""
|
| 1103 |
+
# Path has already been checked by .path_return_ok(), and domain
|
| 1104 |
+
# blocking done by .domain_return_ok().
|
| 1105 |
+
_debug(" - checking cookie %s=%s", cookie.name, cookie.value)
|
| 1106 |
+
|
| 1107 |
+
for n in "version", "verifiability", "secure", "expires", "port", "domain":
|
| 1108 |
+
fn_name = "return_ok_"+n
|
| 1109 |
+
fn = getattr(self, fn_name)
|
| 1110 |
+
if not fn(cookie, request):
|
| 1111 |
+
return False
|
| 1112 |
+
return True
|
| 1113 |
+
|
| 1114 |
+
def return_ok_version(self, cookie, request):
|
| 1115 |
+
if cookie.version > 0 and not self.rfc2965:
|
| 1116 |
+
_debug(" RFC 2965 cookies are switched off")
|
| 1117 |
+
return False
|
| 1118 |
+
elif cookie.version == 0 and not self.netscape:
|
| 1119 |
+
_debug(" Netscape cookies are switched off")
|
| 1120 |
+
return False
|
| 1121 |
+
return True
|
| 1122 |
+
|
| 1123 |
+
def return_ok_verifiability(self, cookie, request):
|
| 1124 |
+
if request.unverifiable and is_third_party(request):
|
| 1125 |
+
if cookie.version > 0 and self.strict_rfc2965_unverifiable:
|
| 1126 |
+
_debug(" third-party RFC 2965 cookie during unverifiable "
|
| 1127 |
+
"transaction")
|
| 1128 |
+
return False
|
| 1129 |
+
elif cookie.version == 0 and self.strict_ns_unverifiable:
|
| 1130 |
+
_debug(" third-party Netscape cookie during unverifiable "
|
| 1131 |
+
"transaction")
|
| 1132 |
+
return False
|
| 1133 |
+
return True
|
| 1134 |
+
|
| 1135 |
+
def return_ok_secure(self, cookie, request):
|
| 1136 |
+
if cookie.secure and request.type not in self.secure_protocols:
|
| 1137 |
+
_debug(" secure cookie with non-secure request")
|
| 1138 |
+
return False
|
| 1139 |
+
return True
|
| 1140 |
+
|
| 1141 |
+
def return_ok_expires(self, cookie, request):
|
| 1142 |
+
if cookie.is_expired(self._now):
|
| 1143 |
+
_debug(" cookie expired")
|
| 1144 |
+
return False
|
| 1145 |
+
return True
|
| 1146 |
+
|
| 1147 |
+
def return_ok_port(self, cookie, request):
|
| 1148 |
+
if cookie.port:
|
| 1149 |
+
req_port = request_port(request)
|
| 1150 |
+
if req_port is None:
|
| 1151 |
+
req_port = "80"
|
| 1152 |
+
for p in cookie.port.split(","):
|
| 1153 |
+
if p == req_port:
|
| 1154 |
+
break
|
| 1155 |
+
else:
|
| 1156 |
+
_debug(" request port %s does not match cookie port %s",
|
| 1157 |
+
req_port, cookie.port)
|
| 1158 |
+
return False
|
| 1159 |
+
return True
|
| 1160 |
+
|
| 1161 |
+
def return_ok_domain(self, cookie, request):
|
| 1162 |
+
req_host, erhn = eff_request_host(request)
|
| 1163 |
+
domain = cookie.domain
|
| 1164 |
+
|
| 1165 |
+
if domain and not domain.startswith("."):
|
| 1166 |
+
dotdomain = "." + domain
|
| 1167 |
+
else:
|
| 1168 |
+
dotdomain = domain
|
| 1169 |
+
|
| 1170 |
+
# strict check of non-domain cookies: Mozilla does this, MSIE5 doesn't
|
| 1171 |
+
if (cookie.version == 0 and
|
| 1172 |
+
(self.strict_ns_domain & self.DomainStrictNonDomain) and
|
| 1173 |
+
not cookie.domain_specified and domain != erhn):
|
| 1174 |
+
_debug(" cookie with unspecified domain does not string-compare "
|
| 1175 |
+
"equal to request domain")
|
| 1176 |
+
return False
|
| 1177 |
+
|
| 1178 |
+
if cookie.version > 0 and not domain_match(erhn, domain):
|
| 1179 |
+
_debug(" effective request-host name %s does not domain-match "
|
| 1180 |
+
"RFC 2965 cookie domain %s", erhn, domain)
|
| 1181 |
+
return False
|
| 1182 |
+
if cookie.version == 0 and not ("."+erhn).endswith(dotdomain):
|
| 1183 |
+
_debug(" request-host %s does not match Netscape cookie domain "
|
| 1184 |
+
"%s", req_host, domain)
|
| 1185 |
+
return False
|
| 1186 |
+
return True
|
| 1187 |
+
|
| 1188 |
+
def domain_return_ok(self, domain, request):
|
| 1189 |
+
# Liberal check of. This is here as an optimization to avoid
|
| 1190 |
+
# having to load lots of MSIE cookie files unless necessary.
|
| 1191 |
+
req_host, erhn = eff_request_host(request)
|
| 1192 |
+
if not req_host.startswith("."):
|
| 1193 |
+
req_host = "."+req_host
|
| 1194 |
+
if not erhn.startswith("."):
|
| 1195 |
+
erhn = "."+erhn
|
| 1196 |
+
if domain and not domain.startswith("."):
|
| 1197 |
+
dotdomain = "." + domain
|
| 1198 |
+
else:
|
| 1199 |
+
dotdomain = domain
|
| 1200 |
+
if not (req_host.endswith(dotdomain) or erhn.endswith(dotdomain)):
|
| 1201 |
+
#_debug(" request domain %s does not match cookie domain %s",
|
| 1202 |
+
# req_host, domain)
|
| 1203 |
+
return False
|
| 1204 |
+
|
| 1205 |
+
if self.is_blocked(domain):
|
| 1206 |
+
_debug(" domain %s is in user block-list", domain)
|
| 1207 |
+
return False
|
| 1208 |
+
if self.is_not_allowed(domain):
|
| 1209 |
+
_debug(" domain %s is not in user allow-list", domain)
|
| 1210 |
+
return False
|
| 1211 |
+
|
| 1212 |
+
return True
|
| 1213 |
+
|
| 1214 |
+
def path_return_ok(self, path, request):
|
| 1215 |
+
_debug("- checking cookie path=%s", path)
|
| 1216 |
+
req_path = request_path(request)
|
| 1217 |
+
pathlen = len(path)
|
| 1218 |
+
if req_path == path:
|
| 1219 |
+
return True
|
| 1220 |
+
elif (req_path.startswith(path) and
|
| 1221 |
+
(path.endswith("/") or req_path[pathlen:pathlen+1] == "/")):
|
| 1222 |
+
return True
|
| 1223 |
+
|
| 1224 |
+
_debug(" %s does not path-match %s", req_path, path)
|
| 1225 |
+
return False
|
| 1226 |
+
|
| 1227 |
+
def vals_sorted_by_key(adict):
|
| 1228 |
+
keys = sorted(adict.keys())
|
| 1229 |
+
return map(adict.get, keys)
|
| 1230 |
+
|
| 1231 |
+
def deepvalues(mapping):
|
| 1232 |
+
"""Iterates over nested mapping, depth-first, in sorted order by key."""
|
| 1233 |
+
values = vals_sorted_by_key(mapping)
|
| 1234 |
+
for obj in values:
|
| 1235 |
+
mapping = False
|
| 1236 |
+
try:
|
| 1237 |
+
obj.items
|
| 1238 |
+
except AttributeError:
|
| 1239 |
+
pass
|
| 1240 |
+
else:
|
| 1241 |
+
mapping = True
|
| 1242 |
+
yield from deepvalues(obj)
|
| 1243 |
+
if not mapping:
|
| 1244 |
+
yield obj
|
| 1245 |
+
|
| 1246 |
+
|
| 1247 |
+
# Used as second parameter to dict.get() method, to distinguish absent
|
| 1248 |
+
# dict key from one with a None value.
|
| 1249 |
+
class Absent: pass
|
| 1250 |
+
|
| 1251 |
+
class CookieJar:
|
| 1252 |
+
"""Collection of HTTP cookies.
|
| 1253 |
+
|
| 1254 |
+
You may not need to know about this class: try
|
| 1255 |
+
urllib.request.build_opener(HTTPCookieProcessor).open(url).
|
| 1256 |
+
"""
|
| 1257 |
+
|
| 1258 |
+
non_word_re = re.compile(r"\W")
|
| 1259 |
+
quote_re = re.compile(r"([\"\\])")
|
| 1260 |
+
strict_domain_re = re.compile(r"\.?[^.]*")
|
| 1261 |
+
domain_re = re.compile(r"[^.]*")
|
| 1262 |
+
dots_re = re.compile(r"^\.+")
|
| 1263 |
+
|
| 1264 |
+
magic_re = re.compile(r"^\#LWP-Cookies-(\d+\.\d+)", re.ASCII)
|
| 1265 |
+
|
| 1266 |
+
def __init__(self, policy=None):
|
| 1267 |
+
if policy is None:
|
| 1268 |
+
policy = DefaultCookiePolicy()
|
| 1269 |
+
self._policy = policy
|
| 1270 |
+
|
| 1271 |
+
self._cookies_lock = _threading.RLock()
|
| 1272 |
+
self._cookies = {}
|
| 1273 |
+
|
| 1274 |
+
def set_policy(self, policy):
|
| 1275 |
+
self._policy = policy
|
| 1276 |
+
|
| 1277 |
+
def _cookies_for_domain(self, domain, request):
|
| 1278 |
+
cookies = []
|
| 1279 |
+
if not self._policy.domain_return_ok(domain, request):
|
| 1280 |
+
return []
|
| 1281 |
+
_debug("Checking %s for cookies to return", domain)
|
| 1282 |
+
cookies_by_path = self._cookies[domain]
|
| 1283 |
+
for path in cookies_by_path.keys():
|
| 1284 |
+
if not self._policy.path_return_ok(path, request):
|
| 1285 |
+
continue
|
| 1286 |
+
cookies_by_name = cookies_by_path[path]
|
| 1287 |
+
for cookie in cookies_by_name.values():
|
| 1288 |
+
if not self._policy.return_ok(cookie, request):
|
| 1289 |
+
_debug(" not returning cookie")
|
| 1290 |
+
continue
|
| 1291 |
+
_debug(" it's a match")
|
| 1292 |
+
cookies.append(cookie)
|
| 1293 |
+
return cookies
|
| 1294 |
+
|
| 1295 |
+
def _cookies_for_request(self, request):
|
| 1296 |
+
"""Return a list of cookies to be returned to server."""
|
| 1297 |
+
cookies = []
|
| 1298 |
+
for domain in self._cookies.keys():
|
| 1299 |
+
cookies.extend(self._cookies_for_domain(domain, request))
|
| 1300 |
+
return cookies
|
| 1301 |
+
|
| 1302 |
+
def _cookie_attrs(self, cookies):
|
| 1303 |
+
"""Return a list of cookie-attributes to be returned to server.
|
| 1304 |
+
|
| 1305 |
+
like ['foo="bar"; $Path="/"', ...]
|
| 1306 |
+
|
| 1307 |
+
The $Version attribute is also added when appropriate (currently only
|
| 1308 |
+
once per request).
|
| 1309 |
+
|
| 1310 |
+
"""
|
| 1311 |
+
# add cookies in order of most specific (ie. longest) path first
|
| 1312 |
+
cookies.sort(key=lambda a: len(a.path), reverse=True)
|
| 1313 |
+
|
| 1314 |
+
version_set = False
|
| 1315 |
+
|
| 1316 |
+
attrs = []
|
| 1317 |
+
for cookie in cookies:
|
| 1318 |
+
# set version of Cookie header
|
| 1319 |
+
# XXX
|
| 1320 |
+
# What should it be if multiple matching Set-Cookie headers have
|
| 1321 |
+
# different versions themselves?
|
| 1322 |
+
# Answer: there is no answer; was supposed to be settled by
|
| 1323 |
+
# RFC 2965 errata, but that may never appear...
|
| 1324 |
+
version = cookie.version
|
| 1325 |
+
if not version_set:
|
| 1326 |
+
version_set = True
|
| 1327 |
+
if version > 0:
|
| 1328 |
+
attrs.append("$Version=%s" % version)
|
| 1329 |
+
|
| 1330 |
+
# quote cookie value if necessary
|
| 1331 |
+
# (not for Netscape protocol, which already has any quotes
|
| 1332 |
+
# intact, due to the poorly-specified Netscape Cookie: syntax)
|
| 1333 |
+
if ((cookie.value is not None) and
|
| 1334 |
+
self.non_word_re.search(cookie.value) and version > 0):
|
| 1335 |
+
value = self.quote_re.sub(r"\\\1", cookie.value)
|
| 1336 |
+
else:
|
| 1337 |
+
value = cookie.value
|
| 1338 |
+
|
| 1339 |
+
# add cookie-attributes to be returned in Cookie header
|
| 1340 |
+
if cookie.value is None:
|
| 1341 |
+
attrs.append(cookie.name)
|
| 1342 |
+
else:
|
| 1343 |
+
attrs.append("%s=%s" % (cookie.name, value))
|
| 1344 |
+
if version > 0:
|
| 1345 |
+
if cookie.path_specified:
|
| 1346 |
+
attrs.append('$Path="%s"' % cookie.path)
|
| 1347 |
+
if cookie.domain.startswith("."):
|
| 1348 |
+
domain = cookie.domain
|
| 1349 |
+
if (not cookie.domain_initial_dot and
|
| 1350 |
+
domain.startswith(".")):
|
| 1351 |
+
domain = domain[1:]
|
| 1352 |
+
attrs.append('$Domain="%s"' % domain)
|
| 1353 |
+
if cookie.port is not None:
|
| 1354 |
+
p = "$Port"
|
| 1355 |
+
if cookie.port_specified:
|
| 1356 |
+
p = p + ('="%s"' % cookie.port)
|
| 1357 |
+
attrs.append(p)
|
| 1358 |
+
|
| 1359 |
+
return attrs
|
| 1360 |
+
|
| 1361 |
+
def add_cookie_header(self, request):
|
| 1362 |
+
"""Add correct Cookie: header to request (urllib.request.Request object).
|
| 1363 |
+
|
| 1364 |
+
The Cookie2 header is also added unless policy.hide_cookie2 is true.
|
| 1365 |
+
|
| 1366 |
+
"""
|
| 1367 |
+
_debug("add_cookie_header")
|
| 1368 |
+
self._cookies_lock.acquire()
|
| 1369 |
+
try:
|
| 1370 |
+
|
| 1371 |
+
self._policy._now = self._now = int(time.time())
|
| 1372 |
+
|
| 1373 |
+
cookies = self._cookies_for_request(request)
|
| 1374 |
+
|
| 1375 |
+
attrs = self._cookie_attrs(cookies)
|
| 1376 |
+
if attrs:
|
| 1377 |
+
if not request.has_header("Cookie"):
|
| 1378 |
+
request.add_unredirected_header(
|
| 1379 |
+
"Cookie", "; ".join(attrs))
|
| 1380 |
+
|
| 1381 |
+
# if necessary, advertise that we know RFC 2965
|
| 1382 |
+
if (self._policy.rfc2965 and not self._policy.hide_cookie2 and
|
| 1383 |
+
not request.has_header("Cookie2")):
|
| 1384 |
+
for cookie in cookies:
|
| 1385 |
+
if cookie.version != 1:
|
| 1386 |
+
request.add_unredirected_header("Cookie2", '$Version="1"')
|
| 1387 |
+
break
|
| 1388 |
+
|
| 1389 |
+
finally:
|
| 1390 |
+
self._cookies_lock.release()
|
| 1391 |
+
|
| 1392 |
+
self.clear_expired_cookies()
|
| 1393 |
+
|
| 1394 |
+
def _normalized_cookie_tuples(self, attrs_set):
|
| 1395 |
+
"""Return list of tuples containing normalised cookie information.
|
| 1396 |
+
|
| 1397 |
+
attrs_set is the list of lists of key,value pairs extracted from
|
| 1398 |
+
the Set-Cookie or Set-Cookie2 headers.
|
| 1399 |
+
|
| 1400 |
+
Tuples are name, value, standard, rest, where name and value are the
|
| 1401 |
+
cookie name and value, standard is a dictionary containing the standard
|
| 1402 |
+
cookie-attributes (discard, secure, version, expires or max-age,
|
| 1403 |
+
domain, path and port) and rest is a dictionary containing the rest of
|
| 1404 |
+
the cookie-attributes.
|
| 1405 |
+
|
| 1406 |
+
"""
|
| 1407 |
+
cookie_tuples = []
|
| 1408 |
+
|
| 1409 |
+
boolean_attrs = "discard", "secure"
|
| 1410 |
+
value_attrs = ("version",
|
| 1411 |
+
"expires", "max-age",
|
| 1412 |
+
"domain", "path", "port",
|
| 1413 |
+
"comment", "commenturl")
|
| 1414 |
+
|
| 1415 |
+
for cookie_attrs in attrs_set:
|
| 1416 |
+
name, value = cookie_attrs[0]
|
| 1417 |
+
|
| 1418 |
+
# Build dictionary of standard cookie-attributes (standard) and
|
| 1419 |
+
# dictionary of other cookie-attributes (rest).
|
| 1420 |
+
|
| 1421 |
+
# Note: expiry time is normalised to seconds since epoch. V0
|
| 1422 |
+
# cookies should have the Expires cookie-attribute, and V1 cookies
|
| 1423 |
+
# should have Max-Age, but since V1 includes RFC 2109 cookies (and
|
| 1424 |
+
# since V0 cookies may be a mish-mash of Netscape and RFC 2109), we
|
| 1425 |
+
# accept either (but prefer Max-Age).
|
| 1426 |
+
max_age_set = False
|
| 1427 |
+
|
| 1428 |
+
bad_cookie = False
|
| 1429 |
+
|
| 1430 |
+
standard = {}
|
| 1431 |
+
rest = {}
|
| 1432 |
+
for k, v in cookie_attrs[1:]:
|
| 1433 |
+
lc = k.lower()
|
| 1434 |
+
# don't lose case distinction for unknown fields
|
| 1435 |
+
if lc in value_attrs or lc in boolean_attrs:
|
| 1436 |
+
k = lc
|
| 1437 |
+
if k in boolean_attrs and v is None:
|
| 1438 |
+
# boolean cookie-attribute is present, but has no value
|
| 1439 |
+
# (like "discard", rather than "port=80")
|
| 1440 |
+
v = True
|
| 1441 |
+
if k in standard:
|
| 1442 |
+
# only first value is significant
|
| 1443 |
+
continue
|
| 1444 |
+
if k == "domain":
|
| 1445 |
+
if v is None:
|
| 1446 |
+
_debug(" missing value for domain attribute")
|
| 1447 |
+
bad_cookie = True
|
| 1448 |
+
break
|
| 1449 |
+
# RFC 2965 section 3.3.3
|
| 1450 |
+
v = v.lower()
|
| 1451 |
+
if k == "expires":
|
| 1452 |
+
if max_age_set:
|
| 1453 |
+
# Prefer max-age to expires (like Mozilla)
|
| 1454 |
+
continue
|
| 1455 |
+
if v is None:
|
| 1456 |
+
_debug(" missing or invalid value for expires "
|
| 1457 |
+
"attribute: treating as session cookie")
|
| 1458 |
+
continue
|
| 1459 |
+
if k == "max-age":
|
| 1460 |
+
max_age_set = True
|
| 1461 |
+
try:
|
| 1462 |
+
v = int(v)
|
| 1463 |
+
except ValueError:
|
| 1464 |
+
_debug(" missing or invalid (non-numeric) value for "
|
| 1465 |
+
"max-age attribute")
|
| 1466 |
+
bad_cookie = True
|
| 1467 |
+
break
|
| 1468 |
+
# convert RFC 2965 Max-Age to seconds since epoch
|
| 1469 |
+
# XXX Strictly you're supposed to follow RFC 2616
|
| 1470 |
+
# age-calculation rules. Remember that zero Max-Age
|
| 1471 |
+
# is a request to discard (old and new) cookie, though.
|
| 1472 |
+
k = "expires"
|
| 1473 |
+
v = self._now + v
|
| 1474 |
+
if (k in value_attrs) or (k in boolean_attrs):
|
| 1475 |
+
if (v is None and
|
| 1476 |
+
k not in ("port", "comment", "commenturl")):
|
| 1477 |
+
_debug(" missing value for %s attribute" % k)
|
| 1478 |
+
bad_cookie = True
|
| 1479 |
+
break
|
| 1480 |
+
standard[k] = v
|
| 1481 |
+
else:
|
| 1482 |
+
rest[k] = v
|
| 1483 |
+
|
| 1484 |
+
if bad_cookie:
|
| 1485 |
+
continue
|
| 1486 |
+
|
| 1487 |
+
cookie_tuples.append((name, value, standard, rest))
|
| 1488 |
+
|
| 1489 |
+
return cookie_tuples
|
| 1490 |
+
|
| 1491 |
+
def _cookie_from_cookie_tuple(self, tup, request):
|
| 1492 |
+
# standard is dict of standard cookie-attributes, rest is dict of the
|
| 1493 |
+
# rest of them
|
| 1494 |
+
name, value, standard, rest = tup
|
| 1495 |
+
|
| 1496 |
+
domain = standard.get("domain", Absent)
|
| 1497 |
+
path = standard.get("path", Absent)
|
| 1498 |
+
port = standard.get("port", Absent)
|
| 1499 |
+
expires = standard.get("expires", Absent)
|
| 1500 |
+
|
| 1501 |
+
# set the easy defaults
|
| 1502 |
+
version = standard.get("version", None)
|
| 1503 |
+
if version is not None:
|
| 1504 |
+
try:
|
| 1505 |
+
version = int(version)
|
| 1506 |
+
except ValueError:
|
| 1507 |
+
return None # invalid version, ignore cookie
|
| 1508 |
+
secure = standard.get("secure", False)
|
| 1509 |
+
# (discard is also set if expires is Absent)
|
| 1510 |
+
discard = standard.get("discard", False)
|
| 1511 |
+
comment = standard.get("comment", None)
|
| 1512 |
+
comment_url = standard.get("commenturl", None)
|
| 1513 |
+
|
| 1514 |
+
# set default path
|
| 1515 |
+
if path is not Absent and path != "":
|
| 1516 |
+
path_specified = True
|
| 1517 |
+
path = escape_path(path)
|
| 1518 |
+
else:
|
| 1519 |
+
path_specified = False
|
| 1520 |
+
path = request_path(request)
|
| 1521 |
+
i = path.rfind("/")
|
| 1522 |
+
if i != -1:
|
| 1523 |
+
if version == 0:
|
| 1524 |
+
# Netscape spec parts company from reality here
|
| 1525 |
+
path = path[:i]
|
| 1526 |
+
else:
|
| 1527 |
+
path = path[:i+1]
|
| 1528 |
+
if len(path) == 0: path = "/"
|
| 1529 |
+
|
| 1530 |
+
# set default domain
|
| 1531 |
+
domain_specified = domain is not Absent
|
| 1532 |
+
# but first we have to remember whether it starts with a dot
|
| 1533 |
+
domain_initial_dot = False
|
| 1534 |
+
if domain_specified:
|
| 1535 |
+
domain_initial_dot = bool(domain.startswith("."))
|
| 1536 |
+
if domain is Absent:
|
| 1537 |
+
req_host, erhn = eff_request_host(request)
|
| 1538 |
+
domain = erhn
|
| 1539 |
+
elif not domain.startswith("."):
|
| 1540 |
+
domain = "."+domain
|
| 1541 |
+
|
| 1542 |
+
# set default port
|
| 1543 |
+
port_specified = False
|
| 1544 |
+
if port is not Absent:
|
| 1545 |
+
if port is None:
|
| 1546 |
+
# Port attr present, but has no value: default to request port.
|
| 1547 |
+
# Cookie should then only be sent back on that port.
|
| 1548 |
+
port = request_port(request)
|
| 1549 |
+
else:
|
| 1550 |
+
port_specified = True
|
| 1551 |
+
port = re.sub(r"\s+", "", port)
|
| 1552 |
+
else:
|
| 1553 |
+
# No port attr present. Cookie can be sent back on any port.
|
| 1554 |
+
port = None
|
| 1555 |
+
|
| 1556 |
+
# set default expires and discard
|
| 1557 |
+
if expires is Absent:
|
| 1558 |
+
expires = None
|
| 1559 |
+
discard = True
|
| 1560 |
+
elif expires <= self._now:
|
| 1561 |
+
# Expiry date in past is request to delete cookie. This can't be
|
| 1562 |
+
# in DefaultCookiePolicy, because can't delete cookies there.
|
| 1563 |
+
try:
|
| 1564 |
+
self.clear(domain, path, name)
|
| 1565 |
+
except KeyError:
|
| 1566 |
+
pass
|
| 1567 |
+
_debug("Expiring cookie, domain='%s', path='%s', name='%s'",
|
| 1568 |
+
domain, path, name)
|
| 1569 |
+
return None
|
| 1570 |
+
|
| 1571 |
+
return Cookie(version,
|
| 1572 |
+
name, value,
|
| 1573 |
+
port, port_specified,
|
| 1574 |
+
domain, domain_specified, domain_initial_dot,
|
| 1575 |
+
path, path_specified,
|
| 1576 |
+
secure,
|
| 1577 |
+
expires,
|
| 1578 |
+
discard,
|
| 1579 |
+
comment,
|
| 1580 |
+
comment_url,
|
| 1581 |
+
rest)
|
| 1582 |
+
|
| 1583 |
+
def _cookies_from_attrs_set(self, attrs_set, request):
|
| 1584 |
+
cookie_tuples = self._normalized_cookie_tuples(attrs_set)
|
| 1585 |
+
|
| 1586 |
+
cookies = []
|
| 1587 |
+
for tup in cookie_tuples:
|
| 1588 |
+
cookie = self._cookie_from_cookie_tuple(tup, request)
|
| 1589 |
+
if cookie: cookies.append(cookie)
|
| 1590 |
+
return cookies
|
| 1591 |
+
|
| 1592 |
+
def _process_rfc2109_cookies(self, cookies):
|
| 1593 |
+
rfc2109_as_ns = getattr(self._policy, 'rfc2109_as_netscape', None)
|
| 1594 |
+
if rfc2109_as_ns is None:
|
| 1595 |
+
rfc2109_as_ns = not self._policy.rfc2965
|
| 1596 |
+
for cookie in cookies:
|
| 1597 |
+
if cookie.version == 1:
|
| 1598 |
+
cookie.rfc2109 = True
|
| 1599 |
+
if rfc2109_as_ns:
|
| 1600 |
+
# treat 2109 cookies as Netscape cookies rather than
|
| 1601 |
+
# as RFC2965 cookies
|
| 1602 |
+
cookie.version = 0
|
| 1603 |
+
|
| 1604 |
+
def make_cookies(self, response, request):
|
| 1605 |
+
"""Return sequence of Cookie objects extracted from response object."""
|
| 1606 |
+
# get cookie-attributes for RFC 2965 and Netscape protocols
|
| 1607 |
+
headers = response.info()
|
| 1608 |
+
rfc2965_hdrs = headers.get_all("Set-Cookie2", [])
|
| 1609 |
+
ns_hdrs = headers.get_all("Set-Cookie", [])
|
| 1610 |
+
self._policy._now = self._now = int(time.time())
|
| 1611 |
+
|
| 1612 |
+
rfc2965 = self._policy.rfc2965
|
| 1613 |
+
netscape = self._policy.netscape
|
| 1614 |
+
|
| 1615 |
+
if ((not rfc2965_hdrs and not ns_hdrs) or
|
| 1616 |
+
(not ns_hdrs and not rfc2965) or
|
| 1617 |
+
(not rfc2965_hdrs and not netscape) or
|
| 1618 |
+
(not netscape and not rfc2965)):
|
| 1619 |
+
return [] # no relevant cookie headers: quick exit
|
| 1620 |
+
|
| 1621 |
+
try:
|
| 1622 |
+
cookies = self._cookies_from_attrs_set(
|
| 1623 |
+
split_header_words(rfc2965_hdrs), request)
|
| 1624 |
+
except Exception:
|
| 1625 |
+
_warn_unhandled_exception()
|
| 1626 |
+
cookies = []
|
| 1627 |
+
|
| 1628 |
+
if ns_hdrs and netscape:
|
| 1629 |
+
try:
|
| 1630 |
+
# RFC 2109 and Netscape cookies
|
| 1631 |
+
ns_cookies = self._cookies_from_attrs_set(
|
| 1632 |
+
parse_ns_headers(ns_hdrs), request)
|
| 1633 |
+
except Exception:
|
| 1634 |
+
_warn_unhandled_exception()
|
| 1635 |
+
ns_cookies = []
|
| 1636 |
+
self._process_rfc2109_cookies(ns_cookies)
|
| 1637 |
+
|
| 1638 |
+
# Look for Netscape cookies (from Set-Cookie headers) that match
|
| 1639 |
+
# corresponding RFC 2965 cookies (from Set-Cookie2 headers).
|
| 1640 |
+
# For each match, keep the RFC 2965 cookie and ignore the Netscape
|
| 1641 |
+
# cookie (RFC 2965 section 9.1). Actually, RFC 2109 cookies are
|
| 1642 |
+
# bundled in with the Netscape cookies for this purpose, which is
|
| 1643 |
+
# reasonable behaviour.
|
| 1644 |
+
if rfc2965:
|
| 1645 |
+
lookup = {}
|
| 1646 |
+
for cookie in cookies:
|
| 1647 |
+
lookup[(cookie.domain, cookie.path, cookie.name)] = None
|
| 1648 |
+
|
| 1649 |
+
def no_matching_rfc2965(ns_cookie, lookup=lookup):
|
| 1650 |
+
key = ns_cookie.domain, ns_cookie.path, ns_cookie.name
|
| 1651 |
+
return key not in lookup
|
| 1652 |
+
ns_cookies = filter(no_matching_rfc2965, ns_cookies)
|
| 1653 |
+
|
| 1654 |
+
if ns_cookies:
|
| 1655 |
+
cookies.extend(ns_cookies)
|
| 1656 |
+
|
| 1657 |
+
return cookies
|
| 1658 |
+
|
| 1659 |
+
def set_cookie_if_ok(self, cookie, request):
|
| 1660 |
+
"""Set a cookie if policy says it's OK to do so."""
|
| 1661 |
+
self._cookies_lock.acquire()
|
| 1662 |
+
try:
|
| 1663 |
+
self._policy._now = self._now = int(time.time())
|
| 1664 |
+
|
| 1665 |
+
if self._policy.set_ok(cookie, request):
|
| 1666 |
+
self.set_cookie(cookie)
|
| 1667 |
+
|
| 1668 |
+
|
| 1669 |
+
finally:
|
| 1670 |
+
self._cookies_lock.release()
|
| 1671 |
+
|
| 1672 |
+
def set_cookie(self, cookie):
|
| 1673 |
+
"""Set a cookie, without checking whether or not it should be set."""
|
| 1674 |
+
c = self._cookies
|
| 1675 |
+
self._cookies_lock.acquire()
|
| 1676 |
+
try:
|
| 1677 |
+
if cookie.domain not in c: c[cookie.domain] = {}
|
| 1678 |
+
c2 = c[cookie.domain]
|
| 1679 |
+
if cookie.path not in c2: c2[cookie.path] = {}
|
| 1680 |
+
c3 = c2[cookie.path]
|
| 1681 |
+
c3[cookie.name] = cookie
|
| 1682 |
+
finally:
|
| 1683 |
+
self._cookies_lock.release()
|
| 1684 |
+
|
| 1685 |
+
def extract_cookies(self, response, request):
|
| 1686 |
+
"""Extract cookies from response, where allowable given the request."""
|
| 1687 |
+
_debug("extract_cookies: %s", response.info())
|
| 1688 |
+
self._cookies_lock.acquire()
|
| 1689 |
+
try:
|
| 1690 |
+
for cookie in self.make_cookies(response, request):
|
| 1691 |
+
if self._policy.set_ok(cookie, request):
|
| 1692 |
+
_debug(" setting cookie: %s", cookie)
|
| 1693 |
+
self.set_cookie(cookie)
|
| 1694 |
+
finally:
|
| 1695 |
+
self._cookies_lock.release()
|
| 1696 |
+
|
| 1697 |
+
def clear(self, domain=None, path=None, name=None):
|
| 1698 |
+
"""Clear some cookies.
|
| 1699 |
+
|
| 1700 |
+
Invoking this method without arguments will clear all cookies. If
|
| 1701 |
+
given a single argument, only cookies belonging to that domain will be
|
| 1702 |
+
removed. If given two arguments, cookies belonging to the specified
|
| 1703 |
+
path within that domain are removed. If given three arguments, then
|
| 1704 |
+
the cookie with the specified name, path and domain is removed.
|
| 1705 |
+
|
| 1706 |
+
Raises KeyError if no matching cookie exists.
|
| 1707 |
+
|
| 1708 |
+
"""
|
| 1709 |
+
if name is not None:
|
| 1710 |
+
if (domain is None) or (path is None):
|
| 1711 |
+
raise ValueError(
|
| 1712 |
+
"domain and path must be given to remove a cookie by name")
|
| 1713 |
+
del self._cookies[domain][path][name]
|
| 1714 |
+
elif path is not None:
|
| 1715 |
+
if domain is None:
|
| 1716 |
+
raise ValueError(
|
| 1717 |
+
"domain must be given to remove cookies by path")
|
| 1718 |
+
del self._cookies[domain][path]
|
| 1719 |
+
elif domain is not None:
|
| 1720 |
+
del self._cookies[domain]
|
| 1721 |
+
else:
|
| 1722 |
+
self._cookies = {}
|
| 1723 |
+
|
| 1724 |
+
def clear_session_cookies(self):
|
| 1725 |
+
"""Discard all session cookies.
|
| 1726 |
+
|
| 1727 |
+
Note that the .save() method won't save session cookies anyway, unless
|
| 1728 |
+
you ask otherwise by passing a true ignore_discard argument.
|
| 1729 |
+
|
| 1730 |
+
"""
|
| 1731 |
+
self._cookies_lock.acquire()
|
| 1732 |
+
try:
|
| 1733 |
+
for cookie in self:
|
| 1734 |
+
if cookie.discard:
|
| 1735 |
+
self.clear(cookie.domain, cookie.path, cookie.name)
|
| 1736 |
+
finally:
|
| 1737 |
+
self._cookies_lock.release()
|
| 1738 |
+
|
| 1739 |
+
def clear_expired_cookies(self):
|
| 1740 |
+
"""Discard all expired cookies.
|
| 1741 |
+
|
| 1742 |
+
You probably don't need to call this method: expired cookies are never
|
| 1743 |
+
sent back to the server (provided you're using DefaultCookiePolicy),
|
| 1744 |
+
this method is called by CookieJar itself every so often, and the
|
| 1745 |
+
.save() method won't save expired cookies anyway (unless you ask
|
| 1746 |
+
otherwise by passing a true ignore_expires argument).
|
| 1747 |
+
|
| 1748 |
+
"""
|
| 1749 |
+
self._cookies_lock.acquire()
|
| 1750 |
+
try:
|
| 1751 |
+
now = time.time()
|
| 1752 |
+
for cookie in self:
|
| 1753 |
+
if cookie.is_expired(now):
|
| 1754 |
+
self.clear(cookie.domain, cookie.path, cookie.name)
|
| 1755 |
+
finally:
|
| 1756 |
+
self._cookies_lock.release()
|
| 1757 |
+
|
| 1758 |
+
def __iter__(self):
|
| 1759 |
+
return deepvalues(self._cookies)
|
| 1760 |
+
|
| 1761 |
+
def __len__(self):
|
| 1762 |
+
"""Return number of contained cookies."""
|
| 1763 |
+
i = 0
|
| 1764 |
+
for cookie in self: i = i + 1
|
| 1765 |
+
return i
|
| 1766 |
+
|
| 1767 |
+
def __repr__(self):
|
| 1768 |
+
r = []
|
| 1769 |
+
for cookie in self: r.append(repr(cookie))
|
| 1770 |
+
return "<%s[%s]>" % (self.__class__.__name__, ", ".join(r))
|
| 1771 |
+
|
| 1772 |
+
def __str__(self):
|
| 1773 |
+
r = []
|
| 1774 |
+
for cookie in self: r.append(str(cookie))
|
| 1775 |
+
return "<%s[%s]>" % (self.__class__.__name__, ", ".join(r))
|
| 1776 |
+
|
| 1777 |
+
|
| 1778 |
+
# derives from OSError for backwards-compatibility with Python 2.4.0
|
| 1779 |
+
class LoadError(OSError): pass
|
| 1780 |
+
|
| 1781 |
+
class FileCookieJar(CookieJar):
|
| 1782 |
+
"""CookieJar that can be loaded from and saved to a file."""
|
| 1783 |
+
|
| 1784 |
+
def __init__(self, filename=None, delayload=False, policy=None):
|
| 1785 |
+
"""
|
| 1786 |
+
Cookies are NOT loaded from the named file until either the .load() or
|
| 1787 |
+
.revert() method is called.
|
| 1788 |
+
|
| 1789 |
+
"""
|
| 1790 |
+
CookieJar.__init__(self, policy)
|
| 1791 |
+
if filename is not None:
|
| 1792 |
+
filename = os.fspath(filename)
|
| 1793 |
+
self.filename = filename
|
| 1794 |
+
self.delayload = bool(delayload)
|
| 1795 |
+
|
| 1796 |
+
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
|
| 1797 |
+
"""Save cookies to a file."""
|
| 1798 |
+
raise NotImplementedError()
|
| 1799 |
+
|
| 1800 |
+
def load(self, filename=None, ignore_discard=False, ignore_expires=False):
|
| 1801 |
+
"""Load cookies from a file."""
|
| 1802 |
+
if filename is None:
|
| 1803 |
+
if self.filename is not None: filename = self.filename
|
| 1804 |
+
else: raise ValueError(MISSING_FILENAME_TEXT)
|
| 1805 |
+
|
| 1806 |
+
with open(filename) as f:
|
| 1807 |
+
self._really_load(f, filename, ignore_discard, ignore_expires)
|
| 1808 |
+
|
| 1809 |
+
def revert(self, filename=None,
|
| 1810 |
+
ignore_discard=False, ignore_expires=False):
|
| 1811 |
+
"""Clear all cookies and reload cookies from a saved file.
|
| 1812 |
+
|
| 1813 |
+
Raises LoadError (or OSError) if reversion is not successful; the
|
| 1814 |
+
object's state will not be altered if this happens.
|
| 1815 |
+
|
| 1816 |
+
"""
|
| 1817 |
+
if filename is None:
|
| 1818 |
+
if self.filename is not None: filename = self.filename
|
| 1819 |
+
else: raise ValueError(MISSING_FILENAME_TEXT)
|
| 1820 |
+
|
| 1821 |
+
self._cookies_lock.acquire()
|
| 1822 |
+
try:
|
| 1823 |
+
|
| 1824 |
+
old_state = copy.deepcopy(self._cookies)
|
| 1825 |
+
self._cookies = {}
|
| 1826 |
+
try:
|
| 1827 |
+
self.load(filename, ignore_discard, ignore_expires)
|
| 1828 |
+
except OSError:
|
| 1829 |
+
self._cookies = old_state
|
| 1830 |
+
raise
|
| 1831 |
+
|
| 1832 |
+
finally:
|
| 1833 |
+
self._cookies_lock.release()
|
| 1834 |
+
|
| 1835 |
+
|
| 1836 |
+
def lwp_cookie_str(cookie):
|
| 1837 |
+
"""Return string representation of Cookie in the LWP cookie file format.
|
| 1838 |
+
|
| 1839 |
+
Actually, the format is extended a bit -- see module docstring.
|
| 1840 |
+
|
| 1841 |
+
"""
|
| 1842 |
+
h = [(cookie.name, cookie.value),
|
| 1843 |
+
("path", cookie.path),
|
| 1844 |
+
("domain", cookie.domain)]
|
| 1845 |
+
if cookie.port is not None: h.append(("port", cookie.port))
|
| 1846 |
+
if cookie.path_specified: h.append(("path_spec", None))
|
| 1847 |
+
if cookie.port_specified: h.append(("port_spec", None))
|
| 1848 |
+
if cookie.domain_initial_dot: h.append(("domain_dot", None))
|
| 1849 |
+
if cookie.secure: h.append(("secure", None))
|
| 1850 |
+
if cookie.expires: h.append(("expires",
|
| 1851 |
+
time2isoz(float(cookie.expires))))
|
| 1852 |
+
if cookie.discard: h.append(("discard", None))
|
| 1853 |
+
if cookie.comment: h.append(("comment", cookie.comment))
|
| 1854 |
+
if cookie.comment_url: h.append(("commenturl", cookie.comment_url))
|
| 1855 |
+
|
| 1856 |
+
keys = sorted(cookie._rest.keys())
|
| 1857 |
+
for k in keys:
|
| 1858 |
+
h.append((k, str(cookie._rest[k])))
|
| 1859 |
+
|
| 1860 |
+
h.append(("version", str(cookie.version)))
|
| 1861 |
+
|
| 1862 |
+
return join_header_words([h])
|
| 1863 |
+
|
| 1864 |
+
class LWPCookieJar(FileCookieJar):
|
| 1865 |
+
"""
|
| 1866 |
+
The LWPCookieJar saves a sequence of "Set-Cookie3" lines.
|
| 1867 |
+
"Set-Cookie3" is the format used by the libwww-perl library, not known
|
| 1868 |
+
to be compatible with any browser, but which is easy to read and
|
| 1869 |
+
doesn't lose information about RFC 2965 cookies.
|
| 1870 |
+
|
| 1871 |
+
Additional methods
|
| 1872 |
+
|
| 1873 |
+
as_lwp_str(ignore_discard=True, ignore_expired=True)
|
| 1874 |
+
|
| 1875 |
+
"""
|
| 1876 |
+
|
| 1877 |
+
def as_lwp_str(self, ignore_discard=True, ignore_expires=True):
|
| 1878 |
+
"""Return cookies as a string of "\\n"-separated "Set-Cookie3" headers.
|
| 1879 |
+
|
| 1880 |
+
ignore_discard and ignore_expires: see docstring for FileCookieJar.save
|
| 1881 |
+
|
| 1882 |
+
"""
|
| 1883 |
+
now = time.time()
|
| 1884 |
+
r = []
|
| 1885 |
+
for cookie in self:
|
| 1886 |
+
if not ignore_discard and cookie.discard:
|
| 1887 |
+
continue
|
| 1888 |
+
if not ignore_expires and cookie.is_expired(now):
|
| 1889 |
+
continue
|
| 1890 |
+
r.append("Set-Cookie3: %s" % lwp_cookie_str(cookie))
|
| 1891 |
+
return "\n".join(r+[""])
|
| 1892 |
+
|
| 1893 |
+
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
|
| 1894 |
+
if filename is None:
|
| 1895 |
+
if self.filename is not None: filename = self.filename
|
| 1896 |
+
else: raise ValueError(MISSING_FILENAME_TEXT)
|
| 1897 |
+
|
| 1898 |
+
with open(filename, "w") as f:
|
| 1899 |
+
# There really isn't an LWP Cookies 2.0 format, but this indicates
|
| 1900 |
+
# that there is extra information in here (domain_dot and
|
| 1901 |
+
# port_spec) while still being compatible with libwww-perl, I hope.
|
| 1902 |
+
f.write("#LWP-Cookies-2.0\n")
|
| 1903 |
+
f.write(self.as_lwp_str(ignore_discard, ignore_expires))
|
| 1904 |
+
|
| 1905 |
+
def _really_load(self, f, filename, ignore_discard, ignore_expires):
|
| 1906 |
+
magic = f.readline()
|
| 1907 |
+
if not self.magic_re.search(magic):
|
| 1908 |
+
msg = ("%r does not look like a Set-Cookie3 (LWP) format "
|
| 1909 |
+
"file" % filename)
|
| 1910 |
+
raise LoadError(msg)
|
| 1911 |
+
|
| 1912 |
+
now = time.time()
|
| 1913 |
+
|
| 1914 |
+
header = "Set-Cookie3:"
|
| 1915 |
+
boolean_attrs = ("port_spec", "path_spec", "domain_dot",
|
| 1916 |
+
"secure", "discard")
|
| 1917 |
+
value_attrs = ("version",
|
| 1918 |
+
"port", "path", "domain",
|
| 1919 |
+
"expires",
|
| 1920 |
+
"comment", "commenturl")
|
| 1921 |
+
|
| 1922 |
+
try:
|
| 1923 |
+
while 1:
|
| 1924 |
+
line = f.readline()
|
| 1925 |
+
if line == "": break
|
| 1926 |
+
if not line.startswith(header):
|
| 1927 |
+
continue
|
| 1928 |
+
line = line[len(header):].strip()
|
| 1929 |
+
|
| 1930 |
+
for data in split_header_words([line]):
|
| 1931 |
+
name, value = data[0]
|
| 1932 |
+
standard = {}
|
| 1933 |
+
rest = {}
|
| 1934 |
+
for k in boolean_attrs:
|
| 1935 |
+
standard[k] = False
|
| 1936 |
+
for k, v in data[1:]:
|
| 1937 |
+
if k is not None:
|
| 1938 |
+
lc = k.lower()
|
| 1939 |
+
else:
|
| 1940 |
+
lc = None
|
| 1941 |
+
# don't lose case distinction for unknown fields
|
| 1942 |
+
if (lc in value_attrs) or (lc in boolean_attrs):
|
| 1943 |
+
k = lc
|
| 1944 |
+
if k in boolean_attrs:
|
| 1945 |
+
if v is None: v = True
|
| 1946 |
+
standard[k] = v
|
| 1947 |
+
elif k in value_attrs:
|
| 1948 |
+
standard[k] = v
|
| 1949 |
+
else:
|
| 1950 |
+
rest[k] = v
|
| 1951 |
+
|
| 1952 |
+
h = standard.get
|
| 1953 |
+
expires = h("expires")
|
| 1954 |
+
discard = h("discard")
|
| 1955 |
+
if expires is not None:
|
| 1956 |
+
expires = iso2time(expires)
|
| 1957 |
+
if expires is None:
|
| 1958 |
+
discard = True
|
| 1959 |
+
domain = h("domain")
|
| 1960 |
+
domain_specified = domain.startswith(".")
|
| 1961 |
+
c = Cookie(h("version"), name, value,
|
| 1962 |
+
h("port"), h("port_spec"),
|
| 1963 |
+
domain, domain_specified, h("domain_dot"),
|
| 1964 |
+
h("path"), h("path_spec"),
|
| 1965 |
+
h("secure"),
|
| 1966 |
+
expires,
|
| 1967 |
+
discard,
|
| 1968 |
+
h("comment"),
|
| 1969 |
+
h("commenturl"),
|
| 1970 |
+
rest)
|
| 1971 |
+
if not ignore_discard and c.discard:
|
| 1972 |
+
continue
|
| 1973 |
+
if not ignore_expires and c.is_expired(now):
|
| 1974 |
+
continue
|
| 1975 |
+
self.set_cookie(c)
|
| 1976 |
+
except OSError:
|
| 1977 |
+
raise
|
| 1978 |
+
except Exception:
|
| 1979 |
+
_warn_unhandled_exception()
|
| 1980 |
+
raise LoadError("invalid Set-Cookie3 format file %r: %r" %
|
| 1981 |
+
(filename, line))
|
| 1982 |
+
|
| 1983 |
+
|
| 1984 |
+
class MozillaCookieJar(FileCookieJar):
|
| 1985 |
+
"""
|
| 1986 |
+
|
| 1987 |
+
WARNING: you may want to backup your browser's cookies file if you use
|
| 1988 |
+
this class to save cookies. I *think* it works, but there have been
|
| 1989 |
+
bugs in the past!
|
| 1990 |
+
|
| 1991 |
+
This class differs from CookieJar only in the format it uses to save and
|
| 1992 |
+
load cookies to and from a file. This class uses the Mozilla/Netscape
|
| 1993 |
+
`cookies.txt' format. curl and lynx use this file format, too.
|
| 1994 |
+
|
| 1995 |
+
Don't expect cookies saved while the browser is running to be noticed by
|
| 1996 |
+
the browser (in fact, Mozilla on unix will overwrite your saved cookies if
|
| 1997 |
+
you change them on disk while it's running; on Windows, you probably can't
|
| 1998 |
+
save at all while the browser is running).
|
| 1999 |
+
|
| 2000 |
+
Note that the Mozilla/Netscape format will downgrade RFC2965 cookies to
|
| 2001 |
+
Netscape cookies on saving.
|
| 2002 |
+
|
| 2003 |
+
In particular, the cookie version and port number information is lost,
|
| 2004 |
+
together with information about whether or not Path, Port and Discard were
|
| 2005 |
+
specified by the Set-Cookie2 (or Set-Cookie) header, and whether or not the
|
| 2006 |
+
domain as set in the HTTP header started with a dot (yes, I'm aware some
|
| 2007 |
+
domains in Netscape files start with a dot and some don't -- trust me, you
|
| 2008 |
+
really don't want to know any more about this).
|
| 2009 |
+
|
| 2010 |
+
Note that though Mozilla and Netscape use the same format, they use
|
| 2011 |
+
slightly different headers. The class saves cookies using the Netscape
|
| 2012 |
+
header by default (Mozilla can cope with that).
|
| 2013 |
+
|
| 2014 |
+
"""
|
| 2015 |
+
|
| 2016 |
+
def _really_load(self, f, filename, ignore_discard, ignore_expires):
|
| 2017 |
+
now = time.time()
|
| 2018 |
+
|
| 2019 |
+
if not NETSCAPE_MAGIC_RGX.match(f.readline()):
|
| 2020 |
+
raise LoadError(
|
| 2021 |
+
"%r does not look like a Netscape format cookies file" %
|
| 2022 |
+
filename)
|
| 2023 |
+
|
| 2024 |
+
try:
|
| 2025 |
+
while 1:
|
| 2026 |
+
line = f.readline()
|
| 2027 |
+
rest = {}
|
| 2028 |
+
|
| 2029 |
+
if line == "": break
|
| 2030 |
+
|
| 2031 |
+
# httponly is a cookie flag as defined in rfc6265
|
| 2032 |
+
# when encoded in a netscape cookie file,
|
| 2033 |
+
# the line is prepended with "#HttpOnly_"
|
| 2034 |
+
if line.startswith(HTTPONLY_PREFIX):
|
| 2035 |
+
rest[HTTPONLY_ATTR] = ""
|
| 2036 |
+
line = line[len(HTTPONLY_PREFIX):]
|
| 2037 |
+
|
| 2038 |
+
# last field may be absent, so keep any trailing tab
|
| 2039 |
+
if line.endswith("\n"): line = line[:-1]
|
| 2040 |
+
|
| 2041 |
+
# skip comments and blank lines XXX what is $ for?
|
| 2042 |
+
if (line.strip().startswith(("#", "$")) or
|
| 2043 |
+
line.strip() == ""):
|
| 2044 |
+
continue
|
| 2045 |
+
|
| 2046 |
+
domain, domain_specified, path, secure, expires, name, value = \
|
| 2047 |
+
line.split("\t")
|
| 2048 |
+
secure = (secure == "TRUE")
|
| 2049 |
+
domain_specified = (domain_specified == "TRUE")
|
| 2050 |
+
if name == "":
|
| 2051 |
+
# cookies.txt regards 'Set-Cookie: foo' as a cookie
|
| 2052 |
+
# with no name, whereas http.cookiejar regards it as a
|
| 2053 |
+
# cookie with no value.
|
| 2054 |
+
name = value
|
| 2055 |
+
value = None
|
| 2056 |
+
|
| 2057 |
+
initial_dot = domain.startswith(".")
|
| 2058 |
+
assert domain_specified == initial_dot
|
| 2059 |
+
|
| 2060 |
+
discard = False
|
| 2061 |
+
if expires == "":
|
| 2062 |
+
expires = None
|
| 2063 |
+
discard = True
|
| 2064 |
+
|
| 2065 |
+
# assume path_specified is false
|
| 2066 |
+
c = Cookie(0, name, value,
|
| 2067 |
+
None, False,
|
| 2068 |
+
domain, domain_specified, initial_dot,
|
| 2069 |
+
path, False,
|
| 2070 |
+
secure,
|
| 2071 |
+
expires,
|
| 2072 |
+
discard,
|
| 2073 |
+
None,
|
| 2074 |
+
None,
|
| 2075 |
+
rest)
|
| 2076 |
+
if not ignore_discard and c.discard:
|
| 2077 |
+
continue
|
| 2078 |
+
if not ignore_expires and c.is_expired(now):
|
| 2079 |
+
continue
|
| 2080 |
+
self.set_cookie(c)
|
| 2081 |
+
|
| 2082 |
+
except OSError:
|
| 2083 |
+
raise
|
| 2084 |
+
except Exception:
|
| 2085 |
+
_warn_unhandled_exception()
|
| 2086 |
+
raise LoadError("invalid Netscape format cookies file %r: %r" %
|
| 2087 |
+
(filename, line))
|
| 2088 |
+
|
| 2089 |
+
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
|
| 2090 |
+
if filename is None:
|
| 2091 |
+
if self.filename is not None: filename = self.filename
|
| 2092 |
+
else: raise ValueError(MISSING_FILENAME_TEXT)
|
| 2093 |
+
|
| 2094 |
+
with open(filename, "w") as f:
|
| 2095 |
+
f.write(NETSCAPE_HEADER_TEXT)
|
| 2096 |
+
now = time.time()
|
| 2097 |
+
for cookie in self:
|
| 2098 |
+
domain = cookie.domain
|
| 2099 |
+
if not ignore_discard and cookie.discard:
|
| 2100 |
+
continue
|
| 2101 |
+
if not ignore_expires and cookie.is_expired(now):
|
| 2102 |
+
continue
|
| 2103 |
+
if cookie.secure: secure = "TRUE"
|
| 2104 |
+
else: secure = "FALSE"
|
| 2105 |
+
if domain.startswith("."): initial_dot = "TRUE"
|
| 2106 |
+
else: initial_dot = "FALSE"
|
| 2107 |
+
if cookie.expires is not None:
|
| 2108 |
+
expires = str(cookie.expires)
|
| 2109 |
+
else:
|
| 2110 |
+
expires = ""
|
| 2111 |
+
if cookie.value is None:
|
| 2112 |
+
# cookies.txt regards 'Set-Cookie: foo' as a cookie
|
| 2113 |
+
# with no name, whereas http.cookiejar regards it as a
|
| 2114 |
+
# cookie with no value.
|
| 2115 |
+
name = ""
|
| 2116 |
+
value = cookie.name
|
| 2117 |
+
else:
|
| 2118 |
+
name = cookie.name
|
| 2119 |
+
value = cookie.value
|
| 2120 |
+
if cookie.has_nonstandard_attr(HTTPONLY_ATTR):
|
| 2121 |
+
domain = HTTPONLY_PREFIX + domain
|
| 2122 |
+
f.write(
|
| 2123 |
+
"\t".join([domain, initial_dot, cookie.path,
|
| 2124 |
+
secure, expires, name, value])+
|
| 2125 |
+
"\n")
|
evalkit_llava/lib/python3.10/http/cookies.py
ADDED
|
@@ -0,0 +1,594 @@
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
####
|
| 2 |
+
# Copyright 2000 by Timothy O'Malley <[email protected]>
|
| 3 |
+
#
|
| 4 |
+
# All Rights Reserved
|
| 5 |
+
#
|
| 6 |
+
# Permission to use, copy, modify, and distribute this software
|
| 7 |
+
# and its documentation for any purpose and without fee is hereby
|
| 8 |
+
# granted, provided that the above copyright notice appear in all
|
| 9 |
+
# copies and that both that copyright notice and this permission
|
| 10 |
+
# notice appear in supporting documentation, and that the name of
|
| 11 |
+
# Timothy O'Malley not be used in advertising or publicity
|
| 12 |
+
# pertaining to distribution of the software without specific, written
|
| 13 |
+
# prior permission.
|
| 14 |
+
#
|
| 15 |
+
# Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
|
| 16 |
+
# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
| 17 |
+
# AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR
|
| 18 |
+
# ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
| 19 |
+
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
| 20 |
+
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
| 21 |
+
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
| 22 |
+
# PERFORMANCE OF THIS SOFTWARE.
|
| 23 |
+
#
|
| 24 |
+
####
|
| 25 |
+
#
|
| 26 |
+
# Id: Cookie.py,v 2.29 2000/08/23 05:28:49 timo Exp
|
| 27 |
+
# by Timothy O'Malley <[email protected]>
|
| 28 |
+
#
|
| 29 |
+
# Cookie.py is a Python module for the handling of HTTP
|
| 30 |
+
# cookies as a Python dictionary. See RFC 2109 for more
|
| 31 |
+
# information on cookies.
|
| 32 |
+
#
|
| 33 |
+
# The original idea to treat Cookies as a dictionary came from
|
| 34 |
+
# Dave Mitchell ([email protected]) in 1995, when he released the
|
| 35 |
+
# first version of nscookie.py.
|
| 36 |
+
#
|
| 37 |
+
####
|
| 38 |
+
|
| 39 |
+
r"""
|
| 40 |
+
Here's a sample session to show how to use this module.
|
| 41 |
+
At the moment, this is the only documentation.
|
| 42 |
+
|
| 43 |
+
The Basics
|
| 44 |
+
----------
|
| 45 |
+
|
| 46 |
+
Importing is easy...
|
| 47 |
+
|
| 48 |
+
>>> from http import cookies
|
| 49 |
+
|
| 50 |
+
Most of the time you start by creating a cookie.
|
| 51 |
+
|
| 52 |
+
>>> C = cookies.SimpleCookie()
|
| 53 |
+
|
| 54 |
+
Once you've created your Cookie, you can add values just as if it were
|
| 55 |
+
a dictionary.
|
| 56 |
+
|
| 57 |
+
>>> C = cookies.SimpleCookie()
|
| 58 |
+
>>> C["fig"] = "newton"
|
| 59 |
+
>>> C["sugar"] = "wafer"
|
| 60 |
+
>>> C.output()
|
| 61 |
+
'Set-Cookie: fig=newton\r\nSet-Cookie: sugar=wafer'
|
| 62 |
+
|
| 63 |
+
Notice that the printable representation of a Cookie is the
|
| 64 |
+
appropriate format for a Set-Cookie: header. This is the
|
| 65 |
+
default behavior. You can change the header and printed
|
| 66 |
+
attributes by using the .output() function
|
| 67 |
+
|
| 68 |
+
>>> C = cookies.SimpleCookie()
|
| 69 |
+
>>> C["rocky"] = "road"
|
| 70 |
+
>>> C["rocky"]["path"] = "/cookie"
|
| 71 |
+
>>> print(C.output(header="Cookie:"))
|
| 72 |
+
Cookie: rocky=road; Path=/cookie
|
| 73 |
+
>>> print(C.output(attrs=[], header="Cookie:"))
|
| 74 |
+
Cookie: rocky=road
|
| 75 |
+
|
| 76 |
+
The load() method of a Cookie extracts cookies from a string. In a
|
| 77 |
+
CGI script, you would use this method to extract the cookies from the
|
| 78 |
+
HTTP_COOKIE environment variable.
|
| 79 |
+
|
| 80 |
+
>>> C = cookies.SimpleCookie()
|
| 81 |
+
>>> C.load("chips=ahoy; vienna=finger")
|
| 82 |
+
>>> C.output()
|
| 83 |
+
'Set-Cookie: chips=ahoy\r\nSet-Cookie: vienna=finger'
|
| 84 |
+
|
| 85 |
+
The load() method is darn-tootin smart about identifying cookies
|
| 86 |
+
within a string. Escaped quotation marks, nested semicolons, and other
|
| 87 |
+
such trickeries do not confuse it.
|
| 88 |
+
|
| 89 |
+
>>> C = cookies.SimpleCookie()
|
| 90 |
+
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
|
| 91 |
+
>>> print(C)
|
| 92 |
+
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
|
| 93 |
+
|
| 94 |
+
Each element of the Cookie also supports all of the RFC 2109
|
| 95 |
+
Cookie attributes. Here's an example which sets the Path
|
| 96 |
+
attribute.
|
| 97 |
+
|
| 98 |
+
>>> C = cookies.SimpleCookie()
|
| 99 |
+
>>> C["oreo"] = "doublestuff"
|
| 100 |
+
>>> C["oreo"]["path"] = "/"
|
| 101 |
+
>>> print(C)
|
| 102 |
+
Set-Cookie: oreo=doublestuff; Path=/
|
| 103 |
+
|
| 104 |
+
Each dictionary element has a 'value' attribute, which gives you
|
| 105 |
+
back the value associated with the key.
|
| 106 |
+
|
| 107 |
+
>>> C = cookies.SimpleCookie()
|
| 108 |
+
>>> C["twix"] = "none for you"
|
| 109 |
+
>>> C["twix"].value
|
| 110 |
+
'none for you'
|
| 111 |
+
|
| 112 |
+
The SimpleCookie expects that all values should be standard strings.
|
| 113 |
+
Just to be sure, SimpleCookie invokes the str() builtin to convert
|
| 114 |
+
the value to a string, when the values are set dictionary-style.
|
| 115 |
+
|
| 116 |
+
>>> C = cookies.SimpleCookie()
|
| 117 |
+
>>> C["number"] = 7
|
| 118 |
+
>>> C["string"] = "seven"
|
| 119 |
+
>>> C["number"].value
|
| 120 |
+
'7'
|
| 121 |
+
>>> C["string"].value
|
| 122 |
+
'seven'
|
| 123 |
+
>>> C.output()
|
| 124 |
+
'Set-Cookie: number=7\r\nSet-Cookie: string=seven'
|
| 125 |
+
|
| 126 |
+
Finis.
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
#
|
| 130 |
+
# Import our required modules
|
| 131 |
+
#
|
| 132 |
+
import re
|
| 133 |
+
import string
|
| 134 |
+
import types
|
| 135 |
+
|
| 136 |
+
__all__ = ["CookieError", "BaseCookie", "SimpleCookie"]
|
| 137 |
+
|
| 138 |
+
_nulljoin = ''.join
|
| 139 |
+
_semispacejoin = '; '.join
|
| 140 |
+
_spacejoin = ' '.join
|
| 141 |
+
|
| 142 |
+
#
|
| 143 |
+
# Define an exception visible to External modules
|
| 144 |
+
#
|
| 145 |
+
class CookieError(Exception):
|
| 146 |
+
pass
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# These quoting routines conform to the RFC2109 specification, which in
|
| 150 |
+
# turn references the character definitions from RFC2068. They provide
|
| 151 |
+
# a two-way quoting algorithm. Any non-text character is translated
|
| 152 |
+
# into a 4 character sequence: a forward-slash followed by the
|
| 153 |
+
# three-digit octal equivalent of the character. Any '\' or '"' is
|
| 154 |
+
# quoted with a preceding '\' slash.
|
| 155 |
+
# Because of the way browsers really handle cookies (as opposed to what
|
| 156 |
+
# the RFC says) we also encode "," and ";".
|
| 157 |
+
#
|
| 158 |
+
# These are taken from RFC2068 and RFC2109.
|
| 159 |
+
# _LegalChars is the list of chars which don't require "'s
|
| 160 |
+
# _Translator hash-table for fast quoting
|
| 161 |
+
#
|
| 162 |
+
_LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~:"
|
| 163 |
+
_UnescapedChars = _LegalChars + ' ()/<=>?@[]{}'
|
| 164 |
+
|
| 165 |
+
_Translator = {n: '\\%03o' % n
|
| 166 |
+
for n in set(range(256)) - set(map(ord, _UnescapedChars))}
|
| 167 |
+
_Translator.update({
|
| 168 |
+
ord('"'): '\\"',
|
| 169 |
+
ord('\\'): '\\\\',
|
| 170 |
+
})
|
| 171 |
+
|
| 172 |
+
_is_legal_key = re.compile('[%s]+' % re.escape(_LegalChars)).fullmatch
|
| 173 |
+
|
| 174 |
+
def _quote(str):
|
| 175 |
+
r"""Quote a string for use in a cookie header.
|
| 176 |
+
|
| 177 |
+
If the string does not need to be double-quoted, then just return the
|
| 178 |
+
string. Otherwise, surround the string in doublequotes and quote
|
| 179 |
+
(with a \) special characters.
|
| 180 |
+
"""
|
| 181 |
+
if str is None or _is_legal_key(str):
|
| 182 |
+
return str
|
| 183 |
+
else:
|
| 184 |
+
return '"' + str.translate(_Translator) + '"'
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
_unquote_sub = re.compile(r'\\(?:([0-3][0-7][0-7])|(.))').sub
|
| 188 |
+
|
| 189 |
+
def _unquote_replace(m):
|
| 190 |
+
if m[1]:
|
| 191 |
+
return chr(int(m[1], 8))
|
| 192 |
+
else:
|
| 193 |
+
return m[2]
|
| 194 |
+
|
| 195 |
+
def _unquote(str):
|
| 196 |
+
# If there aren't any doublequotes,
|
| 197 |
+
# then there can't be any special characters. See RFC 2109.
|
| 198 |
+
if str is None or len(str) < 2:
|
| 199 |
+
return str
|
| 200 |
+
if str[0] != '"' or str[-1] != '"':
|
| 201 |
+
return str
|
| 202 |
+
|
| 203 |
+
# We have to assume that we must decode this string.
|
| 204 |
+
# Down to work.
|
| 205 |
+
|
| 206 |
+
# Remove the "s
|
| 207 |
+
str = str[1:-1]
|
| 208 |
+
|
| 209 |
+
# Check for special sequences. Examples:
|
| 210 |
+
# \012 --> \n
|
| 211 |
+
# \" --> "
|
| 212 |
+
#
|
| 213 |
+
return _unquote_sub(_unquote_replace, str)
|
| 214 |
+
|
| 215 |
+
# The _getdate() routine is used to set the expiration time in the cookie's HTTP
|
| 216 |
+
# header. By default, _getdate() returns the current time in the appropriate
|
| 217 |
+
# "expires" format for a Set-Cookie header. The one optional argument is an
|
| 218 |
+
# offset from now, in seconds. For example, an offset of -3600 means "one hour
|
| 219 |
+
# ago". The offset may be a floating point number.
|
| 220 |
+
#
|
| 221 |
+
|
| 222 |
+
_weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
|
| 223 |
+
|
| 224 |
+
_monthname = [None,
|
| 225 |
+
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
| 226 |
+
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
|
| 227 |
+
|
| 228 |
+
def _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname):
|
| 229 |
+
from time import gmtime, time
|
| 230 |
+
now = time()
|
| 231 |
+
year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future)
|
| 232 |
+
return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % \
|
| 233 |
+
(weekdayname[wd], day, monthname[month], year, hh, mm, ss)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class Morsel(dict):
|
| 237 |
+
"""A class to hold ONE (key, value) pair.
|
| 238 |
+
|
| 239 |
+
In a cookie, each such pair may have several attributes, so this class is
|
| 240 |
+
used to keep the attributes associated with the appropriate key,value pair.
|
| 241 |
+
This class also includes a coded_value attribute, which is used to hold
|
| 242 |
+
the network representation of the value.
|
| 243 |
+
"""
|
| 244 |
+
# RFC 2109 lists these attributes as reserved:
|
| 245 |
+
# path comment domain
|
| 246 |
+
# max-age secure version
|
| 247 |
+
#
|
| 248 |
+
# For historical reasons, these attributes are also reserved:
|
| 249 |
+
# expires
|
| 250 |
+
#
|
| 251 |
+
# This is an extension from Microsoft:
|
| 252 |
+
# httponly
|
| 253 |
+
#
|
| 254 |
+
# This dictionary provides a mapping from the lowercase
|
| 255 |
+
# variant on the left to the appropriate traditional
|
| 256 |
+
# formatting on the right.
|
| 257 |
+
_reserved = {
|
| 258 |
+
"expires" : "expires",
|
| 259 |
+
"path" : "Path",
|
| 260 |
+
"comment" : "Comment",
|
| 261 |
+
"domain" : "Domain",
|
| 262 |
+
"max-age" : "Max-Age",
|
| 263 |
+
"secure" : "Secure",
|
| 264 |
+
"httponly" : "HttpOnly",
|
| 265 |
+
"version" : "Version",
|
| 266 |
+
"samesite" : "SameSite",
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
_flags = {'secure', 'httponly'}
|
| 270 |
+
|
| 271 |
+
def __init__(self):
|
| 272 |
+
# Set defaults
|
| 273 |
+
self._key = self._value = self._coded_value = None
|
| 274 |
+
|
| 275 |
+
# Set default attributes
|
| 276 |
+
for key in self._reserved:
|
| 277 |
+
dict.__setitem__(self, key, "")
|
| 278 |
+
|
| 279 |
+
@property
|
| 280 |
+
def key(self):
|
| 281 |
+
return self._key
|
| 282 |
+
|
| 283 |
+
@property
|
| 284 |
+
def value(self):
|
| 285 |
+
return self._value
|
| 286 |
+
|
| 287 |
+
@property
|
| 288 |
+
def coded_value(self):
|
| 289 |
+
return self._coded_value
|
| 290 |
+
|
| 291 |
+
def __setitem__(self, K, V):
|
| 292 |
+
K = K.lower()
|
| 293 |
+
if not K in self._reserved:
|
| 294 |
+
raise CookieError("Invalid attribute %r" % (K,))
|
| 295 |
+
dict.__setitem__(self, K, V)
|
| 296 |
+
|
| 297 |
+
def setdefault(self, key, val=None):
|
| 298 |
+
key = key.lower()
|
| 299 |
+
if key not in self._reserved:
|
| 300 |
+
raise CookieError("Invalid attribute %r" % (key,))
|
| 301 |
+
return dict.setdefault(self, key, val)
|
| 302 |
+
|
| 303 |
+
def __eq__(self, morsel):
|
| 304 |
+
if not isinstance(morsel, Morsel):
|
| 305 |
+
return NotImplemented
|
| 306 |
+
return (dict.__eq__(self, morsel) and
|
| 307 |
+
self._value == morsel._value and
|
| 308 |
+
self._key == morsel._key and
|
| 309 |
+
self._coded_value == morsel._coded_value)
|
| 310 |
+
|
| 311 |
+
__ne__ = object.__ne__
|
| 312 |
+
|
| 313 |
+
def copy(self):
|
| 314 |
+
morsel = Morsel()
|
| 315 |
+
dict.update(morsel, self)
|
| 316 |
+
morsel.__dict__.update(self.__dict__)
|
| 317 |
+
return morsel
|
| 318 |
+
|
| 319 |
+
def update(self, values):
|
| 320 |
+
data = {}
|
| 321 |
+
for key, val in dict(values).items():
|
| 322 |
+
key = key.lower()
|
| 323 |
+
if key not in self._reserved:
|
| 324 |
+
raise CookieError("Invalid attribute %r" % (key,))
|
| 325 |
+
data[key] = val
|
| 326 |
+
dict.update(self, data)
|
| 327 |
+
|
| 328 |
+
def isReservedKey(self, K):
|
| 329 |
+
return K.lower() in self._reserved
|
| 330 |
+
|
| 331 |
+
def set(self, key, val, coded_val):
|
| 332 |
+
if key.lower() in self._reserved:
|
| 333 |
+
raise CookieError('Attempt to set a reserved key %r' % (key,))
|
| 334 |
+
if not _is_legal_key(key):
|
| 335 |
+
raise CookieError('Illegal key %r' % (key,))
|
| 336 |
+
|
| 337 |
+
# It's a good key, so save it.
|
| 338 |
+
self._key = key
|
| 339 |
+
self._value = val
|
| 340 |
+
self._coded_value = coded_val
|
| 341 |
+
|
| 342 |
+
def __getstate__(self):
|
| 343 |
+
return {
|
| 344 |
+
'key': self._key,
|
| 345 |
+
'value': self._value,
|
| 346 |
+
'coded_value': self._coded_value,
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
def __setstate__(self, state):
|
| 350 |
+
self._key = state['key']
|
| 351 |
+
self._value = state['value']
|
| 352 |
+
self._coded_value = state['coded_value']
|
| 353 |
+
|
| 354 |
+
def output(self, attrs=None, header="Set-Cookie:"):
|
| 355 |
+
return "%s %s" % (header, self.OutputString(attrs))
|
| 356 |
+
|
| 357 |
+
__str__ = output
|
| 358 |
+
|
| 359 |
+
def __repr__(self):
|
| 360 |
+
return '<%s: %s>' % (self.__class__.__name__, self.OutputString())
|
| 361 |
+
|
| 362 |
+
def js_output(self, attrs=None):
|
| 363 |
+
# Print javascript
|
| 364 |
+
return """
|
| 365 |
+
<script type="text/javascript">
|
| 366 |
+
<!-- begin hiding
|
| 367 |
+
document.cookie = \"%s\";
|
| 368 |
+
// end hiding -->
|
| 369 |
+
</script>
|
| 370 |
+
""" % (self.OutputString(attrs).replace('"', r'\"'))
|
| 371 |
+
|
| 372 |
+
def OutputString(self, attrs=None):
|
| 373 |
+
# Build up our result
|
| 374 |
+
#
|
| 375 |
+
result = []
|
| 376 |
+
append = result.append
|
| 377 |
+
|
| 378 |
+
# First, the key=value pair
|
| 379 |
+
append("%s=%s" % (self.key, self.coded_value))
|
| 380 |
+
|
| 381 |
+
# Now add any defined attributes
|
| 382 |
+
if attrs is None:
|
| 383 |
+
attrs = self._reserved
|
| 384 |
+
items = sorted(self.items())
|
| 385 |
+
for key, value in items:
|
| 386 |
+
if value == "":
|
| 387 |
+
continue
|
| 388 |
+
if key not in attrs:
|
| 389 |
+
continue
|
| 390 |
+
if key == "expires" and isinstance(value, int):
|
| 391 |
+
append("%s=%s" % (self._reserved[key], _getdate(value)))
|
| 392 |
+
elif key == "max-age" and isinstance(value, int):
|
| 393 |
+
append("%s=%d" % (self._reserved[key], value))
|
| 394 |
+
elif key == "comment" and isinstance(value, str):
|
| 395 |
+
append("%s=%s" % (self._reserved[key], _quote(value)))
|
| 396 |
+
elif key in self._flags:
|
| 397 |
+
if value:
|
| 398 |
+
append(str(self._reserved[key]))
|
| 399 |
+
else:
|
| 400 |
+
append("%s=%s" % (self._reserved[key], value))
|
| 401 |
+
|
| 402 |
+
# Return the result
|
| 403 |
+
return _semispacejoin(result)
|
| 404 |
+
|
| 405 |
+
__class_getitem__ = classmethod(types.GenericAlias)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
#
|
| 409 |
+
# Pattern for finding cookie
|
| 410 |
+
#
|
| 411 |
+
# This used to be strict parsing based on the RFC2109 and RFC2068
|
| 412 |
+
# specifications. I have since discovered that MSIE 3.0x doesn't
|
| 413 |
+
# follow the character rules outlined in those specs. As a
|
| 414 |
+
# result, the parsing rules here are less strict.
|
| 415 |
+
#
|
| 416 |
+
|
| 417 |
+
_LegalKeyChars = r"\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\="
|
| 418 |
+
_LegalValueChars = _LegalKeyChars + r'\[\]'
|
| 419 |
+
_CookiePattern = re.compile(r"""
|
| 420 |
+
\s* # Optional whitespace at start of cookie
|
| 421 |
+
(?P<key> # Start of group 'key'
|
| 422 |
+
[""" + _LegalKeyChars + r"""]+? # Any word of at least one letter
|
| 423 |
+
) # End of group 'key'
|
| 424 |
+
( # Optional group: there may not be a value.
|
| 425 |
+
\s*=\s* # Equal Sign
|
| 426 |
+
(?P<val> # Start of group 'val'
|
| 427 |
+
"(?:[^\\"]|\\.)*" # Any doublequoted string
|
| 428 |
+
| # or
|
| 429 |
+
\w{3},\s[\w\d\s-]{9,11}\s[\d:]{8}\sGMT # Special case for "expires" attr
|
| 430 |
+
| # or
|
| 431 |
+
[""" + _LegalValueChars + r"""]* # Any word or empty string
|
| 432 |
+
) # End of group 'val'
|
| 433 |
+
)? # End of optional value group
|
| 434 |
+
\s* # Any number of spaces.
|
| 435 |
+
(\s+|;|$) # Ending either at space, semicolon, or EOS.
|
| 436 |
+
""", re.ASCII | re.VERBOSE) # re.ASCII may be removed if safe.
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
# At long last, here is the cookie class. Using this class is almost just like
|
| 440 |
+
# using a dictionary. See this module's docstring for example usage.
|
| 441 |
+
#
|
| 442 |
+
class BaseCookie(dict):
|
| 443 |
+
"""A container class for a set of Morsels."""
|
| 444 |
+
|
| 445 |
+
def value_decode(self, val):
|
| 446 |
+
"""real_value, coded_value = value_decode(STRING)
|
| 447 |
+
Called prior to setting a cookie's value from the network
|
| 448 |
+
representation. The VALUE is the value read from HTTP
|
| 449 |
+
header.
|
| 450 |
+
Override this function to modify the behavior of cookies.
|
| 451 |
+
"""
|
| 452 |
+
return val, val
|
| 453 |
+
|
| 454 |
+
def value_encode(self, val):
|
| 455 |
+
"""real_value, coded_value = value_encode(VALUE)
|
| 456 |
+
Called prior to setting a cookie's value from the dictionary
|
| 457 |
+
representation. The VALUE is the value being assigned.
|
| 458 |
+
Override this function to modify the behavior of cookies.
|
| 459 |
+
"""
|
| 460 |
+
strval = str(val)
|
| 461 |
+
return strval, strval
|
| 462 |
+
|
| 463 |
+
def __init__(self, input=None):
|
| 464 |
+
if input:
|
| 465 |
+
self.load(input)
|
| 466 |
+
|
| 467 |
+
def __set(self, key, real_value, coded_value):
|
| 468 |
+
"""Private method for setting a cookie's value"""
|
| 469 |
+
M = self.get(key, Morsel())
|
| 470 |
+
M.set(key, real_value, coded_value)
|
| 471 |
+
dict.__setitem__(self, key, M)
|
| 472 |
+
|
| 473 |
+
def __setitem__(self, key, value):
|
| 474 |
+
"""Dictionary style assignment."""
|
| 475 |
+
if isinstance(value, Morsel):
|
| 476 |
+
# allow assignment of constructed Morsels (e.g. for pickling)
|
| 477 |
+
dict.__setitem__(self, key, value)
|
| 478 |
+
else:
|
| 479 |
+
rval, cval = self.value_encode(value)
|
| 480 |
+
self.__set(key, rval, cval)
|
| 481 |
+
|
| 482 |
+
def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):
|
| 483 |
+
"""Return a string suitable for HTTP."""
|
| 484 |
+
result = []
|
| 485 |
+
items = sorted(self.items())
|
| 486 |
+
for key, value in items:
|
| 487 |
+
result.append(value.output(attrs, header))
|
| 488 |
+
return sep.join(result)
|
| 489 |
+
|
| 490 |
+
__str__ = output
|
| 491 |
+
|
| 492 |
+
def __repr__(self):
|
| 493 |
+
l = []
|
| 494 |
+
items = sorted(self.items())
|
| 495 |
+
for key, value in items:
|
| 496 |
+
l.append('%s=%s' % (key, repr(value.value)))
|
| 497 |
+
return '<%s: %s>' % (self.__class__.__name__, _spacejoin(l))
|
| 498 |
+
|
| 499 |
+
def js_output(self, attrs=None):
|
| 500 |
+
"""Return a string suitable for JavaScript."""
|
| 501 |
+
result = []
|
| 502 |
+
items = sorted(self.items())
|
| 503 |
+
for key, value in items:
|
| 504 |
+
result.append(value.js_output(attrs))
|
| 505 |
+
return _nulljoin(result)
|
| 506 |
+
|
| 507 |
+
def load(self, rawdata):
|
| 508 |
+
"""Load cookies from a string (presumably HTTP_COOKIE) or
|
| 509 |
+
from a dictionary. Loading cookies from a dictionary 'd'
|
| 510 |
+
is equivalent to calling:
|
| 511 |
+
map(Cookie.__setitem__, d.keys(), d.values())
|
| 512 |
+
"""
|
| 513 |
+
if isinstance(rawdata, str):
|
| 514 |
+
self.__parse_string(rawdata)
|
| 515 |
+
else:
|
| 516 |
+
# self.update() wouldn't call our custom __setitem__
|
| 517 |
+
for key, value in rawdata.items():
|
| 518 |
+
self[key] = value
|
| 519 |
+
return
|
| 520 |
+
|
| 521 |
+
def __parse_string(self, str, patt=_CookiePattern):
|
| 522 |
+
i = 0 # Our starting point
|
| 523 |
+
n = len(str) # Length of string
|
| 524 |
+
parsed_items = [] # Parsed (type, key, value) triples
|
| 525 |
+
morsel_seen = False # A key=value pair was previously encountered
|
| 526 |
+
|
| 527 |
+
TYPE_ATTRIBUTE = 1
|
| 528 |
+
TYPE_KEYVALUE = 2
|
| 529 |
+
|
| 530 |
+
# We first parse the whole cookie string and reject it if it's
|
| 531 |
+
# syntactically invalid (this helps avoid some classes of injection
|
| 532 |
+
# attacks).
|
| 533 |
+
while 0 <= i < n:
|
| 534 |
+
# Start looking for a cookie
|
| 535 |
+
match = patt.match(str, i)
|
| 536 |
+
if not match:
|
| 537 |
+
# No more cookies
|
| 538 |
+
break
|
| 539 |
+
|
| 540 |
+
key, value = match.group("key"), match.group("val")
|
| 541 |
+
i = match.end(0)
|
| 542 |
+
|
| 543 |
+
if key[0] == "$":
|
| 544 |
+
if not morsel_seen:
|
| 545 |
+
# We ignore attributes which pertain to the cookie
|
| 546 |
+
# mechanism as a whole, such as "$Version".
|
| 547 |
+
# See RFC 2965. (Does anyone care?)
|
| 548 |
+
continue
|
| 549 |
+
parsed_items.append((TYPE_ATTRIBUTE, key[1:], value))
|
| 550 |
+
elif key.lower() in Morsel._reserved:
|
| 551 |
+
if not morsel_seen:
|
| 552 |
+
# Invalid cookie string
|
| 553 |
+
return
|
| 554 |
+
if value is None:
|
| 555 |
+
if key.lower() in Morsel._flags:
|
| 556 |
+
parsed_items.append((TYPE_ATTRIBUTE, key, True))
|
| 557 |
+
else:
|
| 558 |
+
# Invalid cookie string
|
| 559 |
+
return
|
| 560 |
+
else:
|
| 561 |
+
parsed_items.append((TYPE_ATTRIBUTE, key, _unquote(value)))
|
| 562 |
+
elif value is not None:
|
| 563 |
+
parsed_items.append((TYPE_KEYVALUE, key, self.value_decode(value)))
|
| 564 |
+
morsel_seen = True
|
| 565 |
+
else:
|
| 566 |
+
# Invalid cookie string
|
| 567 |
+
return
|
| 568 |
+
|
| 569 |
+
# The cookie string is valid, apply it.
|
| 570 |
+
M = None # current morsel
|
| 571 |
+
for tp, key, value in parsed_items:
|
| 572 |
+
if tp == TYPE_ATTRIBUTE:
|
| 573 |
+
assert M is not None
|
| 574 |
+
M[key] = value
|
| 575 |
+
else:
|
| 576 |
+
assert tp == TYPE_KEYVALUE
|
| 577 |
+
rval, cval = value
|
| 578 |
+
self.__set(key, rval, cval)
|
| 579 |
+
M = self[key]
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
class SimpleCookie(BaseCookie):
|
| 583 |
+
"""
|
| 584 |
+
SimpleCookie supports strings as cookie values. When setting
|
| 585 |
+
the value using the dictionary assignment notation, SimpleCookie
|
| 586 |
+
calls the builtin str() to convert the value to a string. Values
|
| 587 |
+
received from HTTP are kept as strings.
|
| 588 |
+
"""
|
| 589 |
+
def value_decode(self, val):
|
| 590 |
+
return _unquote(val), val
|
| 591 |
+
|
| 592 |
+
def value_encode(self, val):
|
| 593 |
+
strval = str(val)
|
| 594 |
+
return strval, _quote(strval)
|
evalkit_llava/lib/python3.10/http/server.py
ADDED
|
@@ -0,0 +1,1312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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see
|
| 4 |
+
SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST,
|
| 5 |
+
and CGIHTTPRequestHandler for CGI scripts.
|
| 6 |
+
|
| 7 |
+
It does, however, optionally implement HTTP/1.1 persistent connections,
|
| 8 |
+
as of version 0.3.
|
| 9 |
+
|
| 10 |
+
Notes on CGIHTTPRequestHandler
|
| 11 |
+
------------------------------
|
| 12 |
+
|
| 13 |
+
This class implements GET and POST requests to cgi-bin scripts.
|
| 14 |
+
|
| 15 |
+
If the os.fork() function is not present (e.g. on Windows),
|
| 16 |
+
subprocess.Popen() is used as a fallback, with slightly altered semantics.
|
| 17 |
+
|
| 18 |
+
In all cases, the implementation is intentionally naive -- all
|
| 19 |
+
requests are executed synchronously.
|
| 20 |
+
|
| 21 |
+
SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL
|
| 22 |
+
-- it may execute arbitrary Python code or external programs.
|
| 23 |
+
|
| 24 |
+
Note that status code 200 is sent prior to execution of a CGI script, so
|
| 25 |
+
scripts cannot send other status codes such as 302 (redirect).
|
| 26 |
+
|
| 27 |
+
XXX To do:
|
| 28 |
+
|
| 29 |
+
- log requests even later (to capture byte count)
|
| 30 |
+
- log user-agent header and other interesting goodies
|
| 31 |
+
- send error log to separate file
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# See also:
|
| 36 |
+
#
|
| 37 |
+
# HTTP Working Group T. Berners-Lee
|
| 38 |
+
# INTERNET-DRAFT R. T. Fielding
|
| 39 |
+
# <draft-ietf-http-v10-spec-00.txt> H. Frystyk Nielsen
|
| 40 |
+
# Expires September 8, 1995 March 8, 1995
|
| 41 |
+
#
|
| 42 |
+
# URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
|
| 43 |
+
#
|
| 44 |
+
# and
|
| 45 |
+
#
|
| 46 |
+
# Network Working Group R. Fielding
|
| 47 |
+
# Request for Comments: 2616 et al
|
| 48 |
+
# Obsoletes: 2068 June 1999
|
| 49 |
+
# Category: Standards Track
|
| 50 |
+
#
|
| 51 |
+
# URL: http://www.faqs.org/rfcs/rfc2616.html
|
| 52 |
+
|
| 53 |
+
# Log files
|
| 54 |
+
# ---------
|
| 55 |
+
#
|
| 56 |
+
# Here's a quote from the NCSA httpd docs about log file format.
|
| 57 |
+
#
|
| 58 |
+
# | The logfile format is as follows. Each line consists of:
|
| 59 |
+
# |
|
| 60 |
+
# | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb
|
| 61 |
+
# |
|
| 62 |
+
# | host: Either the DNS name or the IP number of the remote client
|
| 63 |
+
# | rfc931: Any information returned by identd for this person,
|
| 64 |
+
# | - otherwise.
|
| 65 |
+
# | authuser: If user sent a userid for authentication, the user name,
|
| 66 |
+
# | - otherwise.
|
| 67 |
+
# | DD: Day
|
| 68 |
+
# | Mon: Month (calendar name)
|
| 69 |
+
# | YYYY: Year
|
| 70 |
+
# | hh: hour (24-hour format, the machine's timezone)
|
| 71 |
+
# | mm: minutes
|
| 72 |
+
# | ss: seconds
|
| 73 |
+
# | request: The first line of the HTTP request as sent by the client.
|
| 74 |
+
# | ddd: the status code returned by the server, - if not available.
|
| 75 |
+
# | bbbb: the total number of bytes sent,
|
| 76 |
+
# | *not including the HTTP/1.0 header*, - if not available
|
| 77 |
+
# |
|
| 78 |
+
# | You can determine the name of the file accessed through request.
|
| 79 |
+
#
|
| 80 |
+
# (Actually, the latter is only true if you know the server configuration
|
| 81 |
+
# at the time the request was made!)
|
| 82 |
+
|
| 83 |
+
__version__ = "0.6"
|
| 84 |
+
|
| 85 |
+
__all__ = [
|
| 86 |
+
"HTTPServer", "ThreadingHTTPServer", "BaseHTTPRequestHandler",
|
| 87 |
+
"SimpleHTTPRequestHandler", "CGIHTTPRequestHandler",
|
| 88 |
+
]
|
| 89 |
+
|
| 90 |
+
import copy
|
| 91 |
+
import datetime
|
| 92 |
+
import email.utils
|
| 93 |
+
import html
|
| 94 |
+
import http.client
|
| 95 |
+
import io
|
| 96 |
+
import itertools
|
| 97 |
+
import mimetypes
|
| 98 |
+
import os
|
| 99 |
+
import posixpath
|
| 100 |
+
import select
|
| 101 |
+
import shutil
|
| 102 |
+
import socket # For gethostbyaddr()
|
| 103 |
+
import socketserver
|
| 104 |
+
import sys
|
| 105 |
+
import time
|
| 106 |
+
import urllib.parse
|
| 107 |
+
|
| 108 |
+
from http import HTTPStatus
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# Default error message template
|
| 112 |
+
DEFAULT_ERROR_MESSAGE = """\
|
| 113 |
+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
|
| 114 |
+
"http://www.w3.org/TR/html4/strict.dtd">
|
| 115 |
+
<html>
|
| 116 |
+
<head>
|
| 117 |
+
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
|
| 118 |
+
<title>Error response</title>
|
| 119 |
+
</head>
|
| 120 |
+
<body>
|
| 121 |
+
<h1>Error response</h1>
|
| 122 |
+
<p>Error code: %(code)d</p>
|
| 123 |
+
<p>Message: %(message)s.</p>
|
| 124 |
+
<p>Error code explanation: %(code)s - %(explain)s.</p>
|
| 125 |
+
</body>
|
| 126 |
+
</html>
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
DEFAULT_ERROR_CONTENT_TYPE = "text/html;charset=utf-8"
|
| 130 |
+
|
| 131 |
+
class HTTPServer(socketserver.TCPServer):
|
| 132 |
+
|
| 133 |
+
allow_reuse_address = 1 # Seems to make sense in testing environment
|
| 134 |
+
|
| 135 |
+
def server_bind(self):
|
| 136 |
+
"""Override server_bind to store the server name."""
|
| 137 |
+
socketserver.TCPServer.server_bind(self)
|
| 138 |
+
host, port = self.server_address[:2]
|
| 139 |
+
self.server_name = socket.getfqdn(host)
|
| 140 |
+
self.server_port = port
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer):
|
| 144 |
+
daemon_threads = True
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
|
| 148 |
+
|
| 149 |
+
"""HTTP request handler base class.
|
| 150 |
+
|
| 151 |
+
The following explanation of HTTP serves to guide you through the
|
| 152 |
+
code as well as to expose any misunderstandings I may have about
|
| 153 |
+
HTTP (so you don't need to read the code to figure out I'm wrong
|
| 154 |
+
:-).
|
| 155 |
+
|
| 156 |
+
HTTP (HyperText Transfer Protocol) is an extensible protocol on
|
| 157 |
+
top of a reliable stream transport (e.g. TCP/IP). The protocol
|
| 158 |
+
recognizes three parts to a request:
|
| 159 |
+
|
| 160 |
+
1. One line identifying the request type and path
|
| 161 |
+
2. An optional set of RFC-822-style headers
|
| 162 |
+
3. An optional data part
|
| 163 |
+
|
| 164 |
+
The headers and data are separated by a blank line.
|
| 165 |
+
|
| 166 |
+
The first line of the request has the form
|
| 167 |
+
|
| 168 |
+
<command> <path> <version>
|
| 169 |
+
|
| 170 |
+
where <command> is a (case-sensitive) keyword such as GET or POST,
|
| 171 |
+
<path> is a string containing path information for the request,
|
| 172 |
+
and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
|
| 173 |
+
<path> is encoded using the URL encoding scheme (using %xx to signify
|
| 174 |
+
the ASCII character with hex code xx).
|
| 175 |
+
|
| 176 |
+
The specification specifies that lines are separated by CRLF but
|
| 177 |
+
for compatibility with the widest range of clients recommends
|
| 178 |
+
servers also handle LF. Similarly, whitespace in the request line
|
| 179 |
+
is treated sensibly (allowing multiple spaces between components
|
| 180 |
+
and allowing trailing whitespace).
|
| 181 |
+
|
| 182 |
+
Similarly, for output, lines ought to be separated by CRLF pairs
|
| 183 |
+
but most clients grok LF characters just fine.
|
| 184 |
+
|
| 185 |
+
If the first line of the request has the form
|
| 186 |
+
|
| 187 |
+
<command> <path>
|
| 188 |
+
|
| 189 |
+
(i.e. <version> is left out) then this is assumed to be an HTTP
|
| 190 |
+
0.9 request; this form has no optional headers and data part and
|
| 191 |
+
the reply consists of just the data.
|
| 192 |
+
|
| 193 |
+
The reply form of the HTTP 1.x protocol again has three parts:
|
| 194 |
+
|
| 195 |
+
1. One line giving the response code
|
| 196 |
+
2. An optional set of RFC-822-style headers
|
| 197 |
+
3. The data
|
| 198 |
+
|
| 199 |
+
Again, the headers and data are separated by a blank line.
|
| 200 |
+
|
| 201 |
+
The response code line has the form
|
| 202 |
+
|
| 203 |
+
<version> <responsecode> <responsestring>
|
| 204 |
+
|
| 205 |
+
where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
|
| 206 |
+
<responsecode> is a 3-digit response code indicating success or
|
| 207 |
+
failure of the request, and <responsestring> is an optional
|
| 208 |
+
human-readable string explaining what the response code means.
|
| 209 |
+
|
| 210 |
+
This server parses the request and the headers, and then calls a
|
| 211 |
+
function specific to the request type (<command>). Specifically,
|
| 212 |
+
a request SPAM will be handled by a method do_SPAM(). If no
|
| 213 |
+
such method exists the server sends an error response to the
|
| 214 |
+
client. If it exists, it is called with no arguments:
|
| 215 |
+
|
| 216 |
+
do_SPAM()
|
| 217 |
+
|
| 218 |
+
Note that the request name is case sensitive (i.e. SPAM and spam
|
| 219 |
+
are different requests).
|
| 220 |
+
|
| 221 |
+
The various request details are stored in instance variables:
|
| 222 |
+
|
| 223 |
+
- client_address is the client IP address in the form (host,
|
| 224 |
+
port);
|
| 225 |
+
|
| 226 |
+
- command, path and version are the broken-down request line;
|
| 227 |
+
|
| 228 |
+
- headers is an instance of email.message.Message (or a derived
|
| 229 |
+
class) containing the header information;
|
| 230 |
+
|
| 231 |
+
- rfile is a file object open for reading positioned at the
|
| 232 |
+
start of the optional input data part;
|
| 233 |
+
|
| 234 |
+
- wfile is a file object open for writing.
|
| 235 |
+
|
| 236 |
+
IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
|
| 237 |
+
|
| 238 |
+
The first thing to be written must be the response line. Then
|
| 239 |
+
follow 0 or more header lines, then a blank line, and then the
|
| 240 |
+
actual data (if any). The meaning of the header lines depends on
|
| 241 |
+
the command executed by the server; in most cases, when data is
|
| 242 |
+
returned, there should be at least one header line of the form
|
| 243 |
+
|
| 244 |
+
Content-type: <type>/<subtype>
|
| 245 |
+
|
| 246 |
+
where <type> and <subtype> should be registered MIME types,
|
| 247 |
+
e.g. "text/html" or "text/plain".
|
| 248 |
+
|
| 249 |
+
"""
|
| 250 |
+
|
| 251 |
+
# The Python system version, truncated to its first component.
|
| 252 |
+
sys_version = "Python/" + sys.version.split()[0]
|
| 253 |
+
|
| 254 |
+
# The server software version. You may want to override this.
|
| 255 |
+
# The format is multiple whitespace-separated strings,
|
| 256 |
+
# where each string is of the form name[/version].
|
| 257 |
+
server_version = "BaseHTTP/" + __version__
|
| 258 |
+
|
| 259 |
+
error_message_format = DEFAULT_ERROR_MESSAGE
|
| 260 |
+
error_content_type = DEFAULT_ERROR_CONTENT_TYPE
|
| 261 |
+
|
| 262 |
+
# The default request version. This only affects responses up until
|
| 263 |
+
# the point where the request line is parsed, so it mainly decides what
|
| 264 |
+
# the client gets back when sending a malformed request line.
|
| 265 |
+
# Most web servers default to HTTP 0.9, i.e. don't send a status line.
|
| 266 |
+
default_request_version = "HTTP/0.9"
|
| 267 |
+
|
| 268 |
+
def parse_request(self):
|
| 269 |
+
"""Parse a request (internal).
|
| 270 |
+
|
| 271 |
+
The request should be stored in self.raw_requestline; the results
|
| 272 |
+
are in self.command, self.path, self.request_version and
|
| 273 |
+
self.headers.
|
| 274 |
+
|
| 275 |
+
Return True for success, False for failure; on failure, any relevant
|
| 276 |
+
error response has already been sent back.
|
| 277 |
+
|
| 278 |
+
"""
|
| 279 |
+
self.command = None # set in case of error on the first line
|
| 280 |
+
self.request_version = version = self.default_request_version
|
| 281 |
+
self.close_connection = True
|
| 282 |
+
requestline = str(self.raw_requestline, 'iso-8859-1')
|
| 283 |
+
requestline = requestline.rstrip('\r\n')
|
| 284 |
+
self.requestline = requestline
|
| 285 |
+
words = requestline.split()
|
| 286 |
+
if len(words) == 0:
|
| 287 |
+
return False
|
| 288 |
+
|
| 289 |
+
if len(words) >= 3: # Enough to determine protocol version
|
| 290 |
+
version = words[-1]
|
| 291 |
+
try:
|
| 292 |
+
if not version.startswith('HTTP/'):
|
| 293 |
+
raise ValueError
|
| 294 |
+
base_version_number = version.split('/', 1)[1]
|
| 295 |
+
version_number = base_version_number.split(".")
|
| 296 |
+
# RFC 2145 section 3.1 says there can be only one "." and
|
| 297 |
+
# - major and minor numbers MUST be treated as
|
| 298 |
+
# separate integers;
|
| 299 |
+
# - HTTP/2.4 is a lower version than HTTP/2.13, which in
|
| 300 |
+
# turn is lower than HTTP/12.3;
|
| 301 |
+
# - Leading zeros MUST be ignored by recipients.
|
| 302 |
+
if len(version_number) != 2:
|
| 303 |
+
raise ValueError
|
| 304 |
+
version_number = int(version_number[0]), int(version_number[1])
|
| 305 |
+
except (ValueError, IndexError):
|
| 306 |
+
self.send_error(
|
| 307 |
+
HTTPStatus.BAD_REQUEST,
|
| 308 |
+
"Bad request version (%r)" % version)
|
| 309 |
+
return False
|
| 310 |
+
if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
|
| 311 |
+
self.close_connection = False
|
| 312 |
+
if version_number >= (2, 0):
|
| 313 |
+
self.send_error(
|
| 314 |
+
HTTPStatus.HTTP_VERSION_NOT_SUPPORTED,
|
| 315 |
+
"Invalid HTTP version (%s)" % base_version_number)
|
| 316 |
+
return False
|
| 317 |
+
self.request_version = version
|
| 318 |
+
|
| 319 |
+
if not 2 <= len(words) <= 3:
|
| 320 |
+
self.send_error(
|
| 321 |
+
HTTPStatus.BAD_REQUEST,
|
| 322 |
+
"Bad request syntax (%r)" % requestline)
|
| 323 |
+
return False
|
| 324 |
+
command, path = words[:2]
|
| 325 |
+
if len(words) == 2:
|
| 326 |
+
self.close_connection = True
|
| 327 |
+
if command != 'GET':
|
| 328 |
+
self.send_error(
|
| 329 |
+
HTTPStatus.BAD_REQUEST,
|
| 330 |
+
"Bad HTTP/0.9 request type (%r)" % command)
|
| 331 |
+
return False
|
| 332 |
+
self.command, self.path = command, path
|
| 333 |
+
|
| 334 |
+
# gh-87389: The purpose of replacing '//' with '/' is to protect
|
| 335 |
+
# against open redirect attacks possibly triggered if the path starts
|
| 336 |
+
# with '//' because http clients treat //path as an absolute URI
|
| 337 |
+
# without scheme (similar to http://path) rather than a path.
|
| 338 |
+
if self.path.startswith('//'):
|
| 339 |
+
self.path = '/' + self.path.lstrip('/') # Reduce to a single /
|
| 340 |
+
|
| 341 |
+
# Examine the headers and look for a Connection directive.
|
| 342 |
+
try:
|
| 343 |
+
self.headers = http.client.parse_headers(self.rfile,
|
| 344 |
+
_class=self.MessageClass)
|
| 345 |
+
except http.client.LineTooLong as err:
|
| 346 |
+
self.send_error(
|
| 347 |
+
HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,
|
| 348 |
+
"Line too long",
|
| 349 |
+
str(err))
|
| 350 |
+
return False
|
| 351 |
+
except http.client.HTTPException as err:
|
| 352 |
+
self.send_error(
|
| 353 |
+
HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,
|
| 354 |
+
"Too many headers",
|
| 355 |
+
str(err)
|
| 356 |
+
)
|
| 357 |
+
return False
|
| 358 |
+
|
| 359 |
+
conntype = self.headers.get('Connection', "")
|
| 360 |
+
if conntype.lower() == 'close':
|
| 361 |
+
self.close_connection = True
|
| 362 |
+
elif (conntype.lower() == 'keep-alive' and
|
| 363 |
+
self.protocol_version >= "HTTP/1.1"):
|
| 364 |
+
self.close_connection = False
|
| 365 |
+
# Examine the headers and look for an Expect directive
|
| 366 |
+
expect = self.headers.get('Expect', "")
|
| 367 |
+
if (expect.lower() == "100-continue" and
|
| 368 |
+
self.protocol_version >= "HTTP/1.1" and
|
| 369 |
+
self.request_version >= "HTTP/1.1"):
|
| 370 |
+
if not self.handle_expect_100():
|
| 371 |
+
return False
|
| 372 |
+
return True
|
| 373 |
+
|
| 374 |
+
def handle_expect_100(self):
|
| 375 |
+
"""Decide what to do with an "Expect: 100-continue" header.
|
| 376 |
+
|
| 377 |
+
If the client is expecting a 100 Continue response, we must
|
| 378 |
+
respond with either a 100 Continue or a final response before
|
| 379 |
+
waiting for the request body. The default is to always respond
|
| 380 |
+
with a 100 Continue. You can behave differently (for example,
|
| 381 |
+
reject unauthorized requests) by overriding this method.
|
| 382 |
+
|
| 383 |
+
This method should either return True (possibly after sending
|
| 384 |
+
a 100 Continue response) or send an error response and return
|
| 385 |
+
False.
|
| 386 |
+
|
| 387 |
+
"""
|
| 388 |
+
self.send_response_only(HTTPStatus.CONTINUE)
|
| 389 |
+
self.end_headers()
|
| 390 |
+
return True
|
| 391 |
+
|
| 392 |
+
def handle_one_request(self):
|
| 393 |
+
"""Handle a single HTTP request.
|
| 394 |
+
|
| 395 |
+
You normally don't need to override this method; see the class
|
| 396 |
+
__doc__ string for information on how to handle specific HTTP
|
| 397 |
+
commands such as GET and POST.
|
| 398 |
+
|
| 399 |
+
"""
|
| 400 |
+
try:
|
| 401 |
+
self.raw_requestline = self.rfile.readline(65537)
|
| 402 |
+
if len(self.raw_requestline) > 65536:
|
| 403 |
+
self.requestline = ''
|
| 404 |
+
self.request_version = ''
|
| 405 |
+
self.command = ''
|
| 406 |
+
self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG)
|
| 407 |
+
return
|
| 408 |
+
if not self.raw_requestline:
|
| 409 |
+
self.close_connection = True
|
| 410 |
+
return
|
| 411 |
+
if not self.parse_request():
|
| 412 |
+
# An error code has been sent, just exit
|
| 413 |
+
return
|
| 414 |
+
mname = 'do_' + self.command
|
| 415 |
+
if not hasattr(self, mname):
|
| 416 |
+
self.send_error(
|
| 417 |
+
HTTPStatus.NOT_IMPLEMENTED,
|
| 418 |
+
"Unsupported method (%r)" % self.command)
|
| 419 |
+
return
|
| 420 |
+
method = getattr(self, mname)
|
| 421 |
+
method()
|
| 422 |
+
self.wfile.flush() #actually send the response if not already done.
|
| 423 |
+
except TimeoutError as e:
|
| 424 |
+
#a read or a write timed out. Discard this connection
|
| 425 |
+
self.log_error("Request timed out: %r", e)
|
| 426 |
+
self.close_connection = True
|
| 427 |
+
return
|
| 428 |
+
|
| 429 |
+
def handle(self):
|
| 430 |
+
"""Handle multiple requests if necessary."""
|
| 431 |
+
self.close_connection = True
|
| 432 |
+
|
| 433 |
+
self.handle_one_request()
|
| 434 |
+
while not self.close_connection:
|
| 435 |
+
self.handle_one_request()
|
| 436 |
+
|
| 437 |
+
def send_error(self, code, message=None, explain=None):
|
| 438 |
+
"""Send and log an error reply.
|
| 439 |
+
|
| 440 |
+
Arguments are
|
| 441 |
+
* code: an HTTP error code
|
| 442 |
+
3 digits
|
| 443 |
+
* message: a simple optional 1 line reason phrase.
|
| 444 |
+
*( HTAB / SP / VCHAR / %x80-FF )
|
| 445 |
+
defaults to short entry matching the response code
|
| 446 |
+
* explain: a detailed message defaults to the long entry
|
| 447 |
+
matching the response code.
|
| 448 |
+
|
| 449 |
+
This sends an error response (so it must be called before any
|
| 450 |
+
output has been generated), logs the error, and finally sends
|
| 451 |
+
a piece of HTML explaining the error to the user.
|
| 452 |
+
|
| 453 |
+
"""
|
| 454 |
+
|
| 455 |
+
try:
|
| 456 |
+
shortmsg, longmsg = self.responses[code]
|
| 457 |
+
except KeyError:
|
| 458 |
+
shortmsg, longmsg = '???', '???'
|
| 459 |
+
if message is None:
|
| 460 |
+
message = shortmsg
|
| 461 |
+
if explain is None:
|
| 462 |
+
explain = longmsg
|
| 463 |
+
self.log_error("code %d, message %s", code, message)
|
| 464 |
+
self.send_response(code, message)
|
| 465 |
+
self.send_header('Connection', 'close')
|
| 466 |
+
|
| 467 |
+
# Message body is omitted for cases described in:
|
| 468 |
+
# - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified)
|
| 469 |
+
# - RFC7231: 6.3.6. 205(Reset Content)
|
| 470 |
+
body = None
|
| 471 |
+
if (code >= 200 and
|
| 472 |
+
code not in (HTTPStatus.NO_CONTENT,
|
| 473 |
+
HTTPStatus.RESET_CONTENT,
|
| 474 |
+
HTTPStatus.NOT_MODIFIED)):
|
| 475 |
+
# HTML encode to prevent Cross Site Scripting attacks
|
| 476 |
+
# (see bug #1100201)
|
| 477 |
+
content = (self.error_message_format % {
|
| 478 |
+
'code': code,
|
| 479 |
+
'message': html.escape(message, quote=False),
|
| 480 |
+
'explain': html.escape(explain, quote=False)
|
| 481 |
+
})
|
| 482 |
+
body = content.encode('UTF-8', 'replace')
|
| 483 |
+
self.send_header("Content-Type", self.error_content_type)
|
| 484 |
+
self.send_header('Content-Length', str(len(body)))
|
| 485 |
+
self.end_headers()
|
| 486 |
+
|
| 487 |
+
if self.command != 'HEAD' and body:
|
| 488 |
+
self.wfile.write(body)
|
| 489 |
+
|
| 490 |
+
def send_response(self, code, message=None):
|
| 491 |
+
"""Add the response header to the headers buffer and log the
|
| 492 |
+
response code.
|
| 493 |
+
|
| 494 |
+
Also send two standard headers with the server software
|
| 495 |
+
version and the current date.
|
| 496 |
+
|
| 497 |
+
"""
|
| 498 |
+
self.log_request(code)
|
| 499 |
+
self.send_response_only(code, message)
|
| 500 |
+
self.send_header('Server', self.version_string())
|
| 501 |
+
self.send_header('Date', self.date_time_string())
|
| 502 |
+
|
| 503 |
+
def send_response_only(self, code, message=None):
|
| 504 |
+
"""Send the response header only."""
|
| 505 |
+
if self.request_version != 'HTTP/0.9':
|
| 506 |
+
if message is None:
|
| 507 |
+
if code in self.responses:
|
| 508 |
+
message = self.responses[code][0]
|
| 509 |
+
else:
|
| 510 |
+
message = ''
|
| 511 |
+
if not hasattr(self, '_headers_buffer'):
|
| 512 |
+
self._headers_buffer = []
|
| 513 |
+
self._headers_buffer.append(("%s %d %s\r\n" %
|
| 514 |
+
(self.protocol_version, code, message)).encode(
|
| 515 |
+
'latin-1', 'strict'))
|
| 516 |
+
|
| 517 |
+
def send_header(self, keyword, value):
|
| 518 |
+
"""Send a MIME header to the headers buffer."""
|
| 519 |
+
if self.request_version != 'HTTP/0.9':
|
| 520 |
+
if not hasattr(self, '_headers_buffer'):
|
| 521 |
+
self._headers_buffer = []
|
| 522 |
+
self._headers_buffer.append(
|
| 523 |
+
("%s: %s\r\n" % (keyword, value)).encode('latin-1', 'strict'))
|
| 524 |
+
|
| 525 |
+
if keyword.lower() == 'connection':
|
| 526 |
+
if value.lower() == 'close':
|
| 527 |
+
self.close_connection = True
|
| 528 |
+
elif value.lower() == 'keep-alive':
|
| 529 |
+
self.close_connection = False
|
| 530 |
+
|
| 531 |
+
def end_headers(self):
|
| 532 |
+
"""Send the blank line ending the MIME headers."""
|
| 533 |
+
if self.request_version != 'HTTP/0.9':
|
| 534 |
+
self._headers_buffer.append(b"\r\n")
|
| 535 |
+
self.flush_headers()
|
| 536 |
+
|
| 537 |
+
def flush_headers(self):
|
| 538 |
+
if hasattr(self, '_headers_buffer'):
|
| 539 |
+
self.wfile.write(b"".join(self._headers_buffer))
|
| 540 |
+
self._headers_buffer = []
|
| 541 |
+
|
| 542 |
+
def log_request(self, code='-', size='-'):
|
| 543 |
+
"""Log an accepted request.
|
| 544 |
+
|
| 545 |
+
This is called by send_response().
|
| 546 |
+
|
| 547 |
+
"""
|
| 548 |
+
if isinstance(code, HTTPStatus):
|
| 549 |
+
code = code.value
|
| 550 |
+
self.log_message('"%s" %s %s',
|
| 551 |
+
self.requestline, str(code), str(size))
|
| 552 |
+
|
| 553 |
+
def log_error(self, format, *args):
|
| 554 |
+
"""Log an error.
|
| 555 |
+
|
| 556 |
+
This is called when a request cannot be fulfilled. By
|
| 557 |
+
default it passes the message on to log_message().
|
| 558 |
+
|
| 559 |
+
Arguments are the same as for log_message().
|
| 560 |
+
|
| 561 |
+
XXX This should go to the separate error log.
|
| 562 |
+
|
| 563 |
+
"""
|
| 564 |
+
|
| 565 |
+
self.log_message(format, *args)
|
| 566 |
+
|
| 567 |
+
# https://en.wikipedia.org/wiki/List_of_Unicode_characters#Control_codes
|
| 568 |
+
_control_char_table = str.maketrans(
|
| 569 |
+
{c: fr'\x{c:02x}' for c in itertools.chain(range(0x20), range(0x7f,0xa0))})
|
| 570 |
+
_control_char_table[ord('\\')] = r'\\'
|
| 571 |
+
|
| 572 |
+
def log_message(self, format, *args):
|
| 573 |
+
"""Log an arbitrary message.
|
| 574 |
+
|
| 575 |
+
This is used by all other logging functions. Override
|
| 576 |
+
it if you have specific logging wishes.
|
| 577 |
+
|
| 578 |
+
The first argument, FORMAT, is a format string for the
|
| 579 |
+
message to be logged. If the format string contains
|
| 580 |
+
any % escapes requiring parameters, they should be
|
| 581 |
+
specified as subsequent arguments (it's just like
|
| 582 |
+
printf!).
|
| 583 |
+
|
| 584 |
+
The client ip and current date/time are prefixed to
|
| 585 |
+
every message.
|
| 586 |
+
|
| 587 |
+
Unicode control characters are replaced with escaped hex
|
| 588 |
+
before writing the output to stderr.
|
| 589 |
+
|
| 590 |
+
"""
|
| 591 |
+
|
| 592 |
+
message = format % args
|
| 593 |
+
sys.stderr.write("%s - - [%s] %s\n" %
|
| 594 |
+
(self.address_string(),
|
| 595 |
+
self.log_date_time_string(),
|
| 596 |
+
message.translate(self._control_char_table)))
|
| 597 |
+
|
| 598 |
+
def version_string(self):
|
| 599 |
+
"""Return the server software version string."""
|
| 600 |
+
return self.server_version + ' ' + self.sys_version
|
| 601 |
+
|
| 602 |
+
def date_time_string(self, timestamp=None):
|
| 603 |
+
"""Return the current date and time formatted for a message header."""
|
| 604 |
+
if timestamp is None:
|
| 605 |
+
timestamp = time.time()
|
| 606 |
+
return email.utils.formatdate(timestamp, usegmt=True)
|
| 607 |
+
|
| 608 |
+
def log_date_time_string(self):
|
| 609 |
+
"""Return the current time formatted for logging."""
|
| 610 |
+
now = time.time()
|
| 611 |
+
year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
|
| 612 |
+
s = "%02d/%3s/%04d %02d:%02d:%02d" % (
|
| 613 |
+
day, self.monthname[month], year, hh, mm, ss)
|
| 614 |
+
return s
|
| 615 |
+
|
| 616 |
+
weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
|
| 617 |
+
|
| 618 |
+
monthname = [None,
|
| 619 |
+
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
| 620 |
+
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
|
| 621 |
+
|
| 622 |
+
def address_string(self):
|
| 623 |
+
"""Return the client address."""
|
| 624 |
+
|
| 625 |
+
return self.client_address[0]
|
| 626 |
+
|
| 627 |
+
# Essentially static class variables
|
| 628 |
+
|
| 629 |
+
# The version of the HTTP protocol we support.
|
| 630 |
+
# Set this to HTTP/1.1 to enable automatic keepalive
|
| 631 |
+
protocol_version = "HTTP/1.0"
|
| 632 |
+
|
| 633 |
+
# MessageClass used to parse headers
|
| 634 |
+
MessageClass = http.client.HTTPMessage
|
| 635 |
+
|
| 636 |
+
# hack to maintain backwards compatibility
|
| 637 |
+
responses = {
|
| 638 |
+
v: (v.phrase, v.description)
|
| 639 |
+
for v in HTTPStatus.__members__.values()
|
| 640 |
+
}
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
|
| 644 |
+
|
| 645 |
+
"""Simple HTTP request handler with GET and HEAD commands.
|
| 646 |
+
|
| 647 |
+
This serves files from the current directory and any of its
|
| 648 |
+
subdirectories. The MIME type for files is determined by
|
| 649 |
+
calling the .guess_type() method.
|
| 650 |
+
|
| 651 |
+
The GET and HEAD requests are identical except that the HEAD
|
| 652 |
+
request omits the actual contents of the file.
|
| 653 |
+
|
| 654 |
+
"""
|
| 655 |
+
|
| 656 |
+
server_version = "SimpleHTTP/" + __version__
|
| 657 |
+
extensions_map = _encodings_map_default = {
|
| 658 |
+
'.gz': 'application/gzip',
|
| 659 |
+
'.Z': 'application/octet-stream',
|
| 660 |
+
'.bz2': 'application/x-bzip2',
|
| 661 |
+
'.xz': 'application/x-xz',
|
| 662 |
+
}
|
| 663 |
+
|
| 664 |
+
def __init__(self, *args, directory=None, **kwargs):
|
| 665 |
+
if directory is None:
|
| 666 |
+
directory = os.getcwd()
|
| 667 |
+
self.directory = os.fspath(directory)
|
| 668 |
+
super().__init__(*args, **kwargs)
|
| 669 |
+
|
| 670 |
+
def do_GET(self):
|
| 671 |
+
"""Serve a GET request."""
|
| 672 |
+
f = self.send_head()
|
| 673 |
+
if f:
|
| 674 |
+
try:
|
| 675 |
+
self.copyfile(f, self.wfile)
|
| 676 |
+
finally:
|
| 677 |
+
f.close()
|
| 678 |
+
|
| 679 |
+
def do_HEAD(self):
|
| 680 |
+
"""Serve a HEAD request."""
|
| 681 |
+
f = self.send_head()
|
| 682 |
+
if f:
|
| 683 |
+
f.close()
|
| 684 |
+
|
| 685 |
+
def send_head(self):
|
| 686 |
+
"""Common code for GET and HEAD commands.
|
| 687 |
+
|
| 688 |
+
This sends the response code and MIME headers.
|
| 689 |
+
|
| 690 |
+
Return value is either a file object (which has to be copied
|
| 691 |
+
to the outputfile by the caller unless the command was HEAD,
|
| 692 |
+
and must be closed by the caller under all circumstances), or
|
| 693 |
+
None, in which case the caller has nothing further to do.
|
| 694 |
+
|
| 695 |
+
"""
|
| 696 |
+
path = self.translate_path(self.path)
|
| 697 |
+
f = None
|
| 698 |
+
if os.path.isdir(path):
|
| 699 |
+
parts = urllib.parse.urlsplit(self.path)
|
| 700 |
+
if not parts.path.endswith('/'):
|
| 701 |
+
# redirect browser - doing basically what apache does
|
| 702 |
+
self.send_response(HTTPStatus.MOVED_PERMANENTLY)
|
| 703 |
+
new_parts = (parts[0], parts[1], parts[2] + '/',
|
| 704 |
+
parts[3], parts[4])
|
| 705 |
+
new_url = urllib.parse.urlunsplit(new_parts)
|
| 706 |
+
self.send_header("Location", new_url)
|
| 707 |
+
self.send_header("Content-Length", "0")
|
| 708 |
+
self.end_headers()
|
| 709 |
+
return None
|
| 710 |
+
for index in "index.html", "index.htm":
|
| 711 |
+
index = os.path.join(path, index)
|
| 712 |
+
if os.path.isfile(index):
|
| 713 |
+
path = index
|
| 714 |
+
break
|
| 715 |
+
else:
|
| 716 |
+
return self.list_directory(path)
|
| 717 |
+
ctype = self.guess_type(path)
|
| 718 |
+
# check for trailing "/" which should return 404. See Issue17324
|
| 719 |
+
# The test for this was added in test_httpserver.py
|
| 720 |
+
# However, some OS platforms accept a trailingSlash as a filename
|
| 721 |
+
# See discussion on python-dev and Issue34711 regarding
|
| 722 |
+
# parseing and rejection of filenames with a trailing slash
|
| 723 |
+
if path.endswith("/"):
|
| 724 |
+
self.send_error(HTTPStatus.NOT_FOUND, "File not found")
|
| 725 |
+
return None
|
| 726 |
+
try:
|
| 727 |
+
f = open(path, 'rb')
|
| 728 |
+
except OSError:
|
| 729 |
+
self.send_error(HTTPStatus.NOT_FOUND, "File not found")
|
| 730 |
+
return None
|
| 731 |
+
|
| 732 |
+
try:
|
| 733 |
+
fs = os.fstat(f.fileno())
|
| 734 |
+
# Use browser cache if possible
|
| 735 |
+
if ("If-Modified-Since" in self.headers
|
| 736 |
+
and "If-None-Match" not in self.headers):
|
| 737 |
+
# compare If-Modified-Since and time of last file modification
|
| 738 |
+
try:
|
| 739 |
+
ims = email.utils.parsedate_to_datetime(
|
| 740 |
+
self.headers["If-Modified-Since"])
|
| 741 |
+
except (TypeError, IndexError, OverflowError, ValueError):
|
| 742 |
+
# ignore ill-formed values
|
| 743 |
+
pass
|
| 744 |
+
else:
|
| 745 |
+
if ims.tzinfo is None:
|
| 746 |
+
# obsolete format with no timezone, cf.
|
| 747 |
+
# https://tools.ietf.org/html/rfc7231#section-7.1.1.1
|
| 748 |
+
ims = ims.replace(tzinfo=datetime.timezone.utc)
|
| 749 |
+
if ims.tzinfo is datetime.timezone.utc:
|
| 750 |
+
# compare to UTC datetime of last modification
|
| 751 |
+
last_modif = datetime.datetime.fromtimestamp(
|
| 752 |
+
fs.st_mtime, datetime.timezone.utc)
|
| 753 |
+
# remove microseconds, like in If-Modified-Since
|
| 754 |
+
last_modif = last_modif.replace(microsecond=0)
|
| 755 |
+
|
| 756 |
+
if last_modif <= ims:
|
| 757 |
+
self.send_response(HTTPStatus.NOT_MODIFIED)
|
| 758 |
+
self.end_headers()
|
| 759 |
+
f.close()
|
| 760 |
+
return None
|
| 761 |
+
|
| 762 |
+
self.send_response(HTTPStatus.OK)
|
| 763 |
+
self.send_header("Content-type", ctype)
|
| 764 |
+
self.send_header("Content-Length", str(fs[6]))
|
| 765 |
+
self.send_header("Last-Modified",
|
| 766 |
+
self.date_time_string(fs.st_mtime))
|
| 767 |
+
self.end_headers()
|
| 768 |
+
return f
|
| 769 |
+
except:
|
| 770 |
+
f.close()
|
| 771 |
+
raise
|
| 772 |
+
|
| 773 |
+
def list_directory(self, path):
|
| 774 |
+
"""Helper to produce a directory listing (absent index.html).
|
| 775 |
+
|
| 776 |
+
Return value is either a file object, or None (indicating an
|
| 777 |
+
error). In either case, the headers are sent, making the
|
| 778 |
+
interface the same as for send_head().
|
| 779 |
+
|
| 780 |
+
"""
|
| 781 |
+
try:
|
| 782 |
+
list = os.listdir(path)
|
| 783 |
+
except OSError:
|
| 784 |
+
self.send_error(
|
| 785 |
+
HTTPStatus.NOT_FOUND,
|
| 786 |
+
"No permission to list directory")
|
| 787 |
+
return None
|
| 788 |
+
list.sort(key=lambda a: a.lower())
|
| 789 |
+
r = []
|
| 790 |
+
try:
|
| 791 |
+
displaypath = urllib.parse.unquote(self.path,
|
| 792 |
+
errors='surrogatepass')
|
| 793 |
+
except UnicodeDecodeError:
|
| 794 |
+
displaypath = urllib.parse.unquote(self.path)
|
| 795 |
+
displaypath = html.escape(displaypath, quote=False)
|
| 796 |
+
enc = sys.getfilesystemencoding()
|
| 797 |
+
title = 'Directory listing for %s' % displaypath
|
| 798 |
+
r.append('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
|
| 799 |
+
'"http://www.w3.org/TR/html4/strict.dtd">')
|
| 800 |
+
r.append('<html>\n<head>')
|
| 801 |
+
r.append('<meta http-equiv="Content-Type" '
|
| 802 |
+
'content="text/html; charset=%s">' % enc)
|
| 803 |
+
r.append('<title>%s</title>\n</head>' % title)
|
| 804 |
+
r.append('<body>\n<h1>%s</h1>' % title)
|
| 805 |
+
r.append('<hr>\n<ul>')
|
| 806 |
+
for name in list:
|
| 807 |
+
fullname = os.path.join(path, name)
|
| 808 |
+
displayname = linkname = name
|
| 809 |
+
# Append / for directories or @ for symbolic links
|
| 810 |
+
if os.path.isdir(fullname):
|
| 811 |
+
displayname = name + "/"
|
| 812 |
+
linkname = name + "/"
|
| 813 |
+
if os.path.islink(fullname):
|
| 814 |
+
displayname = name + "@"
|
| 815 |
+
# Note: a link to a directory displays with @ and links with /
|
| 816 |
+
r.append('<li><a href="%s">%s</a></li>'
|
| 817 |
+
% (urllib.parse.quote(linkname,
|
| 818 |
+
errors='surrogatepass'),
|
| 819 |
+
html.escape(displayname, quote=False)))
|
| 820 |
+
r.append('</ul>\n<hr>\n</body>\n</html>\n')
|
| 821 |
+
encoded = '\n'.join(r).encode(enc, 'surrogateescape')
|
| 822 |
+
f = io.BytesIO()
|
| 823 |
+
f.write(encoded)
|
| 824 |
+
f.seek(0)
|
| 825 |
+
self.send_response(HTTPStatus.OK)
|
| 826 |
+
self.send_header("Content-type", "text/html; charset=%s" % enc)
|
| 827 |
+
self.send_header("Content-Length", str(len(encoded)))
|
| 828 |
+
self.end_headers()
|
| 829 |
+
return f
|
| 830 |
+
|
| 831 |
+
def translate_path(self, path):
|
| 832 |
+
"""Translate a /-separated PATH to the local filename syntax.
|
| 833 |
+
|
| 834 |
+
Components that mean special things to the local file system
|
| 835 |
+
(e.g. drive or directory names) are ignored. (XXX They should
|
| 836 |
+
probably be diagnosed.)
|
| 837 |
+
|
| 838 |
+
"""
|
| 839 |
+
# abandon query parameters
|
| 840 |
+
path = path.split('?',1)[0]
|
| 841 |
+
path = path.split('#',1)[0]
|
| 842 |
+
# Don't forget explicit trailing slash when normalizing. Issue17324
|
| 843 |
+
trailing_slash = path.rstrip().endswith('/')
|
| 844 |
+
try:
|
| 845 |
+
path = urllib.parse.unquote(path, errors='surrogatepass')
|
| 846 |
+
except UnicodeDecodeError:
|
| 847 |
+
path = urllib.parse.unquote(path)
|
| 848 |
+
path = posixpath.normpath(path)
|
| 849 |
+
words = path.split('/')
|
| 850 |
+
words = filter(None, words)
|
| 851 |
+
path = self.directory
|
| 852 |
+
for word in words:
|
| 853 |
+
if os.path.dirname(word) or word in (os.curdir, os.pardir):
|
| 854 |
+
# Ignore components that are not a simple file/directory name
|
| 855 |
+
continue
|
| 856 |
+
path = os.path.join(path, word)
|
| 857 |
+
if trailing_slash:
|
| 858 |
+
path += '/'
|
| 859 |
+
return path
|
| 860 |
+
|
| 861 |
+
def copyfile(self, source, outputfile):
|
| 862 |
+
"""Copy all data between two file objects.
|
| 863 |
+
|
| 864 |
+
The SOURCE argument is a file object open for reading
|
| 865 |
+
(or anything with a read() method) and the DESTINATION
|
| 866 |
+
argument is a file object open for writing (or
|
| 867 |
+
anything with a write() method).
|
| 868 |
+
|
| 869 |
+
The only reason for overriding this would be to change
|
| 870 |
+
the block size or perhaps to replace newlines by CRLF
|
| 871 |
+
-- note however that this the default server uses this
|
| 872 |
+
to copy binary data as well.
|
| 873 |
+
|
| 874 |
+
"""
|
| 875 |
+
shutil.copyfileobj(source, outputfile)
|
| 876 |
+
|
| 877 |
+
def guess_type(self, path):
|
| 878 |
+
"""Guess the type of a file.
|
| 879 |
+
|
| 880 |
+
Argument is a PATH (a filename).
|
| 881 |
+
|
| 882 |
+
Return value is a string of the form type/subtype,
|
| 883 |
+
usable for a MIME Content-type header.
|
| 884 |
+
|
| 885 |
+
The default implementation looks the file's extension
|
| 886 |
+
up in the table self.extensions_map, using application/octet-stream
|
| 887 |
+
as a default; however it would be permissible (if
|
| 888 |
+
slow) to look inside the data to make a better guess.
|
| 889 |
+
|
| 890 |
+
"""
|
| 891 |
+
base, ext = posixpath.splitext(path)
|
| 892 |
+
if ext in self.extensions_map:
|
| 893 |
+
return self.extensions_map[ext]
|
| 894 |
+
ext = ext.lower()
|
| 895 |
+
if ext in self.extensions_map:
|
| 896 |
+
return self.extensions_map[ext]
|
| 897 |
+
guess, _ = mimetypes.guess_type(path)
|
| 898 |
+
if guess:
|
| 899 |
+
return guess
|
| 900 |
+
return 'application/octet-stream'
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
# Utilities for CGIHTTPRequestHandler
|
| 904 |
+
|
| 905 |
+
def _url_collapse_path(path):
|
| 906 |
+
"""
|
| 907 |
+
Given a URL path, remove extra '/'s and '.' path elements and collapse
|
| 908 |
+
any '..' references and returns a collapsed path.
|
| 909 |
+
|
| 910 |
+
Implements something akin to RFC-2396 5.2 step 6 to parse relative paths.
|
| 911 |
+
The utility of this function is limited to is_cgi method and helps
|
| 912 |
+
preventing some security attacks.
|
| 913 |
+
|
| 914 |
+
Returns: The reconstituted URL, which will always start with a '/'.
|
| 915 |
+
|
| 916 |
+
Raises: IndexError if too many '..' occur within the path.
|
| 917 |
+
|
| 918 |
+
"""
|
| 919 |
+
# Query component should not be involved.
|
| 920 |
+
path, _, query = path.partition('?')
|
| 921 |
+
path = urllib.parse.unquote(path)
|
| 922 |
+
|
| 923 |
+
# Similar to os.path.split(os.path.normpath(path)) but specific to URL
|
| 924 |
+
# path semantics rather than local operating system semantics.
|
| 925 |
+
path_parts = path.split('/')
|
| 926 |
+
head_parts = []
|
| 927 |
+
for part in path_parts[:-1]:
|
| 928 |
+
if part == '..':
|
| 929 |
+
head_parts.pop() # IndexError if more '..' than prior parts
|
| 930 |
+
elif part and part != '.':
|
| 931 |
+
head_parts.append( part )
|
| 932 |
+
if path_parts:
|
| 933 |
+
tail_part = path_parts.pop()
|
| 934 |
+
if tail_part:
|
| 935 |
+
if tail_part == '..':
|
| 936 |
+
head_parts.pop()
|
| 937 |
+
tail_part = ''
|
| 938 |
+
elif tail_part == '.':
|
| 939 |
+
tail_part = ''
|
| 940 |
+
else:
|
| 941 |
+
tail_part = ''
|
| 942 |
+
|
| 943 |
+
if query:
|
| 944 |
+
tail_part = '?'.join((tail_part, query))
|
| 945 |
+
|
| 946 |
+
splitpath = ('/' + '/'.join(head_parts), tail_part)
|
| 947 |
+
collapsed_path = "/".join(splitpath)
|
| 948 |
+
|
| 949 |
+
return collapsed_path
|
| 950 |
+
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
nobody = None
|
| 954 |
+
|
| 955 |
+
def nobody_uid():
|
| 956 |
+
"""Internal routine to get nobody's uid"""
|
| 957 |
+
global nobody
|
| 958 |
+
if nobody:
|
| 959 |
+
return nobody
|
| 960 |
+
try:
|
| 961 |
+
import pwd
|
| 962 |
+
except ImportError:
|
| 963 |
+
return -1
|
| 964 |
+
try:
|
| 965 |
+
nobody = pwd.getpwnam('nobody')[2]
|
| 966 |
+
except KeyError:
|
| 967 |
+
nobody = 1 + max(x[2] for x in pwd.getpwall())
|
| 968 |
+
return nobody
|
| 969 |
+
|
| 970 |
+
|
| 971 |
+
def executable(path):
|
| 972 |
+
"""Test for executable file."""
|
| 973 |
+
return os.access(path, os.X_OK)
|
| 974 |
+
|
| 975 |
+
|
| 976 |
+
class CGIHTTPRequestHandler(SimpleHTTPRequestHandler):
|
| 977 |
+
|
| 978 |
+
"""Complete HTTP server with GET, HEAD and POST commands.
|
| 979 |
+
|
| 980 |
+
GET and HEAD also support running CGI scripts.
|
| 981 |
+
|
| 982 |
+
The POST command is *only* implemented for CGI scripts.
|
| 983 |
+
|
| 984 |
+
"""
|
| 985 |
+
|
| 986 |
+
# Determine platform specifics
|
| 987 |
+
have_fork = hasattr(os, 'fork')
|
| 988 |
+
|
| 989 |
+
# Make rfile unbuffered -- we need to read one line and then pass
|
| 990 |
+
# the rest to a subprocess, so we can't use buffered input.
|
| 991 |
+
rbufsize = 0
|
| 992 |
+
|
| 993 |
+
def do_POST(self):
|
| 994 |
+
"""Serve a POST request.
|
| 995 |
+
|
| 996 |
+
This is only implemented for CGI scripts.
|
| 997 |
+
|
| 998 |
+
"""
|
| 999 |
+
|
| 1000 |
+
if self.is_cgi():
|
| 1001 |
+
self.run_cgi()
|
| 1002 |
+
else:
|
| 1003 |
+
self.send_error(
|
| 1004 |
+
HTTPStatus.NOT_IMPLEMENTED,
|
| 1005 |
+
"Can only POST to CGI scripts")
|
| 1006 |
+
|
| 1007 |
+
def send_head(self):
|
| 1008 |
+
"""Version of send_head that support CGI scripts"""
|
| 1009 |
+
if self.is_cgi():
|
| 1010 |
+
return self.run_cgi()
|
| 1011 |
+
else:
|
| 1012 |
+
return SimpleHTTPRequestHandler.send_head(self)
|
| 1013 |
+
|
| 1014 |
+
def is_cgi(self):
|
| 1015 |
+
"""Test whether self.path corresponds to a CGI script.
|
| 1016 |
+
|
| 1017 |
+
Returns True and updates the cgi_info attribute to the tuple
|
| 1018 |
+
(dir, rest) if self.path requires running a CGI script.
|
| 1019 |
+
Returns False otherwise.
|
| 1020 |
+
|
| 1021 |
+
If any exception is raised, the caller should assume that
|
| 1022 |
+
self.path was rejected as invalid and act accordingly.
|
| 1023 |
+
|
| 1024 |
+
The default implementation tests whether the normalized url
|
| 1025 |
+
path begins with one of the strings in self.cgi_directories
|
| 1026 |
+
(and the next character is a '/' or the end of the string).
|
| 1027 |
+
|
| 1028 |
+
"""
|
| 1029 |
+
collapsed_path = _url_collapse_path(self.path)
|
| 1030 |
+
dir_sep = collapsed_path.find('/', 1)
|
| 1031 |
+
while dir_sep > 0 and not collapsed_path[:dir_sep] in self.cgi_directories:
|
| 1032 |
+
dir_sep = collapsed_path.find('/', dir_sep+1)
|
| 1033 |
+
if dir_sep > 0:
|
| 1034 |
+
head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:]
|
| 1035 |
+
self.cgi_info = head, tail
|
| 1036 |
+
return True
|
| 1037 |
+
return False
|
| 1038 |
+
|
| 1039 |
+
|
| 1040 |
+
cgi_directories = ['/cgi-bin', '/htbin']
|
| 1041 |
+
|
| 1042 |
+
def is_executable(self, path):
|
| 1043 |
+
"""Test whether argument path is an executable file."""
|
| 1044 |
+
return executable(path)
|
| 1045 |
+
|
| 1046 |
+
def is_python(self, path):
|
| 1047 |
+
"""Test whether argument path is a Python script."""
|
| 1048 |
+
head, tail = os.path.splitext(path)
|
| 1049 |
+
return tail.lower() in (".py", ".pyw")
|
| 1050 |
+
|
| 1051 |
+
def run_cgi(self):
|
| 1052 |
+
"""Execute a CGI script."""
|
| 1053 |
+
dir, rest = self.cgi_info
|
| 1054 |
+
path = dir + '/' + rest
|
| 1055 |
+
i = path.find('/', len(dir)+1)
|
| 1056 |
+
while i >= 0:
|
| 1057 |
+
nextdir = path[:i]
|
| 1058 |
+
nextrest = path[i+1:]
|
| 1059 |
+
|
| 1060 |
+
scriptdir = self.translate_path(nextdir)
|
| 1061 |
+
if os.path.isdir(scriptdir):
|
| 1062 |
+
dir, rest = nextdir, nextrest
|
| 1063 |
+
i = path.find('/', len(dir)+1)
|
| 1064 |
+
else:
|
| 1065 |
+
break
|
| 1066 |
+
|
| 1067 |
+
# find an explicit query string, if present.
|
| 1068 |
+
rest, _, query = rest.partition('?')
|
| 1069 |
+
|
| 1070 |
+
# dissect the part after the directory name into a script name &
|
| 1071 |
+
# a possible additional path, to be stored in PATH_INFO.
|
| 1072 |
+
i = rest.find('/')
|
| 1073 |
+
if i >= 0:
|
| 1074 |
+
script, rest = rest[:i], rest[i:]
|
| 1075 |
+
else:
|
| 1076 |
+
script, rest = rest, ''
|
| 1077 |
+
|
| 1078 |
+
scriptname = dir + '/' + script
|
| 1079 |
+
scriptfile = self.translate_path(scriptname)
|
| 1080 |
+
if not os.path.exists(scriptfile):
|
| 1081 |
+
self.send_error(
|
| 1082 |
+
HTTPStatus.NOT_FOUND,
|
| 1083 |
+
"No such CGI script (%r)" % scriptname)
|
| 1084 |
+
return
|
| 1085 |
+
if not os.path.isfile(scriptfile):
|
| 1086 |
+
self.send_error(
|
| 1087 |
+
HTTPStatus.FORBIDDEN,
|
| 1088 |
+
"CGI script is not a plain file (%r)" % scriptname)
|
| 1089 |
+
return
|
| 1090 |
+
ispy = self.is_python(scriptname)
|
| 1091 |
+
if self.have_fork or not ispy:
|
| 1092 |
+
if not self.is_executable(scriptfile):
|
| 1093 |
+
self.send_error(
|
| 1094 |
+
HTTPStatus.FORBIDDEN,
|
| 1095 |
+
"CGI script is not executable (%r)" % scriptname)
|
| 1096 |
+
return
|
| 1097 |
+
|
| 1098 |
+
# Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
|
| 1099 |
+
# XXX Much of the following could be prepared ahead of time!
|
| 1100 |
+
env = copy.deepcopy(os.environ)
|
| 1101 |
+
env['SERVER_SOFTWARE'] = self.version_string()
|
| 1102 |
+
env['SERVER_NAME'] = self.server.server_name
|
| 1103 |
+
env['GATEWAY_INTERFACE'] = 'CGI/1.1'
|
| 1104 |
+
env['SERVER_PROTOCOL'] = self.protocol_version
|
| 1105 |
+
env['SERVER_PORT'] = str(self.server.server_port)
|
| 1106 |
+
env['REQUEST_METHOD'] = self.command
|
| 1107 |
+
uqrest = urllib.parse.unquote(rest)
|
| 1108 |
+
env['PATH_INFO'] = uqrest
|
| 1109 |
+
env['PATH_TRANSLATED'] = self.translate_path(uqrest)
|
| 1110 |
+
env['SCRIPT_NAME'] = scriptname
|
| 1111 |
+
env['QUERY_STRING'] = query
|
| 1112 |
+
env['REMOTE_ADDR'] = self.client_address[0]
|
| 1113 |
+
authorization = self.headers.get("authorization")
|
| 1114 |
+
if authorization:
|
| 1115 |
+
authorization = authorization.split()
|
| 1116 |
+
if len(authorization) == 2:
|
| 1117 |
+
import base64, binascii
|
| 1118 |
+
env['AUTH_TYPE'] = authorization[0]
|
| 1119 |
+
if authorization[0].lower() == "basic":
|
| 1120 |
+
try:
|
| 1121 |
+
authorization = authorization[1].encode('ascii')
|
| 1122 |
+
authorization = base64.decodebytes(authorization).\
|
| 1123 |
+
decode('ascii')
|
| 1124 |
+
except (binascii.Error, UnicodeError):
|
| 1125 |
+
pass
|
| 1126 |
+
else:
|
| 1127 |
+
authorization = authorization.split(':')
|
| 1128 |
+
if len(authorization) == 2:
|
| 1129 |
+
env['REMOTE_USER'] = authorization[0]
|
| 1130 |
+
# XXX REMOTE_IDENT
|
| 1131 |
+
if self.headers.get('content-type') is None:
|
| 1132 |
+
env['CONTENT_TYPE'] = self.headers.get_content_type()
|
| 1133 |
+
else:
|
| 1134 |
+
env['CONTENT_TYPE'] = self.headers['content-type']
|
| 1135 |
+
length = self.headers.get('content-length')
|
| 1136 |
+
if length:
|
| 1137 |
+
env['CONTENT_LENGTH'] = length
|
| 1138 |
+
referer = self.headers.get('referer')
|
| 1139 |
+
if referer:
|
| 1140 |
+
env['HTTP_REFERER'] = referer
|
| 1141 |
+
accept = self.headers.get_all('accept', ())
|
| 1142 |
+
env['HTTP_ACCEPT'] = ','.join(accept)
|
| 1143 |
+
ua = self.headers.get('user-agent')
|
| 1144 |
+
if ua:
|
| 1145 |
+
env['HTTP_USER_AGENT'] = ua
|
| 1146 |
+
co = filter(None, self.headers.get_all('cookie', []))
|
| 1147 |
+
cookie_str = ', '.join(co)
|
| 1148 |
+
if cookie_str:
|
| 1149 |
+
env['HTTP_COOKIE'] = cookie_str
|
| 1150 |
+
# XXX Other HTTP_* headers
|
| 1151 |
+
# Since we're setting the env in the parent, provide empty
|
| 1152 |
+
# values to override previously set values
|
| 1153 |
+
for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
|
| 1154 |
+
'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
|
| 1155 |
+
env.setdefault(k, "")
|
| 1156 |
+
|
| 1157 |
+
self.send_response(HTTPStatus.OK, "Script output follows")
|
| 1158 |
+
self.flush_headers()
|
| 1159 |
+
|
| 1160 |
+
decoded_query = query.replace('+', ' ')
|
| 1161 |
+
|
| 1162 |
+
if self.have_fork:
|
| 1163 |
+
# Unix -- fork as we should
|
| 1164 |
+
args = [script]
|
| 1165 |
+
if '=' not in decoded_query:
|
| 1166 |
+
args.append(decoded_query)
|
| 1167 |
+
nobody = nobody_uid()
|
| 1168 |
+
self.wfile.flush() # Always flush before forking
|
| 1169 |
+
pid = os.fork()
|
| 1170 |
+
if pid != 0:
|
| 1171 |
+
# Parent
|
| 1172 |
+
pid, sts = os.waitpid(pid, 0)
|
| 1173 |
+
# throw away additional data [see bug #427345]
|
| 1174 |
+
while select.select([self.rfile], [], [], 0)[0]:
|
| 1175 |
+
if not self.rfile.read(1):
|
| 1176 |
+
break
|
| 1177 |
+
exitcode = os.waitstatus_to_exitcode(sts)
|
| 1178 |
+
if exitcode:
|
| 1179 |
+
self.log_error(f"CGI script exit code {exitcode}")
|
| 1180 |
+
return
|
| 1181 |
+
# Child
|
| 1182 |
+
try:
|
| 1183 |
+
try:
|
| 1184 |
+
os.setuid(nobody)
|
| 1185 |
+
except OSError:
|
| 1186 |
+
pass
|
| 1187 |
+
os.dup2(self.rfile.fileno(), 0)
|
| 1188 |
+
os.dup2(self.wfile.fileno(), 1)
|
| 1189 |
+
os.execve(scriptfile, args, env)
|
| 1190 |
+
except:
|
| 1191 |
+
self.server.handle_error(self.request, self.client_address)
|
| 1192 |
+
os._exit(127)
|
| 1193 |
+
|
| 1194 |
+
else:
|
| 1195 |
+
# Non-Unix -- use subprocess
|
| 1196 |
+
import subprocess
|
| 1197 |
+
cmdline = [scriptfile]
|
| 1198 |
+
if self.is_python(scriptfile):
|
| 1199 |
+
interp = sys.executable
|
| 1200 |
+
if interp.lower().endswith("w.exe"):
|
| 1201 |
+
# On Windows, use python.exe, not pythonw.exe
|
| 1202 |
+
interp = interp[:-5] + interp[-4:]
|
| 1203 |
+
cmdline = [interp, '-u'] + cmdline
|
| 1204 |
+
if '=' not in query:
|
| 1205 |
+
cmdline.append(query)
|
| 1206 |
+
self.log_message("command: %s", subprocess.list2cmdline(cmdline))
|
| 1207 |
+
try:
|
| 1208 |
+
nbytes = int(length)
|
| 1209 |
+
except (TypeError, ValueError):
|
| 1210 |
+
nbytes = 0
|
| 1211 |
+
p = subprocess.Popen(cmdline,
|
| 1212 |
+
stdin=subprocess.PIPE,
|
| 1213 |
+
stdout=subprocess.PIPE,
|
| 1214 |
+
stderr=subprocess.PIPE,
|
| 1215 |
+
env = env
|
| 1216 |
+
)
|
| 1217 |
+
if self.command.lower() == "post" and nbytes > 0:
|
| 1218 |
+
data = self.rfile.read(nbytes)
|
| 1219 |
+
else:
|
| 1220 |
+
data = None
|
| 1221 |
+
# throw away additional data [see bug #427345]
|
| 1222 |
+
while select.select([self.rfile._sock], [], [], 0)[0]:
|
| 1223 |
+
if not self.rfile._sock.recv(1):
|
| 1224 |
+
break
|
| 1225 |
+
stdout, stderr = p.communicate(data)
|
| 1226 |
+
self.wfile.write(stdout)
|
| 1227 |
+
if stderr:
|
| 1228 |
+
self.log_error('%s', stderr)
|
| 1229 |
+
p.stderr.close()
|
| 1230 |
+
p.stdout.close()
|
| 1231 |
+
status = p.returncode
|
| 1232 |
+
if status:
|
| 1233 |
+
self.log_error("CGI script exit status %#x", status)
|
| 1234 |
+
else:
|
| 1235 |
+
self.log_message("CGI script exited OK")
|
| 1236 |
+
|
| 1237 |
+
|
| 1238 |
+
def _get_best_family(*address):
|
| 1239 |
+
infos = socket.getaddrinfo(
|
| 1240 |
+
*address,
|
| 1241 |
+
type=socket.SOCK_STREAM,
|
| 1242 |
+
flags=socket.AI_PASSIVE,
|
| 1243 |
+
)
|
| 1244 |
+
family, type, proto, canonname, sockaddr = next(iter(infos))
|
| 1245 |
+
return family, sockaddr
|
| 1246 |
+
|
| 1247 |
+
|
| 1248 |
+
def test(HandlerClass=BaseHTTPRequestHandler,
|
| 1249 |
+
ServerClass=ThreadingHTTPServer,
|
| 1250 |
+
protocol="HTTP/1.0", port=8000, bind=None):
|
| 1251 |
+
"""Test the HTTP request handler class.
|
| 1252 |
+
|
| 1253 |
+
This runs an HTTP server on port 8000 (or the port argument).
|
| 1254 |
+
|
| 1255 |
+
"""
|
| 1256 |
+
ServerClass.address_family, addr = _get_best_family(bind, port)
|
| 1257 |
+
HandlerClass.protocol_version = protocol
|
| 1258 |
+
with ServerClass(addr, HandlerClass) as httpd:
|
| 1259 |
+
host, port = httpd.socket.getsockname()[:2]
|
| 1260 |
+
url_host = f'[{host}]' if ':' in host else host
|
| 1261 |
+
print(
|
| 1262 |
+
f"Serving HTTP on {host} port {port} "
|
| 1263 |
+
f"(http://{url_host}:{port}/) ..."
|
| 1264 |
+
)
|
| 1265 |
+
try:
|
| 1266 |
+
httpd.serve_forever()
|
| 1267 |
+
except KeyboardInterrupt:
|
| 1268 |
+
print("\nKeyboard interrupt received, exiting.")
|
| 1269 |
+
sys.exit(0)
|
| 1270 |
+
|
| 1271 |
+
if __name__ == '__main__':
|
| 1272 |
+
import argparse
|
| 1273 |
+
import contextlib
|
| 1274 |
+
|
| 1275 |
+
parser = argparse.ArgumentParser()
|
| 1276 |
+
parser.add_argument('--cgi', action='store_true',
|
| 1277 |
+
help='run as CGI server')
|
| 1278 |
+
parser.add_argument('--bind', '-b', metavar='ADDRESS',
|
| 1279 |
+
help='specify alternate bind address '
|
| 1280 |
+
'(default: all interfaces)')
|
| 1281 |
+
parser.add_argument('--directory', '-d', default=os.getcwd(),
|
| 1282 |
+
help='specify alternate directory '
|
| 1283 |
+
'(default: current directory)')
|
| 1284 |
+
parser.add_argument('port', action='store', default=8000, type=int,
|
| 1285 |
+
nargs='?',
|
| 1286 |
+
help='specify alternate port (default: 8000)')
|
| 1287 |
+
args = parser.parse_args()
|
| 1288 |
+
if args.cgi:
|
| 1289 |
+
handler_class = CGIHTTPRequestHandler
|
| 1290 |
+
else:
|
| 1291 |
+
handler_class = SimpleHTTPRequestHandler
|
| 1292 |
+
|
| 1293 |
+
# ensure dual-stack is not disabled; ref #38907
|
| 1294 |
+
class DualStackServer(ThreadingHTTPServer):
|
| 1295 |
+
|
| 1296 |
+
def server_bind(self):
|
| 1297 |
+
# suppress exception when protocol is IPv4
|
| 1298 |
+
with contextlib.suppress(Exception):
|
| 1299 |
+
self.socket.setsockopt(
|
| 1300 |
+
socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
|
| 1301 |
+
return super().server_bind()
|
| 1302 |
+
|
| 1303 |
+
def finish_request(self, request, client_address):
|
| 1304 |
+
self.RequestHandlerClass(request, client_address, self,
|
| 1305 |
+
directory=args.directory)
|
| 1306 |
+
|
| 1307 |
+
test(
|
| 1308 |
+
HandlerClass=handler_class,
|
| 1309 |
+
ServerClass=DualStackServer,
|
| 1310 |
+
port=args.port,
|
| 1311 |
+
bind=args.bind,
|
| 1312 |
+
)
|
evalkit_llava/lib/python3.10/site-packages/setuptools/_vendor/more_itertools/__pycache__/more.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a29978deee94c64619445fc042926f0fe515aafecb26d5e071b5df8adfcaa49d
|
| 3 |
+
size 138269
|
evalkit_llava/lib/python3.10/venv/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (17.6 kB). View file
|
|
|
evalkit_llava/lib/python3.10/venv/scripts/posix/activate.csh
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file must be used with "source bin/activate.csh" *from csh*.
|
| 2 |
+
# You cannot run it directly.
|
| 3 |
+
# Created by Davide Di Blasi <[email protected]>.
|
| 4 |
+
# Ported to Python 3.3 venv by Andrew Svetlov <[email protected]>
|
| 5 |
+
|
| 6 |
+
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate'
|
| 7 |
+
|
| 8 |
+
# Unset irrelevant variables.
|
| 9 |
+
deactivate nondestructive
|
| 10 |
+
|
| 11 |
+
setenv VIRTUAL_ENV __VENV_DIR__
|
| 12 |
+
|
| 13 |
+
set _OLD_VIRTUAL_PATH="$PATH"
|
| 14 |
+
setenv PATH "$VIRTUAL_ENV/"__VENV_BIN_NAME__":$PATH"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
set _OLD_VIRTUAL_PROMPT="$prompt"
|
| 18 |
+
|
| 19 |
+
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
|
| 20 |
+
set prompt = __VENV_PROMPT__"$prompt"
|
| 21 |
+
setenv VIRTUAL_ENV_PROMPT __VENV_PROMPT__
|
| 22 |
+
endif
|
| 23 |
+
|
| 24 |
+
alias pydoc python -m pydoc
|
| 25 |
+
|
| 26 |
+
rehash
|
evalkit_llava/lib/python3.10/wsgiref/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""wsgiref -- a WSGI (PEP 3333) Reference Library
|
| 2 |
+
|
| 3 |
+
Current Contents:
|
| 4 |
+
|
| 5 |
+
* util -- Miscellaneous useful functions and wrappers
|
| 6 |
+
|
| 7 |
+
* headers -- Manage response headers
|
| 8 |
+
|
| 9 |
+
* handlers -- base classes for server/gateway implementations
|
| 10 |
+
|
| 11 |
+
* simple_server -- a simple BaseHTTPServer that supports WSGI
|
| 12 |
+
|
| 13 |
+
* validate -- validation wrapper that sits between an app and a server
|
| 14 |
+
to detect errors in either
|
| 15 |
+
|
| 16 |
+
To-Do:
|
| 17 |
+
|
| 18 |
+
* cgi_gateway -- Run WSGI apps under CGI (pending a deployment standard)
|
| 19 |
+
|
| 20 |
+
* cgi_wrapper -- Run CGI apps under WSGI
|
| 21 |
+
|
| 22 |
+
* router -- a simple middleware component that handles URL traversal
|
| 23 |
+
"""
|
evalkit_llava/lib/python3.10/wsgiref/simple_server.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""BaseHTTPServer that implements the Python WSGI protocol (PEP 3333)
|
| 2 |
+
|
| 3 |
+
This is both an example of how WSGI can be implemented, and a basis for running
|
| 4 |
+
simple web applications on a local machine, such as might be done when testing
|
| 5 |
+
or debugging an application. It has not been reviewed for security issues,
|
| 6 |
+
however, and we strongly recommend that you use a "real" web server for
|
| 7 |
+
production use.
|
| 8 |
+
|
| 9 |
+
For example usage, see the 'if __name__=="__main__"' block at the end of the
|
| 10 |
+
module. See also the BaseHTTPServer module docs for other API information.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 14 |
+
import sys
|
| 15 |
+
import urllib.parse
|
| 16 |
+
from wsgiref.handlers import SimpleHandler
|
| 17 |
+
from platform import python_implementation
|
| 18 |
+
|
| 19 |
+
__version__ = "0.2"
|
| 20 |
+
__all__ = ['WSGIServer', 'WSGIRequestHandler', 'demo_app', 'make_server']
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
server_version = "WSGIServer/" + __version__
|
| 24 |
+
sys_version = python_implementation() + "/" + sys.version.split()[0]
|
| 25 |
+
software_version = server_version + ' ' + sys_version
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class ServerHandler(SimpleHandler):
|
| 29 |
+
|
| 30 |
+
server_software = software_version
|
| 31 |
+
|
| 32 |
+
def close(self):
|
| 33 |
+
try:
|
| 34 |
+
self.request_handler.log_request(
|
| 35 |
+
self.status.split(' ',1)[0], self.bytes_sent
|
| 36 |
+
)
|
| 37 |
+
finally:
|
| 38 |
+
SimpleHandler.close(self)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class WSGIServer(HTTPServer):
|
| 43 |
+
|
| 44 |
+
"""BaseHTTPServer that implements the Python WSGI protocol"""
|
| 45 |
+
|
| 46 |
+
application = None
|
| 47 |
+
|
| 48 |
+
def server_bind(self):
|
| 49 |
+
"""Override server_bind to store the server name."""
|
| 50 |
+
HTTPServer.server_bind(self)
|
| 51 |
+
self.setup_environ()
|
| 52 |
+
|
| 53 |
+
def setup_environ(self):
|
| 54 |
+
# Set up base environment
|
| 55 |
+
env = self.base_environ = {}
|
| 56 |
+
env['SERVER_NAME'] = self.server_name
|
| 57 |
+
env['GATEWAY_INTERFACE'] = 'CGI/1.1'
|
| 58 |
+
env['SERVER_PORT'] = str(self.server_port)
|
| 59 |
+
env['REMOTE_HOST']=''
|
| 60 |
+
env['CONTENT_LENGTH']=''
|
| 61 |
+
env['SCRIPT_NAME'] = ''
|
| 62 |
+
|
| 63 |
+
def get_app(self):
|
| 64 |
+
return self.application
|
| 65 |
+
|
| 66 |
+
def set_app(self,application):
|
| 67 |
+
self.application = application
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class WSGIRequestHandler(BaseHTTPRequestHandler):
|
| 72 |
+
|
| 73 |
+
server_version = "WSGIServer/" + __version__
|
| 74 |
+
|
| 75 |
+
def get_environ(self):
|
| 76 |
+
env = self.server.base_environ.copy()
|
| 77 |
+
env['SERVER_PROTOCOL'] = self.request_version
|
| 78 |
+
env['SERVER_SOFTWARE'] = self.server_version
|
| 79 |
+
env['REQUEST_METHOD'] = self.command
|
| 80 |
+
if '?' in self.path:
|
| 81 |
+
path,query = self.path.split('?',1)
|
| 82 |
+
else:
|
| 83 |
+
path,query = self.path,''
|
| 84 |
+
|
| 85 |
+
env['PATH_INFO'] = urllib.parse.unquote(path, 'iso-8859-1')
|
| 86 |
+
env['QUERY_STRING'] = query
|
| 87 |
+
|
| 88 |
+
host = self.address_string()
|
| 89 |
+
if host != self.client_address[0]:
|
| 90 |
+
env['REMOTE_HOST'] = host
|
| 91 |
+
env['REMOTE_ADDR'] = self.client_address[0]
|
| 92 |
+
|
| 93 |
+
if self.headers.get('content-type') is None:
|
| 94 |
+
env['CONTENT_TYPE'] = self.headers.get_content_type()
|
| 95 |
+
else:
|
| 96 |
+
env['CONTENT_TYPE'] = self.headers['content-type']
|
| 97 |
+
|
| 98 |
+
length = self.headers.get('content-length')
|
| 99 |
+
if length:
|
| 100 |
+
env['CONTENT_LENGTH'] = length
|
| 101 |
+
|
| 102 |
+
for k, v in self.headers.items():
|
| 103 |
+
k=k.replace('-','_').upper(); v=v.strip()
|
| 104 |
+
if k in env:
|
| 105 |
+
continue # skip content length, type,etc.
|
| 106 |
+
if 'HTTP_'+k in env:
|
| 107 |
+
env['HTTP_'+k] += ','+v # comma-separate multiple headers
|
| 108 |
+
else:
|
| 109 |
+
env['HTTP_'+k] = v
|
| 110 |
+
return env
|
| 111 |
+
|
| 112 |
+
def get_stderr(self):
|
| 113 |
+
return sys.stderr
|
| 114 |
+
|
| 115 |
+
def handle(self):
|
| 116 |
+
"""Handle a single HTTP request"""
|
| 117 |
+
|
| 118 |
+
self.raw_requestline = self.rfile.readline(65537)
|
| 119 |
+
if len(self.raw_requestline) > 65536:
|
| 120 |
+
self.requestline = ''
|
| 121 |
+
self.request_version = ''
|
| 122 |
+
self.command = ''
|
| 123 |
+
self.send_error(414)
|
| 124 |
+
return
|
| 125 |
+
|
| 126 |
+
if not self.parse_request(): # An error code has been sent, just exit
|
| 127 |
+
return
|
| 128 |
+
|
| 129 |
+
handler = ServerHandler(
|
| 130 |
+
self.rfile, self.wfile, self.get_stderr(), self.get_environ(),
|
| 131 |
+
multithread=False,
|
| 132 |
+
)
|
| 133 |
+
handler.request_handler = self # backpointer for logging
|
| 134 |
+
handler.run(self.server.get_app())
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def demo_app(environ,start_response):
|
| 139 |
+
from io import StringIO
|
| 140 |
+
stdout = StringIO()
|
| 141 |
+
print("Hello world!", file=stdout)
|
| 142 |
+
print(file=stdout)
|
| 143 |
+
h = sorted(environ.items())
|
| 144 |
+
for k,v in h:
|
| 145 |
+
print(k,'=',repr(v), file=stdout)
|
| 146 |
+
start_response("200 OK", [('Content-Type','text/plain; charset=utf-8')])
|
| 147 |
+
return [stdout.getvalue().encode("utf-8")]
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def make_server(
|
| 151 |
+
host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler
|
| 152 |
+
):
|
| 153 |
+
"""Create a new WSGI server listening on `host` and `port` for `app`"""
|
| 154 |
+
server = server_class((host, port), handler_class)
|
| 155 |
+
server.set_app(app)
|
| 156 |
+
return server
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
if __name__ == '__main__':
|
| 160 |
+
with make_server('', 8000, demo_app) as httpd:
|
| 161 |
+
sa = httpd.socket.getsockname()
|
| 162 |
+
print("Serving HTTP on", sa[0], "port", sa[1], "...")
|
| 163 |
+
import webbrowser
|
| 164 |
+
webbrowser.open('http://localhost:8000/xyz?abc')
|
| 165 |
+
httpd.handle_request() # serve one request, then exit
|
evalkit_llava/lib/python3.10/wsgiref/validate.py
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
|
| 2 |
+
# Licensed under the MIT license: https://opensource.org/licenses/mit-license.php
|
| 3 |
+
# Also licenced under the Apache License, 2.0: https://opensource.org/licenses/apache2.0.php
|
| 4 |
+
# Licensed to PSF under a Contributor Agreement
|
| 5 |
+
"""
|
| 6 |
+
Middleware to check for obedience to the WSGI specification.
|
| 7 |
+
|
| 8 |
+
Some of the things this checks:
|
| 9 |
+
|
| 10 |
+
* Signature of the application and start_response (including that
|
| 11 |
+
keyword arguments are not used).
|
| 12 |
+
|
| 13 |
+
* Environment checks:
|
| 14 |
+
|
| 15 |
+
- Environment is a dictionary (and not a subclass).
|
| 16 |
+
|
| 17 |
+
- That all the required keys are in the environment: REQUEST_METHOD,
|
| 18 |
+
SERVER_NAME, SERVER_PORT, wsgi.version, wsgi.input, wsgi.errors,
|
| 19 |
+
wsgi.multithread, wsgi.multiprocess, wsgi.run_once
|
| 20 |
+
|
| 21 |
+
- That HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH are not in the
|
| 22 |
+
environment (these headers should appear as CONTENT_LENGTH and
|
| 23 |
+
CONTENT_TYPE).
|
| 24 |
+
|
| 25 |
+
- Warns if QUERY_STRING is missing, as the cgi module acts
|
| 26 |
+
unpredictably in that case.
|
| 27 |
+
|
| 28 |
+
- That CGI-style variables (that don't contain a .) have
|
| 29 |
+
(non-unicode) string values
|
| 30 |
+
|
| 31 |
+
- That wsgi.version is a tuple
|
| 32 |
+
|
| 33 |
+
- That wsgi.url_scheme is 'http' or 'https' (@@: is this too
|
| 34 |
+
restrictive?)
|
| 35 |
+
|
| 36 |
+
- Warns if the REQUEST_METHOD is not known (@@: probably too
|
| 37 |
+
restrictive).
|
| 38 |
+
|
| 39 |
+
- That SCRIPT_NAME and PATH_INFO are empty or start with /
|
| 40 |
+
|
| 41 |
+
- That at least one of SCRIPT_NAME or PATH_INFO are set.
|
| 42 |
+
|
| 43 |
+
- That CONTENT_LENGTH is a positive integer.
|
| 44 |
+
|
| 45 |
+
- That SCRIPT_NAME is not '/' (it should be '', and PATH_INFO should
|
| 46 |
+
be '/').
|
| 47 |
+
|
| 48 |
+
- That wsgi.input has the methods read, readline, readlines, and
|
| 49 |
+
__iter__
|
| 50 |
+
|
| 51 |
+
- That wsgi.errors has the methods flush, write, writelines
|
| 52 |
+
|
| 53 |
+
* The status is a string, contains a space, starts with an integer,
|
| 54 |
+
and that integer is in range (> 100).
|
| 55 |
+
|
| 56 |
+
* That the headers is a list (not a subclass, not another kind of
|
| 57 |
+
sequence).
|
| 58 |
+
|
| 59 |
+
* That the items of the headers are tuples of strings.
|
| 60 |
+
|
| 61 |
+
* That there is no 'status' header (that is used in CGI, but not in
|
| 62 |
+
WSGI).
|
| 63 |
+
|
| 64 |
+
* That the headers don't contain newlines or colons, end in _ or -, or
|
| 65 |
+
contain characters codes below 037.
|
| 66 |
+
|
| 67 |
+
* That Content-Type is given if there is content (CGI often has a
|
| 68 |
+
default content type, but WSGI does not).
|
| 69 |
+
|
| 70 |
+
* That no Content-Type is given when there is no content (@@: is this
|
| 71 |
+
too restrictive?)
|
| 72 |
+
|
| 73 |
+
* That the exc_info argument to start_response is a tuple or None.
|
| 74 |
+
|
| 75 |
+
* That all calls to the writer are with strings, and no other methods
|
| 76 |
+
on the writer are accessed.
|
| 77 |
+
|
| 78 |
+
* That wsgi.input is used properly:
|
| 79 |
+
|
| 80 |
+
- .read() is called with exactly one argument
|
| 81 |
+
|
| 82 |
+
- That it returns a string
|
| 83 |
+
|
| 84 |
+
- That readline, readlines, and __iter__ return strings
|
| 85 |
+
|
| 86 |
+
- That .close() is not called
|
| 87 |
+
|
| 88 |
+
- No other methods are provided
|
| 89 |
+
|
| 90 |
+
* That wsgi.errors is used properly:
|
| 91 |
+
|
| 92 |
+
- .write() and .writelines() is called with a string
|
| 93 |
+
|
| 94 |
+
- That .close() is not called, and no other methods are provided.
|
| 95 |
+
|
| 96 |
+
* The response iterator:
|
| 97 |
+
|
| 98 |
+
- That it is not a string (it should be a list of a single string; a
|
| 99 |
+
string will work, but perform horribly).
|
| 100 |
+
|
| 101 |
+
- That .__next__() returns a string
|
| 102 |
+
|
| 103 |
+
- That the iterator is not iterated over until start_response has
|
| 104 |
+
been called (that can signal either a server or application
|
| 105 |
+
error).
|
| 106 |
+
|
| 107 |
+
- That .close() is called (doesn't raise exception, only prints to
|
| 108 |
+
sys.stderr, because we only know it isn't called when the object
|
| 109 |
+
is garbage collected).
|
| 110 |
+
"""
|
| 111 |
+
__all__ = ['validator']
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
import re
|
| 115 |
+
import sys
|
| 116 |
+
import warnings
|
| 117 |
+
|
| 118 |
+
header_re = re.compile(r'^[a-zA-Z][a-zA-Z0-9\-_]*$')
|
| 119 |
+
bad_header_value_re = re.compile(r'[\000-\037]')
|
| 120 |
+
|
| 121 |
+
class WSGIWarning(Warning):
|
| 122 |
+
"""
|
| 123 |
+
Raised in response to WSGI-spec-related warnings
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
def assert_(cond, *args):
|
| 127 |
+
if not cond:
|
| 128 |
+
raise AssertionError(*args)
|
| 129 |
+
|
| 130 |
+
def check_string_type(value, title):
|
| 131 |
+
if type (value) is str:
|
| 132 |
+
return value
|
| 133 |
+
raise AssertionError(
|
| 134 |
+
"{0} must be of type str (got {1})".format(title, repr(value)))
|
| 135 |
+
|
| 136 |
+
def validator(application):
|
| 137 |
+
|
| 138 |
+
"""
|
| 139 |
+
When applied between a WSGI server and a WSGI application, this
|
| 140 |
+
middleware will check for WSGI compliance on a number of levels.
|
| 141 |
+
This middleware does not modify the request or response in any
|
| 142 |
+
way, but will raise an AssertionError if anything seems off
|
| 143 |
+
(except for a failure to close the application iterator, which
|
| 144 |
+
will be printed to stderr -- there's no way to raise an exception
|
| 145 |
+
at that point).
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
def lint_app(*args, **kw):
|
| 149 |
+
assert_(len(args) == 2, "Two arguments required")
|
| 150 |
+
assert_(not kw, "No keyword arguments allowed")
|
| 151 |
+
environ, start_response = args
|
| 152 |
+
|
| 153 |
+
check_environ(environ)
|
| 154 |
+
|
| 155 |
+
# We use this to check if the application returns without
|
| 156 |
+
# calling start_response:
|
| 157 |
+
start_response_started = []
|
| 158 |
+
|
| 159 |
+
def start_response_wrapper(*args, **kw):
|
| 160 |
+
assert_(len(args) == 2 or len(args) == 3, (
|
| 161 |
+
"Invalid number of arguments: %s" % (args,)))
|
| 162 |
+
assert_(not kw, "No keyword arguments allowed")
|
| 163 |
+
status = args[0]
|
| 164 |
+
headers = args[1]
|
| 165 |
+
if len(args) == 3:
|
| 166 |
+
exc_info = args[2]
|
| 167 |
+
else:
|
| 168 |
+
exc_info = None
|
| 169 |
+
|
| 170 |
+
check_status(status)
|
| 171 |
+
check_headers(headers)
|
| 172 |
+
check_content_type(status, headers)
|
| 173 |
+
check_exc_info(exc_info)
|
| 174 |
+
|
| 175 |
+
start_response_started.append(None)
|
| 176 |
+
return WriteWrapper(start_response(*args))
|
| 177 |
+
|
| 178 |
+
environ['wsgi.input'] = InputWrapper(environ['wsgi.input'])
|
| 179 |
+
environ['wsgi.errors'] = ErrorWrapper(environ['wsgi.errors'])
|
| 180 |
+
|
| 181 |
+
iterator = application(environ, start_response_wrapper)
|
| 182 |
+
assert_(iterator is not None and iterator != False,
|
| 183 |
+
"The application must return an iterator, if only an empty list")
|
| 184 |
+
|
| 185 |
+
check_iterator(iterator)
|
| 186 |
+
|
| 187 |
+
return IteratorWrapper(iterator, start_response_started)
|
| 188 |
+
|
| 189 |
+
return lint_app
|
| 190 |
+
|
| 191 |
+
class InputWrapper:
|
| 192 |
+
|
| 193 |
+
def __init__(self, wsgi_input):
|
| 194 |
+
self.input = wsgi_input
|
| 195 |
+
|
| 196 |
+
def read(self, *args):
|
| 197 |
+
assert_(len(args) == 1)
|
| 198 |
+
v = self.input.read(*args)
|
| 199 |
+
assert_(type(v) is bytes)
|
| 200 |
+
return v
|
| 201 |
+
|
| 202 |
+
def readline(self, *args):
|
| 203 |
+
assert_(len(args) <= 1)
|
| 204 |
+
v = self.input.readline(*args)
|
| 205 |
+
assert_(type(v) is bytes)
|
| 206 |
+
return v
|
| 207 |
+
|
| 208 |
+
def readlines(self, *args):
|
| 209 |
+
assert_(len(args) <= 1)
|
| 210 |
+
lines = self.input.readlines(*args)
|
| 211 |
+
assert_(type(lines) is list)
|
| 212 |
+
for line in lines:
|
| 213 |
+
assert_(type(line) is bytes)
|
| 214 |
+
return lines
|
| 215 |
+
|
| 216 |
+
def __iter__(self):
|
| 217 |
+
while 1:
|
| 218 |
+
line = self.readline()
|
| 219 |
+
if not line:
|
| 220 |
+
return
|
| 221 |
+
yield line
|
| 222 |
+
|
| 223 |
+
def close(self):
|
| 224 |
+
assert_(0, "input.close() must not be called")
|
| 225 |
+
|
| 226 |
+
class ErrorWrapper:
|
| 227 |
+
|
| 228 |
+
def __init__(self, wsgi_errors):
|
| 229 |
+
self.errors = wsgi_errors
|
| 230 |
+
|
| 231 |
+
def write(self, s):
|
| 232 |
+
assert_(type(s) is str)
|
| 233 |
+
self.errors.write(s)
|
| 234 |
+
|
| 235 |
+
def flush(self):
|
| 236 |
+
self.errors.flush()
|
| 237 |
+
|
| 238 |
+
def writelines(self, seq):
|
| 239 |
+
for line in seq:
|
| 240 |
+
self.write(line)
|
| 241 |
+
|
| 242 |
+
def close(self):
|
| 243 |
+
assert_(0, "errors.close() must not be called")
|
| 244 |
+
|
| 245 |
+
class WriteWrapper:
|
| 246 |
+
|
| 247 |
+
def __init__(self, wsgi_writer):
|
| 248 |
+
self.writer = wsgi_writer
|
| 249 |
+
|
| 250 |
+
def __call__(self, s):
|
| 251 |
+
assert_(type(s) is bytes)
|
| 252 |
+
self.writer(s)
|
| 253 |
+
|
| 254 |
+
class PartialIteratorWrapper:
|
| 255 |
+
|
| 256 |
+
def __init__(self, wsgi_iterator):
|
| 257 |
+
self.iterator = wsgi_iterator
|
| 258 |
+
|
| 259 |
+
def __iter__(self):
|
| 260 |
+
# We want to make sure __iter__ is called
|
| 261 |
+
return IteratorWrapper(self.iterator, None)
|
| 262 |
+
|
| 263 |
+
class IteratorWrapper:
|
| 264 |
+
|
| 265 |
+
def __init__(self, wsgi_iterator, check_start_response):
|
| 266 |
+
self.original_iterator = wsgi_iterator
|
| 267 |
+
self.iterator = iter(wsgi_iterator)
|
| 268 |
+
self.closed = False
|
| 269 |
+
self.check_start_response = check_start_response
|
| 270 |
+
|
| 271 |
+
def __iter__(self):
|
| 272 |
+
return self
|
| 273 |
+
|
| 274 |
+
def __next__(self):
|
| 275 |
+
assert_(not self.closed,
|
| 276 |
+
"Iterator read after closed")
|
| 277 |
+
v = next(self.iterator)
|
| 278 |
+
if type(v) is not bytes:
|
| 279 |
+
assert_(False, "Iterator yielded non-bytestring (%r)" % (v,))
|
| 280 |
+
if self.check_start_response is not None:
|
| 281 |
+
assert_(self.check_start_response,
|
| 282 |
+
"The application returns and we started iterating over its body, but start_response has not yet been called")
|
| 283 |
+
self.check_start_response = None
|
| 284 |
+
return v
|
| 285 |
+
|
| 286 |
+
def close(self):
|
| 287 |
+
self.closed = True
|
| 288 |
+
if hasattr(self.original_iterator, 'close'):
|
| 289 |
+
self.original_iterator.close()
|
| 290 |
+
|
| 291 |
+
def __del__(self):
|
| 292 |
+
if not self.closed:
|
| 293 |
+
sys.stderr.write(
|
| 294 |
+
"Iterator garbage collected without being closed")
|
| 295 |
+
assert_(self.closed,
|
| 296 |
+
"Iterator garbage collected without being closed")
|
| 297 |
+
|
| 298 |
+
def check_environ(environ):
|
| 299 |
+
assert_(type(environ) is dict,
|
| 300 |
+
"Environment is not of the right type: %r (environment: %r)"
|
| 301 |
+
% (type(environ), environ))
|
| 302 |
+
|
| 303 |
+
for key in ['REQUEST_METHOD', 'SERVER_NAME', 'SERVER_PORT',
|
| 304 |
+
'wsgi.version', 'wsgi.input', 'wsgi.errors',
|
| 305 |
+
'wsgi.multithread', 'wsgi.multiprocess',
|
| 306 |
+
'wsgi.run_once']:
|
| 307 |
+
assert_(key in environ,
|
| 308 |
+
"Environment missing required key: %r" % (key,))
|
| 309 |
+
|
| 310 |
+
for key in ['HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH']:
|
| 311 |
+
assert_(key not in environ,
|
| 312 |
+
"Environment should not have the key: %s "
|
| 313 |
+
"(use %s instead)" % (key, key[5:]))
|
| 314 |
+
|
| 315 |
+
if 'QUERY_STRING' not in environ:
|
| 316 |
+
warnings.warn(
|
| 317 |
+
'QUERY_STRING is not in the WSGI environment; the cgi '
|
| 318 |
+
'module will use sys.argv when this variable is missing, '
|
| 319 |
+
'so application errors are more likely',
|
| 320 |
+
WSGIWarning)
|
| 321 |
+
|
| 322 |
+
for key in environ.keys():
|
| 323 |
+
if '.' in key:
|
| 324 |
+
# Extension, we don't care about its type
|
| 325 |
+
continue
|
| 326 |
+
assert_(type(environ[key]) is str,
|
| 327 |
+
"Environmental variable %s is not a string: %r (value: %r)"
|
| 328 |
+
% (key, type(environ[key]), environ[key]))
|
| 329 |
+
|
| 330 |
+
assert_(type(environ['wsgi.version']) is tuple,
|
| 331 |
+
"wsgi.version should be a tuple (%r)" % (environ['wsgi.version'],))
|
| 332 |
+
assert_(environ['wsgi.url_scheme'] in ('http', 'https'),
|
| 333 |
+
"wsgi.url_scheme unknown: %r" % environ['wsgi.url_scheme'])
|
| 334 |
+
|
| 335 |
+
check_input(environ['wsgi.input'])
|
| 336 |
+
check_errors(environ['wsgi.errors'])
|
| 337 |
+
|
| 338 |
+
# @@: these need filling out:
|
| 339 |
+
if environ['REQUEST_METHOD'] not in (
|
| 340 |
+
'GET', 'HEAD', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE', 'TRACE'):
|
| 341 |
+
warnings.warn(
|
| 342 |
+
"Unknown REQUEST_METHOD: %r" % environ['REQUEST_METHOD'],
|
| 343 |
+
WSGIWarning)
|
| 344 |
+
|
| 345 |
+
assert_(not environ.get('SCRIPT_NAME')
|
| 346 |
+
or environ['SCRIPT_NAME'].startswith('/'),
|
| 347 |
+
"SCRIPT_NAME doesn't start with /: %r" % environ['SCRIPT_NAME'])
|
| 348 |
+
assert_(not environ.get('PATH_INFO')
|
| 349 |
+
or environ['PATH_INFO'].startswith('/'),
|
| 350 |
+
"PATH_INFO doesn't start with /: %r" % environ['PATH_INFO'])
|
| 351 |
+
if environ.get('CONTENT_LENGTH'):
|
| 352 |
+
assert_(int(environ['CONTENT_LENGTH']) >= 0,
|
| 353 |
+
"Invalid CONTENT_LENGTH: %r" % environ['CONTENT_LENGTH'])
|
| 354 |
+
|
| 355 |
+
if not environ.get('SCRIPT_NAME'):
|
| 356 |
+
assert_('PATH_INFO' in environ,
|
| 357 |
+
"One of SCRIPT_NAME or PATH_INFO are required (PATH_INFO "
|
| 358 |
+
"should at least be '/' if SCRIPT_NAME is empty)")
|
| 359 |
+
assert_(environ.get('SCRIPT_NAME') != '/',
|
| 360 |
+
"SCRIPT_NAME cannot be '/'; it should instead be '', and "
|
| 361 |
+
"PATH_INFO should be '/'")
|
| 362 |
+
|
| 363 |
+
def check_input(wsgi_input):
|
| 364 |
+
for attr in ['read', 'readline', 'readlines', '__iter__']:
|
| 365 |
+
assert_(hasattr(wsgi_input, attr),
|
| 366 |
+
"wsgi.input (%r) doesn't have the attribute %s"
|
| 367 |
+
% (wsgi_input, attr))
|
| 368 |
+
|
| 369 |
+
def check_errors(wsgi_errors):
|
| 370 |
+
for attr in ['flush', 'write', 'writelines']:
|
| 371 |
+
assert_(hasattr(wsgi_errors, attr),
|
| 372 |
+
"wsgi.errors (%r) doesn't have the attribute %s"
|
| 373 |
+
% (wsgi_errors, attr))
|
| 374 |
+
|
| 375 |
+
def check_status(status):
|
| 376 |
+
status = check_string_type(status, "Status")
|
| 377 |
+
# Implicitly check that we can turn it into an integer:
|
| 378 |
+
status_code = status.split(None, 1)[0]
|
| 379 |
+
assert_(len(status_code) == 3,
|
| 380 |
+
"Status codes must be three characters: %r" % status_code)
|
| 381 |
+
status_int = int(status_code)
|
| 382 |
+
assert_(status_int >= 100, "Status code is invalid: %r" % status_int)
|
| 383 |
+
if len(status) < 4 or status[3] != ' ':
|
| 384 |
+
warnings.warn(
|
| 385 |
+
"The status string (%r) should be a three-digit integer "
|
| 386 |
+
"followed by a single space and a status explanation"
|
| 387 |
+
% status, WSGIWarning)
|
| 388 |
+
|
| 389 |
+
def check_headers(headers):
|
| 390 |
+
assert_(type(headers) is list,
|
| 391 |
+
"Headers (%r) must be of type list: %r"
|
| 392 |
+
% (headers, type(headers)))
|
| 393 |
+
for item in headers:
|
| 394 |
+
assert_(type(item) is tuple,
|
| 395 |
+
"Individual headers (%r) must be of type tuple: %r"
|
| 396 |
+
% (item, type(item)))
|
| 397 |
+
assert_(len(item) == 2)
|
| 398 |
+
name, value = item
|
| 399 |
+
name = check_string_type(name, "Header name")
|
| 400 |
+
value = check_string_type(value, "Header value")
|
| 401 |
+
assert_(name.lower() != 'status',
|
| 402 |
+
"The Status header cannot be used; it conflicts with CGI "
|
| 403 |
+
"script, and HTTP status is not given through headers "
|
| 404 |
+
"(value: %r)." % value)
|
| 405 |
+
assert_('\n' not in name and ':' not in name,
|
| 406 |
+
"Header names may not contain ':' or '\\n': %r" % name)
|
| 407 |
+
assert_(header_re.search(name), "Bad header name: %r" % name)
|
| 408 |
+
assert_(not name.endswith('-') and not name.endswith('_'),
|
| 409 |
+
"Names may not end in '-' or '_': %r" % name)
|
| 410 |
+
if bad_header_value_re.search(value):
|
| 411 |
+
assert_(0, "Bad header value: %r (bad char: %r)"
|
| 412 |
+
% (value, bad_header_value_re.search(value).group(0)))
|
| 413 |
+
|
| 414 |
+
def check_content_type(status, headers):
|
| 415 |
+
status = check_string_type(status, "Status")
|
| 416 |
+
code = int(status.split(None, 1)[0])
|
| 417 |
+
# @@: need one more person to verify this interpretation of RFC 2616
|
| 418 |
+
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
|
| 419 |
+
NO_MESSAGE_BODY = (204, 304)
|
| 420 |
+
for name, value in headers:
|
| 421 |
+
name = check_string_type(name, "Header name")
|
| 422 |
+
if name.lower() == 'content-type':
|
| 423 |
+
if code not in NO_MESSAGE_BODY:
|
| 424 |
+
return
|
| 425 |
+
assert_(0, ("Content-Type header found in a %s response, "
|
| 426 |
+
"which must not return content.") % code)
|
| 427 |
+
if code not in NO_MESSAGE_BODY:
|
| 428 |
+
assert_(0, "No Content-Type header found in headers (%s)" % headers)
|
| 429 |
+
|
| 430 |
+
def check_exc_info(exc_info):
|
| 431 |
+
assert_(exc_info is None or type(exc_info) is tuple,
|
| 432 |
+
"exc_info (%r) is not a tuple: %r" % (exc_info, type(exc_info)))
|
| 433 |
+
# More exc_info checks?
|
| 434 |
+
|
| 435 |
+
def check_iterator(iterator):
|
| 436 |
+
# Technically a bytestring is legal, which is why it's a really bad
|
| 437 |
+
# idea, because it may cause the response to be returned
|
| 438 |
+
# character-by-character
|
| 439 |
+
assert_(not isinstance(iterator, (str, bytes)),
|
| 440 |
+
"You should not return a string as your application iterator, "
|
| 441 |
+
"instead return a single-item list containing a bytestring.")
|
evalkit_llava/lib/sqlite3.44.2/pkgIndex.tcl
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- tcl -*-
|
| 2 |
+
# Tcl package index file, version 1.1
|
| 3 |
+
#
|
| 4 |
+
# Note sqlite*3* init specifically
|
| 5 |
+
#
|
| 6 |
+
if {[package vsatisfies [package provide Tcl] 9.0-]} {
|
| 7 |
+
package ifneeded sqlite3 3.44.2 \
|
| 8 |
+
[list load [file join $dir libtcl9sqlite3.44.2.so] Sqlite3]
|
| 9 |
+
} else {
|
| 10 |
+
package ifneeded sqlite3 3.44.2 \
|
| 11 |
+
[list load [file join $dir libsqlite3.44.2.so] Sqlite3]
|
| 12 |
+
}
|
evalkit_llava/lib/tcl8/8.4/platform-1.0.19.tm
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- tcl -*-
|
| 2 |
+
# ### ### ### ######### ######### #########
|
| 3 |
+
## Overview
|
| 4 |
+
|
| 5 |
+
# Heuristics to assemble a platform identifier from publicly available
|
| 6 |
+
# information. The identifier describes the platform of the currently
|
| 7 |
+
# running tcl shell. This is a mixture of the runtime environment and
|
| 8 |
+
# of build-time properties of the executable itself.
|
| 9 |
+
#
|
| 10 |
+
# Examples:
|
| 11 |
+
# <1> A tcl shell executing on a x86_64 processor, but having a
|
| 12 |
+
# wordsize of 4 was compiled for the x86 environment, i.e. 32
|
| 13 |
+
# bit, and loaded packages have to match that, and not the
|
| 14 |
+
# actual cpu.
|
| 15 |
+
#
|
| 16 |
+
# <2> The hp/solaris 32/64 bit builds of the core cannot be
|
| 17 |
+
# distinguished by looking at tcl_platform. As packages have to
|
| 18 |
+
# match the 32/64 information we have to look in more places. In
|
| 19 |
+
# this case we inspect the executable itself (magic numbers,
|
| 20 |
+
# i.e. fileutil::magic::filetype).
|
| 21 |
+
#
|
| 22 |
+
# The basic information used comes out of the 'os' and 'machine'
|
| 23 |
+
# entries of the 'tcl_platform' array. A number of general and
|
| 24 |
+
# os/machine specific transformation are applied to get a canonical
|
| 25 |
+
# result.
|
| 26 |
+
#
|
| 27 |
+
# General
|
| 28 |
+
# Only the first element of 'os' is used - we don't care whether we
|
| 29 |
+
# are on "Windows NT" or "Windows XP" or whatever.
|
| 30 |
+
#
|
| 31 |
+
# Machine specific
|
| 32 |
+
# % amd64 -> x86_64
|
| 33 |
+
# % arm* -> arm
|
| 34 |
+
# % sun4* -> sparc
|
| 35 |
+
# % ia32* -> ix86
|
| 36 |
+
# % intel -> ix86
|
| 37 |
+
# % i*86* -> ix86
|
| 38 |
+
# % Power* -> powerpc
|
| 39 |
+
# % x86_64 + wordSize 4 => x86 code
|
| 40 |
+
#
|
| 41 |
+
# OS specific
|
| 42 |
+
# % AIX are always powerpc machines
|
| 43 |
+
# % HP-UX 9000/800 etc means parisc
|
| 44 |
+
# % linux has to take glibc version into account
|
| 45 |
+
# % sunos -> solaris, and keep version number
|
| 46 |
+
#
|
| 47 |
+
# NOTE: A platform like linux glibc 2.3, which can use glibc 2.2 stuff
|
| 48 |
+
# has to provide all possible allowed platform identifiers when
|
| 49 |
+
# searching search. Ditto a solaris 2.8 platform can use solaris 2.6
|
| 50 |
+
# packages. Etc. This is handled by the other procedure, see below.
|
| 51 |
+
|
| 52 |
+
# ### ### ### ######### ######### #########
|
| 53 |
+
## Requirements
|
| 54 |
+
|
| 55 |
+
namespace eval ::platform {}
|
| 56 |
+
|
| 57 |
+
# ### ### ### ######### ######### #########
|
| 58 |
+
## Implementation
|
| 59 |
+
|
| 60 |
+
# -- platform::generic
|
| 61 |
+
#
|
| 62 |
+
# Assembles an identifier for the generic platform. It leaves out
|
| 63 |
+
# details like kernel version, libc version, etc.
|
| 64 |
+
|
| 65 |
+
proc ::platform::generic {} {
|
| 66 |
+
global tcl_platform
|
| 67 |
+
|
| 68 |
+
set plat [string tolower [lindex $tcl_platform(os) 0]]
|
| 69 |
+
set cpu $tcl_platform(machine)
|
| 70 |
+
|
| 71 |
+
switch -glob -- $cpu {
|
| 72 |
+
sun4* {
|
| 73 |
+
set cpu sparc
|
| 74 |
+
}
|
| 75 |
+
intel -
|
| 76 |
+
ia32* -
|
| 77 |
+
i*86* {
|
| 78 |
+
set cpu ix86
|
| 79 |
+
}
|
| 80 |
+
x86_64 {
|
| 81 |
+
if {$tcl_platform(wordSize) == 4} {
|
| 82 |
+
# See Example <1> at the top of this file.
|
| 83 |
+
set cpu ix86
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
ppc -
|
| 87 |
+
"Power*" {
|
| 88 |
+
set cpu powerpc
|
| 89 |
+
}
|
| 90 |
+
"arm*" {
|
| 91 |
+
set cpu arm
|
| 92 |
+
}
|
| 93 |
+
ia64 {
|
| 94 |
+
if {$tcl_platform(wordSize) == 4} {
|
| 95 |
+
append cpu _32
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
switch -glob -- $plat {
|
| 101 |
+
windows {
|
| 102 |
+
if {$tcl_platform(platform) == "unix"} {
|
| 103 |
+
set plat cygwin
|
| 104 |
+
} else {
|
| 105 |
+
set plat win32
|
| 106 |
+
}
|
| 107 |
+
if {$cpu eq "amd64"} {
|
| 108 |
+
# Do not check wordSize, win32-x64 is an IL32P64 platform.
|
| 109 |
+
set cpu x86_64
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
sunos {
|
| 113 |
+
set plat solaris
|
| 114 |
+
if {[string match "ix86" $cpu]} {
|
| 115 |
+
if {$tcl_platform(wordSize) == 8} {
|
| 116 |
+
set cpu x86_64
|
| 117 |
+
}
|
| 118 |
+
} elseif {![string match "ia64*" $cpu]} {
|
| 119 |
+
# sparc
|
| 120 |
+
if {$tcl_platform(wordSize) == 8} {
|
| 121 |
+
append cpu 64
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
darwin {
|
| 126 |
+
set plat macosx
|
| 127 |
+
# Correctly identify the cpu when running as a 64bit
|
| 128 |
+
# process on a machine with a 32bit kernel
|
| 129 |
+
if {$cpu eq "ix86"} {
|
| 130 |
+
if {$tcl_platform(wordSize) == 8} {
|
| 131 |
+
set cpu x86_64
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
aix {
|
| 136 |
+
set cpu powerpc
|
| 137 |
+
if {$tcl_platform(wordSize) == 8} {
|
| 138 |
+
append cpu 64
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
hp-ux {
|
| 142 |
+
set plat hpux
|
| 143 |
+
if {![string match "ia64*" $cpu]} {
|
| 144 |
+
set cpu parisc
|
| 145 |
+
if {$tcl_platform(wordSize) == 8} {
|
| 146 |
+
append cpu 64
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
}
|
| 150 |
+
osf1 {
|
| 151 |
+
set plat tru64
|
| 152 |
+
}
|
| 153 |
+
default {
|
| 154 |
+
set plat [lindex [split $plat _-] 0]
|
| 155 |
+
}
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
return "${plat}-${cpu}"
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
# -- platform::identify
|
| 162 |
+
#
|
| 163 |
+
# Assembles an identifier for the exact platform, by extending the
|
| 164 |
+
# generic identifier. I.e. it adds in details like kernel version,
|
| 165 |
+
# libc version, etc., if they are relevant for the loading of
|
| 166 |
+
# packages on the platform.
|
| 167 |
+
|
| 168 |
+
proc ::platform::identify {} {
|
| 169 |
+
global tcl_platform
|
| 170 |
+
|
| 171 |
+
set id [generic]
|
| 172 |
+
regexp {^([^-]+)-([^-]+)$} $id -> plat cpu
|
| 173 |
+
|
| 174 |
+
switch -- $plat {
|
| 175 |
+
solaris {
|
| 176 |
+
regsub {^5} $tcl_platform(osVersion) 2 text
|
| 177 |
+
append plat $text
|
| 178 |
+
return "${plat}-${cpu}"
|
| 179 |
+
}
|
| 180 |
+
macosx {
|
| 181 |
+
set major [lindex [split $tcl_platform(osVersion) .] 0]
|
| 182 |
+
if {$major > 19} {
|
| 183 |
+
set minor [lindex [split $tcl_platform(osVersion) .] 1]
|
| 184 |
+
incr major -9
|
| 185 |
+
append plat $major.[expr {$minor - 1}]
|
| 186 |
+
} else {
|
| 187 |
+
incr major -4
|
| 188 |
+
append plat 10.$major
|
| 189 |
+
return "${plat}-${cpu}"
|
| 190 |
+
}
|
| 191 |
+
return "${plat}-${cpu}"
|
| 192 |
+
}
|
| 193 |
+
linux {
|
| 194 |
+
# Look for the libc*.so and determine its version
|
| 195 |
+
# (libc5/6, libc6 further glibc 2.X)
|
| 196 |
+
|
| 197 |
+
set v unknown
|
| 198 |
+
|
| 199 |
+
# Determine in which directory to look. /lib, or /lib64.
|
| 200 |
+
# For that we use the tcl_platform(wordSize).
|
| 201 |
+
#
|
| 202 |
+
# We could use the 'cpu' info, per the equivalence below,
|
| 203 |
+
# that however would be restricted to intel. And this may
|
| 204 |
+
# be a arm, mips, etc. system. The wordsize is more
|
| 205 |
+
# fundamental.
|
| 206 |
+
#
|
| 207 |
+
# ix86 <=> (wordSize == 4) <=> 32 bit ==> /lib
|
| 208 |
+
# x86_64 <=> (wordSize == 8) <=> 64 bit ==> /lib64
|
| 209 |
+
#
|
| 210 |
+
# Do not look into /lib64 even if present, if the cpu
|
| 211 |
+
# doesn't fit.
|
| 212 |
+
|
| 213 |
+
# TODO: Determine the prefixes (i386, x86_64, ...) for
|
| 214 |
+
# other cpus. The path after the generic one is utterly
|
| 215 |
+
# specific to intel right now. Ok, on Ubuntu, possibly
|
| 216 |
+
# other Debian systems we may apparently be able to query
|
| 217 |
+
# the necessary CPU code. If we can't we simply use the
|
| 218 |
+
# hardwired fallback.
|
| 219 |
+
|
| 220 |
+
switch -exact -- $tcl_platform(wordSize) {
|
| 221 |
+
4 {
|
| 222 |
+
lappend bases /lib
|
| 223 |
+
if {[catch {
|
| 224 |
+
exec dpkg-architecture -qDEB_HOST_MULTIARCH
|
| 225 |
+
} res]} {
|
| 226 |
+
lappend bases /lib/i386-linux-gnu
|
| 227 |
+
} else {
|
| 228 |
+
# dpkg-arch returns the full tripled, not just cpu.
|
| 229 |
+
lappend bases /lib/$res
|
| 230 |
+
}
|
| 231 |
+
}
|
| 232 |
+
8 {
|
| 233 |
+
lappend bases /lib64
|
| 234 |
+
if {[catch {
|
| 235 |
+
exec dpkg-architecture -qDEB_HOST_MULTIARCH
|
| 236 |
+
} res]} {
|
| 237 |
+
lappend bases /lib/x86_64-linux-gnu
|
| 238 |
+
} else {
|
| 239 |
+
# dpkg-arch returns the full tripled, not just cpu.
|
| 240 |
+
lappend bases /lib/$res
|
| 241 |
+
}
|
| 242 |
+
}
|
| 243 |
+
default {
|
| 244 |
+
return -code error "Bad wordSize $tcl_platform(wordSize), expected 4 or 8"
|
| 245 |
+
}
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
foreach base $bases {
|
| 249 |
+
if {[LibcVersion $base -> v]} break
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
append plat -$v
|
| 253 |
+
return "${plat}-${cpu}"
|
| 254 |
+
}
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
return $id
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
proc ::platform::LibcVersion {base _->_ vv} {
|
| 261 |
+
upvar 1 $vv v
|
| 262 |
+
set libclist [lsort [glob -nocomplain -directory $base libc*]]
|
| 263 |
+
|
| 264 |
+
if {![llength $libclist]} { return 0 }
|
| 265 |
+
|
| 266 |
+
set libc [lindex $libclist 0]
|
| 267 |
+
|
| 268 |
+
# Try executing the library first. This should succeed
|
| 269 |
+
# for a glibc library, and return the version
|
| 270 |
+
# information.
|
| 271 |
+
|
| 272 |
+
if {![catch {
|
| 273 |
+
set vdata [lindex [split [exec $libc] \n] 0]
|
| 274 |
+
}]} {
|
| 275 |
+
regexp {version ([0-9]+(\.[0-9]+)*)} $vdata -> v
|
| 276 |
+
foreach {major minor} [split $v .] break
|
| 277 |
+
set v glibc${major}.${minor}
|
| 278 |
+
return 1
|
| 279 |
+
} else {
|
| 280 |
+
# We had trouble executing the library. We are now
|
| 281 |
+
# inspecting its name to determine the version
|
| 282 |
+
# number. This code by Larry McVoy.
|
| 283 |
+
|
| 284 |
+
if {[regexp -- {libc-([0-9]+)\.([0-9]+)} $libc -> major minor]} {
|
| 285 |
+
set v glibc${major}.${minor}
|
| 286 |
+
return 1
|
| 287 |
+
}
|
| 288 |
+
}
|
| 289 |
+
return 0
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
# -- platform::patterns
|
| 293 |
+
#
|
| 294 |
+
# Given an exact platform identifier, i.e. _not_ the generic
|
| 295 |
+
# identifier it assembles a list of exact platform identifier
|
| 296 |
+
# describing platform which should be compatible with the
|
| 297 |
+
# input.
|
| 298 |
+
#
|
| 299 |
+
# I.e. packages for all platforms in the result list should be
|
| 300 |
+
# loadable on the specified platform.
|
| 301 |
+
|
| 302 |
+
# << Should we add the generic identifier to the list as well ? In
|
| 303 |
+
# general it is not compatible I believe. So better not. In many
|
| 304 |
+
# cases the exact identifier is identical to the generic one
|
| 305 |
+
# anyway.
|
| 306 |
+
# >>
|
| 307 |
+
|
| 308 |
+
proc ::platform::patterns {id} {
|
| 309 |
+
set res [list $id]
|
| 310 |
+
if {$id eq "tcl"} {return $res}
|
| 311 |
+
|
| 312 |
+
switch -glob -- $id {
|
| 313 |
+
solaris*-* {
|
| 314 |
+
if {[regexp {solaris([^-]*)-(.*)} $id -> v cpu]} {
|
| 315 |
+
if {$v eq ""} {return $id}
|
| 316 |
+
foreach {major minor} [split $v .] break
|
| 317 |
+
incr minor -1
|
| 318 |
+
for {set j $minor} {$j >= 6} {incr j -1} {
|
| 319 |
+
lappend res solaris${major}.${j}-${cpu}
|
| 320 |
+
}
|
| 321 |
+
}
|
| 322 |
+
}
|
| 323 |
+
linux*-* {
|
| 324 |
+
if {[regexp {linux-glibc([^-]*)-(.*)} $id -> v cpu]} {
|
| 325 |
+
foreach {major minor} [split $v .] break
|
| 326 |
+
incr minor -1
|
| 327 |
+
for {set j $minor} {$j >= 0} {incr j -1} {
|
| 328 |
+
lappend res linux-glibc${major}.${j}-${cpu}
|
| 329 |
+
}
|
| 330 |
+
}
|
| 331 |
+
}
|
| 332 |
+
macosx-powerpc {
|
| 333 |
+
lappend res macosx-universal
|
| 334 |
+
}
|
| 335 |
+
macosx-x86_64 {
|
| 336 |
+
lappend res macosx-i386-x86_64
|
| 337 |
+
}
|
| 338 |
+
macosx-ix86 {
|
| 339 |
+
lappend res macosx-universal macosx-i386-x86_64
|
| 340 |
+
}
|
| 341 |
+
macosx*-* {
|
| 342 |
+
# 10.5+,11.0+
|
| 343 |
+
if {[regexp {macosx([^-]*)-(.*)} $id -> v cpu]} {
|
| 344 |
+
|
| 345 |
+
switch -exact -- $cpu {
|
| 346 |
+
ix86 {
|
| 347 |
+
lappend alt i386-x86_64
|
| 348 |
+
lappend alt universal
|
| 349 |
+
}
|
| 350 |
+
x86_64 {
|
| 351 |
+
if {[lindex [split $::tcl_platform(osVersion) .] 0] < 19} {
|
| 352 |
+
set alt i386-x86_64
|
| 353 |
+
} else {
|
| 354 |
+
set alt {}
|
| 355 |
+
}
|
| 356 |
+
}
|
| 357 |
+
arm {
|
| 358 |
+
lappend alt x86_64
|
| 359 |
+
}
|
| 360 |
+
default { set alt {} }
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
if {$v ne ""} {
|
| 364 |
+
foreach {major minor} [split $v .] break
|
| 365 |
+
|
| 366 |
+
set res {}
|
| 367 |
+
if {$major eq 13} {
|
| 368 |
+
# Add 13.0 to 13.minor to patterns.
|
| 369 |
+
for {set j $minor} {$j >= 0} {incr j -1} {
|
| 370 |
+
lappend res macosx${major}.${j}-${cpu}
|
| 371 |
+
foreach a $alt {
|
| 372 |
+
lappend res macosx${major}.${j}-$a
|
| 373 |
+
}
|
| 374 |
+
}
|
| 375 |
+
set major 12
|
| 376 |
+
set minor 5
|
| 377 |
+
}
|
| 378 |
+
if {$major eq 12} {
|
| 379 |
+
# Add 12.0 to 12.minor to patterns.
|
| 380 |
+
for {set j $minor} {$j >= 0} {incr j -1} {
|
| 381 |
+
lappend res macosx${major}.${j}-${cpu}
|
| 382 |
+
foreach a $alt {
|
| 383 |
+
lappend res macosx${major}.${j}-$a
|
| 384 |
+
}
|
| 385 |
+
}
|
| 386 |
+
set major 11
|
| 387 |
+
set minor 5
|
| 388 |
+
}
|
| 389 |
+
if {$major eq 11} {
|
| 390 |
+
# Add 11.0 to 11.minor to patterns.
|
| 391 |
+
for {set j $minor} {$j >= 0} {incr j -1} {
|
| 392 |
+
lappend res macosx${major}.${j}-${cpu}
|
| 393 |
+
foreach a $alt {
|
| 394 |
+
lappend res macosx${major}.${j}-$a
|
| 395 |
+
}
|
| 396 |
+
}
|
| 397 |
+
set major 10
|
| 398 |
+
set minor 15
|
| 399 |
+
}
|
| 400 |
+
# Add 10.5 to 10.minor to patterns.
|
| 401 |
+
for {set j $minor} {$j >= 5} {incr j -1} {
|
| 402 |
+
if {$cpu ne "arm"} {
|
| 403 |
+
lappend res macosx${major}.${j}-${cpu}
|
| 404 |
+
}
|
| 405 |
+
foreach a $alt {
|
| 406 |
+
lappend res macosx${major}.${j}-$a
|
| 407 |
+
}
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
# Add unversioned patterns for 10.3/10.4 builds.
|
| 411 |
+
lappend res macosx-${cpu}
|
| 412 |
+
foreach a $alt {
|
| 413 |
+
lappend res macosx-$a
|
| 414 |
+
}
|
| 415 |
+
} else {
|
| 416 |
+
# No version, just do unversioned patterns.
|
| 417 |
+
foreach a $alt {
|
| 418 |
+
lappend res macosx-$a
|
| 419 |
+
}
|
| 420 |
+
}
|
| 421 |
+
} else {
|
| 422 |
+
# no v, no cpu ... nothing
|
| 423 |
+
}
|
| 424 |
+
}
|
| 425 |
+
}
|
| 426 |
+
lappend res tcl ; # Pure tcl packages are always compatible.
|
| 427 |
+
return $res
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
# ### ### ### ######### ######### #########
|
| 432 |
+
## Ready
|
| 433 |
+
|
| 434 |
+
package provide platform 1.0.19
|
| 435 |
+
|
| 436 |
+
# ### ### ### ######### ######### #########
|
| 437 |
+
## Demo application
|
| 438 |
+
|
| 439 |
+
if {[info exists argv0] && ($argv0 eq [info script])} {
|
| 440 |
+
puts ====================================
|
| 441 |
+
parray tcl_platform
|
| 442 |
+
puts ====================================
|
| 443 |
+
puts Generic\ identification:\ [::platform::generic]
|
| 444 |
+
puts Exact\ identification:\ \ \ [::platform::identify]
|
| 445 |
+
puts ====================================
|
| 446 |
+
puts Search\ patterns:
|
| 447 |
+
puts *\ [join [::platform::patterns [::platform::identify]] \n*\ ]
|
| 448 |
+
puts ====================================
|
| 449 |
+
exit 0
|
| 450 |
+
}
|
evalkit_llava/lib/tcl8/8.4/platform/shell-1.1.4.tm
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# -*- tcl -*-
|
| 3 |
+
# ### ### ### ######### ######### #########
|
| 4 |
+
## Overview
|
| 5 |
+
|
| 6 |
+
# Higher-level commands which invoke the functionality of this package
|
| 7 |
+
# for an arbitrary tcl shell (tclsh, wish, ...). This is required by a
|
| 8 |
+
# repository as while the tcl shell executing packages uses the same
|
| 9 |
+
# platform in general as a repository application there can be
|
| 10 |
+
# differences in detail (i.e. 32/64 bit builds).
|
| 11 |
+
|
| 12 |
+
# ### ### ### ######### ######### #########
|
| 13 |
+
## Requirements
|
| 14 |
+
|
| 15 |
+
package require platform
|
| 16 |
+
namespace eval ::platform::shell {}
|
| 17 |
+
|
| 18 |
+
# ### ### ### ######### ######### #########
|
| 19 |
+
## Implementation
|
| 20 |
+
|
| 21 |
+
# -- platform::shell::generic
|
| 22 |
+
|
| 23 |
+
proc ::platform::shell::generic {shell} {
|
| 24 |
+
# Argument is the path to a tcl shell.
|
| 25 |
+
|
| 26 |
+
CHECK $shell
|
| 27 |
+
LOCATE base out
|
| 28 |
+
|
| 29 |
+
set code {}
|
| 30 |
+
# Forget any preexisting platform package, it might be in
|
| 31 |
+
# conflict with this one.
|
| 32 |
+
lappend code {package forget platform}
|
| 33 |
+
# Inject our platform package
|
| 34 |
+
lappend code [list source $base]
|
| 35 |
+
# Query and print the architecture
|
| 36 |
+
lappend code {puts [platform::generic]}
|
| 37 |
+
# And done
|
| 38 |
+
lappend code {exit 0}
|
| 39 |
+
|
| 40 |
+
set arch [RUN $shell [join $code \n]]
|
| 41 |
+
|
| 42 |
+
if {$out} {file delete -force $base}
|
| 43 |
+
return $arch
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
# -- platform::shell::identify
|
| 47 |
+
|
| 48 |
+
proc ::platform::shell::identify {shell} {
|
| 49 |
+
# Argument is the path to a tcl shell.
|
| 50 |
+
|
| 51 |
+
CHECK $shell
|
| 52 |
+
LOCATE base out
|
| 53 |
+
|
| 54 |
+
set code {}
|
| 55 |
+
# Forget any preexisting platform package, it might be in
|
| 56 |
+
# conflict with this one.
|
| 57 |
+
lappend code {package forget platform}
|
| 58 |
+
# Inject our platform package
|
| 59 |
+
lappend code [list source $base]
|
| 60 |
+
# Query and print the architecture
|
| 61 |
+
lappend code {puts [platform::identify]}
|
| 62 |
+
# And done
|
| 63 |
+
lappend code {exit 0}
|
| 64 |
+
|
| 65 |
+
set arch [RUN $shell [join $code \n]]
|
| 66 |
+
|
| 67 |
+
if {$out} {file delete -force $base}
|
| 68 |
+
return $arch
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
# -- platform::shell::platform
|
| 72 |
+
|
| 73 |
+
proc ::platform::shell::platform {shell} {
|
| 74 |
+
# Argument is the path to a tcl shell.
|
| 75 |
+
|
| 76 |
+
CHECK $shell
|
| 77 |
+
|
| 78 |
+
set code {}
|
| 79 |
+
lappend code {puts $tcl_platform(platform)}
|
| 80 |
+
lappend code {exit 0}
|
| 81 |
+
|
| 82 |
+
return [RUN $shell [join $code \n]]
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
# ### ### ### ######### ######### #########
|
| 86 |
+
## Internal helper commands.
|
| 87 |
+
|
| 88 |
+
proc ::platform::shell::CHECK {shell} {
|
| 89 |
+
if {![file exists $shell]} {
|
| 90 |
+
return -code error "Shell \"$shell\" does not exist"
|
| 91 |
+
}
|
| 92 |
+
if {![file executable $shell]} {
|
| 93 |
+
return -code error "Shell \"$shell\" is not executable (permissions)"
|
| 94 |
+
}
|
| 95 |
+
return
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
proc ::platform::shell::LOCATE {bv ov} {
|
| 99 |
+
upvar 1 $bv base $ov out
|
| 100 |
+
|
| 101 |
+
# Locate the platform package for injection into the specified
|
| 102 |
+
# shell. We are using package management to find it, wherever it
|
| 103 |
+
# is, instead of using hardwired relative paths. This allows us to
|
| 104 |
+
# install the two packages as TMs without breaking the code
|
| 105 |
+
# here. If the found package is wrapped we copy the code somewhere
|
| 106 |
+
# where the spawned shell will be able to read it.
|
| 107 |
+
|
| 108 |
+
# This code is brittle, it needs has to adapt to whatever changes
|
| 109 |
+
# are made to the TM code, i.e. the "provide" statement generated by
|
| 110 |
+
# tm.tcl
|
| 111 |
+
|
| 112 |
+
set pl [package ifneeded platform [package require platform]]
|
| 113 |
+
set base [lindex $pl end]
|
| 114 |
+
|
| 115 |
+
set out 0
|
| 116 |
+
if {[lindex [file system $base]] ne "native"} {
|
| 117 |
+
set temp [TEMP]
|
| 118 |
+
file copy -force $base $temp
|
| 119 |
+
set base $temp
|
| 120 |
+
set out 1
|
| 121 |
+
}
|
| 122 |
+
return
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
proc ::platform::shell::RUN {shell code} {
|
| 126 |
+
set c [TEMP]
|
| 127 |
+
set cc [open $c w]
|
| 128 |
+
puts $cc $code
|
| 129 |
+
close $cc
|
| 130 |
+
|
| 131 |
+
set e [TEMP]
|
| 132 |
+
|
| 133 |
+
set code [catch {
|
| 134 |
+
exec $shell $c 2> $e
|
| 135 |
+
} res]
|
| 136 |
+
|
| 137 |
+
file delete $c
|
| 138 |
+
|
| 139 |
+
if {$code} {
|
| 140 |
+
append res \n[read [set chan [open $e r]]][close $chan]
|
| 141 |
+
file delete $e
|
| 142 |
+
return -code error "Shell \"$shell\" is not executable ($res)"
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
file delete $e
|
| 146 |
+
return $res
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
proc ::platform::shell::TEMP {} {
|
| 150 |
+
set prefix platform
|
| 151 |
+
|
| 152 |
+
# This code is copied out of Tcllib's fileutil package.
|
| 153 |
+
# (TempFile/tempfile)
|
| 154 |
+
|
| 155 |
+
set tmpdir [DIR]
|
| 156 |
+
|
| 157 |
+
set chars "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
| 158 |
+
set nrand_chars 10
|
| 159 |
+
set maxtries 10
|
| 160 |
+
set access [list RDWR CREAT EXCL TRUNC]
|
| 161 |
+
set permission 0600
|
| 162 |
+
set channel ""
|
| 163 |
+
set checked_dir_writable 0
|
| 164 |
+
set mypid [pid]
|
| 165 |
+
for {set i 0} {$i < $maxtries} {incr i} {
|
| 166 |
+
set newname $prefix
|
| 167 |
+
for {set j 0} {$j < $nrand_chars} {incr j} {
|
| 168 |
+
append newname [string index $chars \
|
| 169 |
+
[expr {int(rand()*62)}]]
|
| 170 |
+
}
|
| 171 |
+
set newname [file join $tmpdir $newname]
|
| 172 |
+
if {[file exists $newname]} {
|
| 173 |
+
after 1
|
| 174 |
+
} else {
|
| 175 |
+
if {[catch {open $newname $access $permission} channel]} {
|
| 176 |
+
if {!$checked_dir_writable} {
|
| 177 |
+
set dirname [file dirname $newname]
|
| 178 |
+
if {![file writable $dirname]} {
|
| 179 |
+
return -code error "Directory $dirname is not writable"
|
| 180 |
+
}
|
| 181 |
+
set checked_dir_writable 1
|
| 182 |
+
}
|
| 183 |
+
} else {
|
| 184 |
+
# Success
|
| 185 |
+
close $channel
|
| 186 |
+
return [file normalize $newname]
|
| 187 |
+
}
|
| 188 |
+
}
|
| 189 |
+
}
|
| 190 |
+
if {$channel ne ""} {
|
| 191 |
+
return -code error "Failed to open a temporary file: $channel"
|
| 192 |
+
} else {
|
| 193 |
+
return -code error "Failed to find an unused temporary file name"
|
| 194 |
+
}
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
proc ::platform::shell::DIR {} {
|
| 198 |
+
# This code is copied out of Tcllib's fileutil package.
|
| 199 |
+
# (TempDir/tempdir)
|
| 200 |
+
|
| 201 |
+
global tcl_platform env
|
| 202 |
+
|
| 203 |
+
set attempdirs [list]
|
| 204 |
+
|
| 205 |
+
foreach tmp {TMPDIR TEMP TMP} {
|
| 206 |
+
if { [info exists env($tmp)] } {
|
| 207 |
+
lappend attempdirs $env($tmp)
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
switch $tcl_platform(platform) {
|
| 212 |
+
windows {
|
| 213 |
+
lappend attempdirs "C:\\TEMP" "C:\\TMP" "\\TEMP" "\\TMP"
|
| 214 |
+
}
|
| 215 |
+
macintosh {
|
| 216 |
+
set tmpdir $env(TRASH_FOLDER) ;# a better place?
|
| 217 |
+
}
|
| 218 |
+
default {
|
| 219 |
+
lappend attempdirs \
|
| 220 |
+
[file join / tmp] \
|
| 221 |
+
[file join / var tmp] \
|
| 222 |
+
[file join / usr tmp]
|
| 223 |
+
}
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
lappend attempdirs [pwd]
|
| 227 |
+
|
| 228 |
+
foreach tmp $attempdirs {
|
| 229 |
+
if { [file isdirectory $tmp] && [file writable $tmp] } {
|
| 230 |
+
return [file normalize $tmp]
|
| 231 |
+
}
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
# Fail if nothing worked.
|
| 235 |
+
return -code error "Unable to determine a proper directory for temporary files"
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
# ### ### ### ######### ######### #########
|
| 239 |
+
## Ready
|
| 240 |
+
|
| 241 |
+
package provide platform::shell 1.1.4
|
evalkit_llava/lib/tcl8/8.5/msgcat-1.6.1.tm
ADDED
|
@@ -0,0 +1,1210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
| 1 |
+
# msgcat.tcl --
|
| 2 |
+
#
|
| 3 |
+
# This file defines various procedures which implement a
|
| 4 |
+
# message catalog facility for Tcl programs. It should be
|
| 5 |
+
# loaded with the command "package require msgcat".
|
| 6 |
+
#
|
| 7 |
+
# Copyright (c) 2010-2015 Harald Oehlmann.
|
| 8 |
+
# Copyright (c) 1998-2000 Ajuba Solutions.
|
| 9 |
+
# Copyright (c) 1998 Mark Harrison.
|
| 10 |
+
#
|
| 11 |
+
# See the file "license.terms" for information on usage and redistribution
|
| 12 |
+
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
|
| 13 |
+
|
| 14 |
+
package require Tcl 8.5-
|
| 15 |
+
# When the version number changes, be sure to update the pkgIndex.tcl file,
|
| 16 |
+
# and the installation directory in the Makefiles.
|
| 17 |
+
package provide msgcat 1.6.1
|
| 18 |
+
|
| 19 |
+
namespace eval msgcat {
|
| 20 |
+
namespace export mc mcexists mcload mclocale mcmax mcmset mcpreferences mcset\
|
| 21 |
+
mcunknown mcflset mcflmset mcloadedlocales mcforgetpackage\
|
| 22 |
+
mcpackageconfig mcpackagelocale
|
| 23 |
+
|
| 24 |
+
# Records the list of locales to search
|
| 25 |
+
variable Loclist {}
|
| 26 |
+
|
| 27 |
+
# List of currently loaded locales
|
| 28 |
+
variable LoadedLocales {}
|
| 29 |
+
|
| 30 |
+
# Records the locale of the currently sourced message catalogue file
|
| 31 |
+
variable FileLocale
|
| 32 |
+
|
| 33 |
+
# Configuration values per Package (e.g. client namespace).
|
| 34 |
+
# The dict key is of the form "<option> <namespace>" and the value is the
|
| 35 |
+
# configuration option. A non-existing key is an unset option.
|
| 36 |
+
variable PackageConfig [dict create mcfolder {} loadcmd {} changecmd {}\
|
| 37 |
+
unknowncmd {} loadedlocales {} loclist {}]
|
| 38 |
+
|
| 39 |
+
# Records the mapping between source strings and translated strings. The
|
| 40 |
+
# dict key is of the form "<namespace> <locale> <src>", where locale and
|
| 41 |
+
# namespace should be themselves dict values and the value is
|
| 42 |
+
# the translated string.
|
| 43 |
+
variable Msgs [dict create]
|
| 44 |
+
|
| 45 |
+
# Map of language codes used in Windows registry to those of ISO-639
|
| 46 |
+
if {[info sharedlibextension] eq ".dll"} {
|
| 47 |
+
variable WinRegToISO639 [dict create {*}{
|
| 48 |
+
01 ar 0401 ar_SA 0801 ar_IQ 0c01 ar_EG 1001 ar_LY 1401 ar_DZ
|
| 49 |
+
1801 ar_MA 1c01 ar_TN 2001 ar_OM 2401 ar_YE 2801 ar_SY
|
| 50 |
+
2c01 ar_JO 3001 ar_LB 3401 ar_KW 3801 ar_AE 3c01 ar_BH
|
| 51 |
+
4001 ar_QA
|
| 52 |
+
02 bg 0402 bg_BG
|
| 53 |
+
03 ca 0403 ca_ES
|
| 54 |
+
04 zh 0404 zh_TW 0804 zh_CN 0c04 zh_HK 1004 zh_SG 1404 zh_MO
|
| 55 |
+
05 cs 0405 cs_CZ
|
| 56 |
+
06 da 0406 da_DK
|
| 57 |
+
07 de 0407 de_DE 0807 de_CH 0c07 de_AT 1007 de_LU 1407 de_LI
|
| 58 |
+
08 el 0408 el_GR
|
| 59 |
+
09 en 0409 en_US 0809 en_GB 0c09 en_AU 1009 en_CA 1409 en_NZ
|
| 60 |
+
1809 en_IE 1c09 en_ZA 2009 en_JM 2409 en_GD 2809 en_BZ
|
| 61 |
+
2c09 en_TT 3009 en_ZW 3409 en_PH
|
| 62 |
+
0a es 040a es_ES 080a es_MX 0c0a es_ES@modern 100a es_GT 140a es_CR
|
| 63 |
+
180a es_PA 1c0a es_DO 200a es_VE 240a es_CO 280a es_PE
|
| 64 |
+
2c0a es_AR 300a es_EC 340a es_CL 380a es_UY 3c0a es_PY
|
| 65 |
+
400a es_BO 440a es_SV 480a es_HN 4c0a es_NI 500a es_PR
|
| 66 |
+
0b fi 040b fi_FI
|
| 67 |
+
0c fr 040c fr_FR 080c fr_BE 0c0c fr_CA 100c fr_CH 140c fr_LU
|
| 68 |
+
180c fr_MC
|
| 69 |
+
0d he 040d he_IL
|
| 70 |
+
0e hu 040e hu_HU
|
| 71 |
+
0f is 040f is_IS
|
| 72 |
+
10 it 0410 it_IT 0810 it_CH
|
| 73 |
+
11 ja 0411 ja_JP
|
| 74 |
+
12 ko 0412 ko_KR
|
| 75 |
+
13 nl 0413 nl_NL 0813 nl_BE
|
| 76 |
+
14 no 0414 no_NO 0814 nn_NO
|
| 77 |
+
15 pl 0415 pl_PL
|
| 78 |
+
16 pt 0416 pt_BR 0816 pt_PT
|
| 79 |
+
17 rm 0417 rm_CH
|
| 80 |
+
18 ro 0418 ro_RO 0818 ro_MO
|
| 81 |
+
19 ru 0819 ru_MO
|
| 82 |
+
1a hr 041a hr_HR 081a sr_YU 0c1a sr_YU@cyrillic
|
| 83 |
+
1b sk 041b sk_SK
|
| 84 |
+
1c sq 041c sq_AL
|
| 85 |
+
1d sv 041d sv_SE 081d sv_FI
|
| 86 |
+
1e th 041e th_TH
|
| 87 |
+
1f tr 041f tr_TR
|
| 88 |
+
20 ur 0420 ur_PK 0820 ur_IN
|
| 89 |
+
21 id 0421 id_ID
|
| 90 |
+
22 uk 0422 uk_UA
|
| 91 |
+
23 be 0423 be_BY
|
| 92 |
+
24 sl 0424 sl_SI
|
| 93 |
+
25 et 0425 et_EE
|
| 94 |
+
26 lv 0426 lv_LV
|
| 95 |
+
27 lt 0427 lt_LT
|
| 96 |
+
28 tg 0428 tg_TJ
|
| 97 |
+
29 fa 0429 fa_IR
|
| 98 |
+
2a vi 042a vi_VN
|
| 99 |
+
2b hy 042b hy_AM
|
| 100 |
+
2c az 042c az_AZ@latin 082c az_AZ@cyrillic
|
| 101 |
+
2d eu
|
| 102 |
+
2e wen 042e wen_DE
|
| 103 |
+
2f mk 042f mk_MK
|
| 104 |
+
30 bnt 0430 bnt_TZ
|
| 105 |
+
31 ts 0431 ts_ZA
|
| 106 |
+
32 tn
|
| 107 |
+
33 ven 0433 ven_ZA
|
| 108 |
+
34 xh 0434 xh_ZA
|
| 109 |
+
35 zu 0435 zu_ZA
|
| 110 |
+
36 af 0436 af_ZA
|
| 111 |
+
37 ka 0437 ka_GE
|
| 112 |
+
38 fo 0438 fo_FO
|
| 113 |
+
39 hi 0439 hi_IN
|
| 114 |
+
3a mt 043a mt_MT
|
| 115 |
+
3b se 043b se_NO
|
| 116 |
+
043c gd_UK 083c ga_IE
|
| 117 |
+
3d yi 043d yi_IL
|
| 118 |
+
3e ms 043e ms_MY 083e ms_BN
|
| 119 |
+
3f kk 043f kk_KZ
|
| 120 |
+
40 ky 0440 ky_KG
|
| 121 |
+
41 sw 0441 sw_KE
|
| 122 |
+
42 tk 0442 tk_TM
|
| 123 |
+
43 uz 0443 uz_UZ@latin 0843 uz_UZ@cyrillic
|
| 124 |
+
44 tt 0444 tt_RU
|
| 125 |
+
45 bn 0445 bn_IN
|
| 126 |
+
46 pa 0446 pa_IN
|
| 127 |
+
47 gu 0447 gu_IN
|
| 128 |
+
48 or 0448 or_IN
|
| 129 |
+
49 ta
|
| 130 |
+
4a te 044a te_IN
|
| 131 |
+
4b kn 044b kn_IN
|
| 132 |
+
4c ml 044c ml_IN
|
| 133 |
+
4d as 044d as_IN
|
| 134 |
+
4e mr 044e mr_IN
|
| 135 |
+
4f sa 044f sa_IN
|
| 136 |
+
50 mn
|
| 137 |
+
51 bo 0451 bo_CN
|
| 138 |
+
52 cy 0452 cy_GB
|
| 139 |
+
53 km 0453 km_KH
|
| 140 |
+
54 lo 0454 lo_LA
|
| 141 |
+
55 my 0455 my_MM
|
| 142 |
+
56 gl 0456 gl_ES
|
| 143 |
+
57 kok 0457 kok_IN
|
| 144 |
+
58 mni 0458 mni_IN
|
| 145 |
+
59 sd
|
| 146 |
+
5a syr 045a syr_TR
|
| 147 |
+
5b si 045b si_LK
|
| 148 |
+
5c chr 045c chr_US
|
| 149 |
+
5d iu 045d iu_CA
|
| 150 |
+
5e am 045e am_ET
|
| 151 |
+
5f ber 045f ber_MA
|
| 152 |
+
60 ks 0460 ks_PK 0860 ks_IN
|
| 153 |
+
61 ne 0461 ne_NP 0861 ne_IN
|
| 154 |
+
62 fy 0462 fy_NL
|
| 155 |
+
63 ps
|
| 156 |
+
64 tl 0464 tl_PH
|
| 157 |
+
65 div 0465 div_MV
|
| 158 |
+
66 bin 0466 bin_NG
|
| 159 |
+
67 ful 0467 ful_NG
|
| 160 |
+
68 ha 0468 ha_NG
|
| 161 |
+
69 nic 0469 nic_NG
|
| 162 |
+
6a yo 046a yo_NG
|
| 163 |
+
70 ibo 0470 ibo_NG
|
| 164 |
+
71 kau 0471 kau_NG
|
| 165 |
+
72 om 0472 om_ET
|
| 166 |
+
73 ti 0473 ti_ET
|
| 167 |
+
74 gn 0474 gn_PY
|
| 168 |
+
75 cpe 0475 cpe_US
|
| 169 |
+
76 la 0476 la_VA
|
| 170 |
+
77 so 0477 so_SO
|
| 171 |
+
78 sit 0478 sit_CN
|
| 172 |
+
79 pap 0479 pap_AN
|
| 173 |
+
}]
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
# msgcat::mc --
|
| 178 |
+
#
|
| 179 |
+
# Find the translation for the given string based on the current
|
| 180 |
+
# locale setting. Check the local namespace first, then look in each
|
| 181 |
+
# parent namespace until the source is found. If additional args are
|
| 182 |
+
# specified, use the format command to work them into the translated
|
| 183 |
+
# string.
|
| 184 |
+
# If no catalog item is found, mcunknown is called in the caller frame
|
| 185 |
+
# and its result is returned.
|
| 186 |
+
#
|
| 187 |
+
# Arguments:
|
| 188 |
+
# src The string to translate.
|
| 189 |
+
# args Args to pass to the format command
|
| 190 |
+
#
|
| 191 |
+
# Results:
|
| 192 |
+
# Returns the translated string. Propagates errors thrown by the
|
| 193 |
+
# format command.
|
| 194 |
+
|
| 195 |
+
proc msgcat::mc {src args} {
|
| 196 |
+
# this may be replaced by:
|
| 197 |
+
# return [mcget -namespace [uplevel 1 [list ::namespace current]] --\
|
| 198 |
+
# $src {*}$args]
|
| 199 |
+
|
| 200 |
+
# Check for the src in each namespace starting from the local and
|
| 201 |
+
# ending in the global.
|
| 202 |
+
|
| 203 |
+
variable Msgs
|
| 204 |
+
variable Loclist
|
| 205 |
+
|
| 206 |
+
set ns [uplevel 1 [list ::namespace current]]
|
| 207 |
+
set loclist [PackagePreferences $ns]
|
| 208 |
+
|
| 209 |
+
set nscur $ns
|
| 210 |
+
while {$nscur != ""} {
|
| 211 |
+
foreach loc $loclist {
|
| 212 |
+
if {[dict exists $Msgs $nscur $loc $src]} {
|
| 213 |
+
return [DefaultUnknown "" [dict get $Msgs $nscur $loc $src]\
|
| 214 |
+
{*}$args]
|
| 215 |
+
}
|
| 216 |
+
}
|
| 217 |
+
set nscur [namespace parent $nscur]
|
| 218 |
+
}
|
| 219 |
+
# call package local or default unknown command
|
| 220 |
+
set args [linsert $args 0 [lindex $loclist 0] $src]
|
| 221 |
+
switch -exact -- [Invoke unknowncmd $args $ns result 1] {
|
| 222 |
+
0 { return [uplevel 1 [linsert $args 0 [namespace origin mcunknown]]] }
|
| 223 |
+
1 { return [DefaultUnknown {*}$args] }
|
| 224 |
+
default { return $result }
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
# msgcat::mcexists --
|
| 229 |
+
#
|
| 230 |
+
# Check if a catalog item is set or if mc would invoke mcunknown.
|
| 231 |
+
#
|
| 232 |
+
# Arguments:
|
| 233 |
+
# -exactnamespace Only check the exact namespace and no
|
| 234 |
+
# parent namespaces
|
| 235 |
+
# -exactlocale Only check the exact locale and not all members
|
| 236 |
+
# of the preferences list
|
| 237 |
+
# src Message catalog key
|
| 238 |
+
#
|
| 239 |
+
# Results:
|
| 240 |
+
# true if an adequate catalog key was found
|
| 241 |
+
|
| 242 |
+
proc msgcat::mcexists {args} {
|
| 243 |
+
|
| 244 |
+
variable Msgs
|
| 245 |
+
variable Loclist
|
| 246 |
+
variable PackageConfig
|
| 247 |
+
|
| 248 |
+
set ns [uplevel 1 [list ::namespace current]]
|
| 249 |
+
set loclist [PackagePreferences $ns]
|
| 250 |
+
|
| 251 |
+
while {[llength $args] != 1} {
|
| 252 |
+
set args [lassign $args option]
|
| 253 |
+
switch -glob -- $option {
|
| 254 |
+
-exactnamespace { set exactnamespace 1 }
|
| 255 |
+
-exactlocale { set loclist [lrange $loclist 0 0] }
|
| 256 |
+
-* { return -code error "unknown option \"$option\"" }
|
| 257 |
+
default {
|
| 258 |
+
return -code error "wrong # args: should be\
|
| 259 |
+
\"[lindex [info level 0] 0] ?-exactnamespace?\
|
| 260 |
+
?-exactlocale? src\""
|
| 261 |
+
}
|
| 262 |
+
}
|
| 263 |
+
}
|
| 264 |
+
set src [lindex $args 0]
|
| 265 |
+
|
| 266 |
+
while {$ns ne ""} {
|
| 267 |
+
foreach loc $loclist {
|
| 268 |
+
if {[dict exists $Msgs $ns $loc $src]} {
|
| 269 |
+
return 1
|
| 270 |
+
}
|
| 271 |
+
}
|
| 272 |
+
if {[info exists exactnamespace]} {return 0}
|
| 273 |
+
set ns [namespace parent $ns]
|
| 274 |
+
}
|
| 275 |
+
return 0
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
# msgcat::mclocale --
|
| 279 |
+
#
|
| 280 |
+
# Query or set the current locale.
|
| 281 |
+
#
|
| 282 |
+
# Arguments:
|
| 283 |
+
# newLocale (Optional) The new locale string. Locale strings
|
| 284 |
+
# should be composed of one or more sublocale parts
|
| 285 |
+
# separated by underscores (e.g. en_US).
|
| 286 |
+
#
|
| 287 |
+
# Results:
|
| 288 |
+
# Returns the normalized set locale.
|
| 289 |
+
|
| 290 |
+
proc msgcat::mclocale {args} {
|
| 291 |
+
variable Loclist
|
| 292 |
+
variable LoadedLocales
|
| 293 |
+
set len [llength $args]
|
| 294 |
+
|
| 295 |
+
if {$len > 1} {
|
| 296 |
+
return -code error "wrong # args: should be\
|
| 297 |
+
\"[lindex [info level 0] 0] ?newLocale?\""
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
if {$len == 1} {
|
| 301 |
+
set newLocale [string tolower [lindex $args 0]]
|
| 302 |
+
if {$newLocale ne [file tail $newLocale]} {
|
| 303 |
+
return -code error "invalid newLocale value \"$newLocale\":\
|
| 304 |
+
could be path to unsafe code."
|
| 305 |
+
}
|
| 306 |
+
if {[lindex $Loclist 0] ne $newLocale} {
|
| 307 |
+
set Loclist [GetPreferences $newLocale]
|
| 308 |
+
|
| 309 |
+
# locale not loaded jet
|
| 310 |
+
LoadAll $Loclist
|
| 311 |
+
# Invoke callback
|
| 312 |
+
Invoke changecmd $Loclist
|
| 313 |
+
}
|
| 314 |
+
}
|
| 315 |
+
return [lindex $Loclist 0]
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
# msgcat::GetPreferences --
|
| 319 |
+
#
|
| 320 |
+
# Get list of locales from a locale.
|
| 321 |
+
# The first element is always the lowercase locale.
|
| 322 |
+
# Other elements have one component separated by "_" less.
|
| 323 |
+
# Multiple "_" are seen as one separator: de__ch_spec de__ch de {}
|
| 324 |
+
#
|
| 325 |
+
# Arguments:
|
| 326 |
+
# Locale.
|
| 327 |
+
#
|
| 328 |
+
# Results:
|
| 329 |
+
# Locale list
|
| 330 |
+
|
| 331 |
+
proc msgcat::GetPreferences {locale} {
|
| 332 |
+
set locale [string tolower $locale]
|
| 333 |
+
set loclist [list $locale]
|
| 334 |
+
while {-1 !=[set pos [string last "_" $locale]]} {
|
| 335 |
+
set locale [string range $locale 0 $pos-1]
|
| 336 |
+
if { "_" ne [string index $locale end] } {
|
| 337 |
+
lappend loclist $locale
|
| 338 |
+
}
|
| 339 |
+
}
|
| 340 |
+
if {"" ne [lindex $loclist end]} {
|
| 341 |
+
lappend loclist {}
|
| 342 |
+
}
|
| 343 |
+
return $loclist
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
# msgcat::mcpreferences --
|
| 347 |
+
#
|
| 348 |
+
# Fetch the list of locales used to look up strings, ordered from
|
| 349 |
+
# most preferred to least preferred.
|
| 350 |
+
#
|
| 351 |
+
# Arguments:
|
| 352 |
+
# None.
|
| 353 |
+
#
|
| 354 |
+
# Results:
|
| 355 |
+
# Returns an ordered list of the locales preferred by the user.
|
| 356 |
+
|
| 357 |
+
proc msgcat::mcpreferences {} {
|
| 358 |
+
variable Loclist
|
| 359 |
+
return $Loclist
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
# msgcat::mcloadedlocales --
|
| 363 |
+
#
|
| 364 |
+
# Get or change the list of currently loaded default locales
|
| 365 |
+
#
|
| 366 |
+
# The following subcommands are available:
|
| 367 |
+
# loaded
|
| 368 |
+
# Get the current list of loaded locales
|
| 369 |
+
# clear
|
| 370 |
+
# Remove all loaded locales not present in mcpreferences.
|
| 371 |
+
#
|
| 372 |
+
# Arguments:
|
| 373 |
+
# subcommand One of loaded or clear
|
| 374 |
+
#
|
| 375 |
+
# Results:
|
| 376 |
+
# Empty string, if not stated differently for the subcommand
|
| 377 |
+
|
| 378 |
+
proc msgcat::mcloadedlocales {subcommand} {
|
| 379 |
+
variable Loclist
|
| 380 |
+
variable LoadedLocales
|
| 381 |
+
variable Msgs
|
| 382 |
+
variable PackageConfig
|
| 383 |
+
switch -exact -- $subcommand {
|
| 384 |
+
clear {
|
| 385 |
+
# Remove all locales not contained in Loclist
|
| 386 |
+
# skip any packages with package locale
|
| 387 |
+
set LoadedLocales $Loclist
|
| 388 |
+
foreach ns [dict keys $Msgs] {
|
| 389 |
+
if {![dict exists $PackageConfig loclist $ns]} {
|
| 390 |
+
foreach locale [dict keys [dict get $Msgs $ns]] {
|
| 391 |
+
if {$locale ni $Loclist} {
|
| 392 |
+
dict unset Msgs $ns $locale
|
| 393 |
+
}
|
| 394 |
+
}
|
| 395 |
+
}
|
| 396 |
+
}
|
| 397 |
+
}
|
| 398 |
+
loaded { return $LoadedLocales }
|
| 399 |
+
default {
|
| 400 |
+
return -code error "unknown subcommand \"$subcommand\": must be\
|
| 401 |
+
clear, or loaded"
|
| 402 |
+
}
|
| 403 |
+
}
|
| 404 |
+
return
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
# msgcat::mcpackagelocale --
|
| 408 |
+
#
|
| 409 |
+
# Get or change the package locale of the calling package.
|
| 410 |
+
#
|
| 411 |
+
# The following subcommands are available:
|
| 412 |
+
# set
|
| 413 |
+
# Set a package locale.
|
| 414 |
+
# This may load message catalog files and may clear message catalog
|
| 415 |
+
# items, if the former locale was the default locale.
|
| 416 |
+
# Returns the normalized set locale.
|
| 417 |
+
# The default locale is taken, if locale is not given.
|
| 418 |
+
# get
|
| 419 |
+
# Get the locale valid for this package.
|
| 420 |
+
# isset
|
| 421 |
+
# Returns true, if a package locale is set
|
| 422 |
+
# unset
|
| 423 |
+
# Unset the package locale and activate the default locale.
|
| 424 |
+
# This loads message catalog file which where missing in the package
|
| 425 |
+
# locale.
|
| 426 |
+
# preferences
|
| 427 |
+
# Return locale preference list valid for the package.
|
| 428 |
+
# loaded
|
| 429 |
+
# Return loaded locale list valid for the current package.
|
| 430 |
+
# clear
|
| 431 |
+
# If the current package has a package locale, remove all package
|
| 432 |
+
# locales not containes in package mcpreferences.
|
| 433 |
+
# It is an error to call this without a package locale set.
|
| 434 |
+
#
|
| 435 |
+
# The subcommands get, preferences and loaded return the corresponding
|
| 436 |
+
# default data, if no package locale is set.
|
| 437 |
+
#
|
| 438 |
+
# Arguments:
|
| 439 |
+
# subcommand see list above
|
| 440 |
+
# locale package locale (only set subcommand)
|
| 441 |
+
#
|
| 442 |
+
# Results:
|
| 443 |
+
# Empty string, if not stated differently for the subcommand
|
| 444 |
+
|
| 445 |
+
proc msgcat::mcpackagelocale {subcommand {locale ""}} {
|
| 446 |
+
# todo: implement using an ensemble
|
| 447 |
+
variable Loclist
|
| 448 |
+
variable LoadedLocales
|
| 449 |
+
variable Msgs
|
| 450 |
+
variable PackageConfig
|
| 451 |
+
# Check option
|
| 452 |
+
# check if required item is exactly provided
|
| 453 |
+
if {[llength [info level 0]] == 2} {
|
| 454 |
+
# locale not given
|
| 455 |
+
unset locale
|
| 456 |
+
} else {
|
| 457 |
+
# locale given
|
| 458 |
+
if {$subcommand in
|
| 459 |
+
{"get" "isset" "unset" "preferences" "loaded" "clear"} } {
|
| 460 |
+
return -code error "wrong # args: should be\
|
| 461 |
+
\"[lrange [info level 0] 0 1]\""
|
| 462 |
+
}
|
| 463 |
+
set locale [string tolower $locale]
|
| 464 |
+
}
|
| 465 |
+
set ns [uplevel 1 {::namespace current}]
|
| 466 |
+
|
| 467 |
+
switch -exact -- $subcommand {
|
| 468 |
+
get { return [lindex [PackagePreferences $ns] 0] }
|
| 469 |
+
preferences { return [PackagePreferences $ns] }
|
| 470 |
+
loaded { return [PackageLocales $ns] }
|
| 471 |
+
present { return [expr {$locale in [PackageLocales $ns]} ]}
|
| 472 |
+
isset { return [dict exists $PackageConfig loclist $ns] }
|
| 473 |
+
set { # set a package locale or add a package locale
|
| 474 |
+
|
| 475 |
+
# Copy the default locale if no package locale set so far
|
| 476 |
+
if {![dict exists $PackageConfig loclist $ns]} {
|
| 477 |
+
dict set PackageConfig loclist $ns $Loclist
|
| 478 |
+
dict set PackageConfig loadedlocales $ns $LoadedLocales
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
# Check if changed
|
| 482 |
+
set loclist [dict get $PackageConfig loclist $ns]
|
| 483 |
+
if {! [info exists locale] || $locale eq [lindex $loclist 0] } {
|
| 484 |
+
return [lindex $loclist 0]
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
# Change loclist
|
| 488 |
+
set loclist [GetPreferences $locale]
|
| 489 |
+
set locale [lindex $loclist 0]
|
| 490 |
+
dict set PackageConfig loclist $ns $loclist
|
| 491 |
+
|
| 492 |
+
# load eventual missing locales
|
| 493 |
+
set loadedLocales [dict get $PackageConfig loadedlocales $ns]
|
| 494 |
+
if {$locale in $loadedLocales} { return $locale }
|
| 495 |
+
set loadLocales [ListComplement $loadedLocales $loclist]
|
| 496 |
+
dict set PackageConfig loadedlocales $ns\
|
| 497 |
+
[concat $loadedLocales $loadLocales]
|
| 498 |
+
Load $ns $loadLocales
|
| 499 |
+
return $locale
|
| 500 |
+
}
|
| 501 |
+
clear { # Remove all locales not contained in Loclist
|
| 502 |
+
if {![dict exists $PackageConfig loclist $ns]} {
|
| 503 |
+
return -code error "clear only when package locale set"
|
| 504 |
+
}
|
| 505 |
+
set loclist [dict get $PackageConfig loclist $ns]
|
| 506 |
+
dict set PackageConfig loadedlocales $ns $loclist
|
| 507 |
+
if {[dict exists $Msgs $ns]} {
|
| 508 |
+
foreach locale [dict keys [dict get $Msgs $ns]] {
|
| 509 |
+
if {$locale ni $loclist} {
|
| 510 |
+
dict unset Msgs $ns $locale
|
| 511 |
+
}
|
| 512 |
+
}
|
| 513 |
+
}
|
| 514 |
+
}
|
| 515 |
+
unset { # unset package locale and restore default locales
|
| 516 |
+
|
| 517 |
+
if { ![dict exists $PackageConfig loclist $ns] } { return }
|
| 518 |
+
|
| 519 |
+
# unset package locale
|
| 520 |
+
set loadLocales [ListComplement\
|
| 521 |
+
[dict get $PackageConfig loadedlocales $ns] $LoadedLocales]
|
| 522 |
+
dict unset PackageConfig loadedlocales $ns
|
| 523 |
+
dict unset PackageConfig loclist $ns
|
| 524 |
+
|
| 525 |
+
# unset keys not in global loaded locales
|
| 526 |
+
if {[dict exists $Msgs $ns]} {
|
| 527 |
+
foreach locale [dict keys [dict get $Msgs $ns]] {
|
| 528 |
+
if {$locale ni $LoadedLocales} {
|
| 529 |
+
dict unset Msgs $ns $locale
|
| 530 |
+
}
|
| 531 |
+
}
|
| 532 |
+
}
|
| 533 |
+
|
| 534 |
+
# Add missing locales
|
| 535 |
+
Load $ns $loadLocales
|
| 536 |
+
}
|
| 537 |
+
default {
|
| 538 |
+
return -code error "unknown subcommand \"$subcommand\": must be\
|
| 539 |
+
clear, get, isset, loaded, present, set, or unset"
|
| 540 |
+
}
|
| 541 |
+
}
|
| 542 |
+
return
|
| 543 |
+
}
|
| 544 |
+
|
| 545 |
+
# msgcat::mcforgetpackage --
|
| 546 |
+
#
|
| 547 |
+
# Remove any data of the calling package from msgcat
|
| 548 |
+
#
|
| 549 |
+
|
| 550 |
+
proc msgcat::mcforgetpackage {} {
|
| 551 |
+
# todo: this may be implemented using an ensemble
|
| 552 |
+
variable PackageConfig
|
| 553 |
+
variable Msgs
|
| 554 |
+
set ns [uplevel 1 {::namespace current}]
|
| 555 |
+
# Remove MC items
|
| 556 |
+
dict unset Msgs $ns
|
| 557 |
+
# Remove config items
|
| 558 |
+
foreach key [dict keys $PackageConfig] {
|
| 559 |
+
dict unset PackageConfig $key $ns
|
| 560 |
+
}
|
| 561 |
+
return
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
# msgcat::mcpackageconfig --
|
| 565 |
+
#
|
| 566 |
+
# Get or modify the per caller namespace (e.g. packages) config options.
|
| 567 |
+
#
|
| 568 |
+
# Available subcommands are:
|
| 569 |
+
#
|
| 570 |
+
# get get the current value or an error if not set.
|
| 571 |
+
# isset return true, if the option is set
|
| 572 |
+
# set set the value (see also distinct option).
|
| 573 |
+
# Returns the number of loaded message files.
|
| 574 |
+
# unset Clear option. return "".
|
| 575 |
+
#
|
| 576 |
+
# Available options are:
|
| 577 |
+
#
|
| 578 |
+
# mcfolder
|
| 579 |
+
# The message catalog folder of the package.
|
| 580 |
+
# This is automatically set by mcload.
|
| 581 |
+
# If the value is changed using the set subcommand, an eventual
|
| 582 |
+
# loadcmd is invoked and all message files of the package locale are
|
| 583 |
+
# loaded.
|
| 584 |
+
#
|
| 585 |
+
# loadcmd
|
| 586 |
+
# The command gets executed before a message file would be
|
| 587 |
+
# sourced for this module.
|
| 588 |
+
# The command is invoked with the expanded locale list to load.
|
| 589 |
+
# The command is not invoked if the registering package namespace
|
| 590 |
+
# is not present.
|
| 591 |
+
# This callback might also be used as an alternative to message
|
| 592 |
+
# files.
|
| 593 |
+
# If the value is changed using the set subcommand, the callback is
|
| 594 |
+
# directly invoked with the current file locale list. No file load is
|
| 595 |
+
# executed.
|
| 596 |
+
#
|
| 597 |
+
# changecmd
|
| 598 |
+
# The command is invoked, after an executed locale change.
|
| 599 |
+
# Appended argument is expanded mcpreferences.
|
| 600 |
+
#
|
| 601 |
+
# unknowncmd
|
| 602 |
+
# Use a package locale mcunknown procedure instead the global one.
|
| 603 |
+
# The appended arguments are identical to mcunknown.
|
| 604 |
+
# A default unknown handler is used if set to the empty string.
|
| 605 |
+
# This consists in returning the key if no arguments are given.
|
| 606 |
+
# With given arguments, format is used to process the arguments.
|
| 607 |
+
#
|
| 608 |
+
# Arguments:
|
| 609 |
+
# subcommand Operation on the package
|
| 610 |
+
# option The package option to get or set.
|
| 611 |
+
# ?value? Eventual value for the subcommand
|
| 612 |
+
#
|
| 613 |
+
# Results:
|
| 614 |
+
# Depends on the subcommand and option and is described there
|
| 615 |
+
|
| 616 |
+
proc msgcat::mcpackageconfig {subcommand option {value ""}} {
|
| 617 |
+
variable PackageConfig
|
| 618 |
+
# get namespace
|
| 619 |
+
set ns [uplevel 1 {::namespace current}]
|
| 620 |
+
|
| 621 |
+
if {$option ni {"mcfolder" "loadcmd" "changecmd" "unknowncmd"}} {
|
| 622 |
+
return -code error "bad option \"$option\": must be mcfolder, loadcmd,\
|
| 623 |
+
changecmd, or unknowncmd"
|
| 624 |
+
}
|
| 625 |
+
|
| 626 |
+
# check if value argument is exactly provided
|
| 627 |
+
if {[llength [info level 0]] == 4 } {
|
| 628 |
+
# value provided
|
| 629 |
+
if {$subcommand in {"get" "isset" "unset"}} {
|
| 630 |
+
return -code error "wrong # args: should be\
|
| 631 |
+
\"[lrange [info level 0] 0 2] value\""
|
| 632 |
+
}
|
| 633 |
+
} elseif {$subcommand eq "set"} {
|
| 634 |
+
return -code error\
|
| 635 |
+
"wrong # args: should be \"[lrange [info level 0] 0 2]\""
|
| 636 |
+
}
|
| 637 |
+
|
| 638 |
+
# Execute subcommands
|
| 639 |
+
switch -exact -- $subcommand {
|
| 640 |
+
get { # Operation get return current value
|
| 641 |
+
if {![dict exists $PackageConfig $option $ns]} {
|
| 642 |
+
return -code error "package option \"$option\" not set"
|
| 643 |
+
}
|
| 644 |
+
return [dict get $PackageConfig $option $ns]
|
| 645 |
+
}
|
| 646 |
+
isset { return [dict exists $PackageConfig $option $ns] }
|
| 647 |
+
unset { dict unset PackageConfig $option $ns }
|
| 648 |
+
set { # Set option
|
| 649 |
+
|
| 650 |
+
if {$option eq "mcfolder"} {
|
| 651 |
+
set value [file normalize $value]
|
| 652 |
+
}
|
| 653 |
+
# Check if changed
|
| 654 |
+
if { [dict exists $PackageConfig $option $ns]
|
| 655 |
+
&& $value eq [dict get $PackageConfig $option $ns] } {
|
| 656 |
+
return 0
|
| 657 |
+
}
|
| 658 |
+
|
| 659 |
+
# set new value
|
| 660 |
+
dict set PackageConfig $option $ns $value
|
| 661 |
+
|
| 662 |
+
# Reload pending message catalogs
|
| 663 |
+
switch -exact -- $option {
|
| 664 |
+
mcfolder { return [Load $ns [PackageLocales $ns]] }
|
| 665 |
+
loadcmd { return [Load $ns [PackageLocales $ns] 1] }
|
| 666 |
+
}
|
| 667 |
+
return 0
|
| 668 |
+
}
|
| 669 |
+
default {
|
| 670 |
+
return -code error "unknown subcommand \"$subcommand\":\
|
| 671 |
+
must be get, isset, set, or unset"
|
| 672 |
+
}
|
| 673 |
+
}
|
| 674 |
+
return
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
# msgcat::PackagePreferences --
|
| 678 |
+
#
|
| 679 |
+
# Return eventual present package preferences or the default list if not
|
| 680 |
+
# present.
|
| 681 |
+
#
|
| 682 |
+
# Arguments:
|
| 683 |
+
# ns Package namespace
|
| 684 |
+
#
|
| 685 |
+
# Results:
|
| 686 |
+
# locale list
|
| 687 |
+
|
| 688 |
+
proc msgcat::PackagePreferences {ns} {
|
| 689 |
+
variable PackageConfig
|
| 690 |
+
if {[dict exists $PackageConfig loclist $ns]} {
|
| 691 |
+
return [dict get $PackageConfig loclist $ns]
|
| 692 |
+
}
|
| 693 |
+
variable Loclist
|
| 694 |
+
return $Loclist
|
| 695 |
+
}
|
| 696 |
+
|
| 697 |
+
# msgcat::PackageLocales --
|
| 698 |
+
#
|
| 699 |
+
# Return eventual present package locales or the default list if not
|
| 700 |
+
# present.
|
| 701 |
+
#
|
| 702 |
+
# Arguments:
|
| 703 |
+
# ns Package namespace
|
| 704 |
+
#
|
| 705 |
+
# Results:
|
| 706 |
+
# locale list
|
| 707 |
+
|
| 708 |
+
proc msgcat::PackageLocales {ns} {
|
| 709 |
+
variable PackageConfig
|
| 710 |
+
if {[dict exists $PackageConfig loadedlocales $ns]} {
|
| 711 |
+
return [dict get $PackageConfig loadedlocales $ns]
|
| 712 |
+
}
|
| 713 |
+
variable LoadedLocales
|
| 714 |
+
return $LoadedLocales
|
| 715 |
+
}
|
| 716 |
+
|
| 717 |
+
# msgcat::ListComplement --
|
| 718 |
+
#
|
| 719 |
+
# Build the complement of two lists.
|
| 720 |
+
# Return a list with all elements in list2 but not in list1.
|
| 721 |
+
# Optionally return the intersection.
|
| 722 |
+
#
|
| 723 |
+
# Arguments:
|
| 724 |
+
# list1 excluded list
|
| 725 |
+
# list2 included list
|
| 726 |
+
# inlistname If not "", write in this variable the intersection list
|
| 727 |
+
#
|
| 728 |
+
# Results:
|
| 729 |
+
# list with all elements in list2 but not in list1
|
| 730 |
+
|
| 731 |
+
proc msgcat::ListComplement {list1 list2 {inlistname ""}} {
|
| 732 |
+
if {"" ne $inlistname} {
|
| 733 |
+
upvar 1 $inlistname inlist
|
| 734 |
+
}
|
| 735 |
+
set inlist {}
|
| 736 |
+
set outlist {}
|
| 737 |
+
foreach item $list2 {
|
| 738 |
+
if {$item in $list1} {
|
| 739 |
+
lappend inlist $item
|
| 740 |
+
} else {
|
| 741 |
+
lappend outlist $item
|
| 742 |
+
}
|
| 743 |
+
}
|
| 744 |
+
return $outlist
|
| 745 |
+
}
|
| 746 |
+
|
| 747 |
+
# msgcat::mcload --
|
| 748 |
+
#
|
| 749 |
+
# Attempt to load message catalogs for each locale in the
|
| 750 |
+
# preference list from the specified directory.
|
| 751 |
+
#
|
| 752 |
+
# Arguments:
|
| 753 |
+
# langdir The directory to search.
|
| 754 |
+
#
|
| 755 |
+
# Results:
|
| 756 |
+
# Returns the number of message catalogs that were loaded.
|
| 757 |
+
|
| 758 |
+
proc msgcat::mcload {langdir} {
|
| 759 |
+
return [uplevel 1 [list\
|
| 760 |
+
[namespace origin mcpackageconfig] set mcfolder $langdir]]
|
| 761 |
+
}
|
| 762 |
+
|
| 763 |
+
# msgcat::LoadAll --
|
| 764 |
+
#
|
| 765 |
+
# Load a list of locales for all packages not having a package locale
|
| 766 |
+
# list.
|
| 767 |
+
#
|
| 768 |
+
# Arguments:
|
| 769 |
+
# langdir The directory to search.
|
| 770 |
+
#
|
| 771 |
+
# Results:
|
| 772 |
+
# Returns the number of message catalogs that were loaded.
|
| 773 |
+
|
| 774 |
+
proc msgcat::LoadAll {locales} {
|
| 775 |
+
variable PackageConfig
|
| 776 |
+
variable LoadedLocales
|
| 777 |
+
if {0 == [llength $locales]} { return {} }
|
| 778 |
+
# filter jet unloaded locales
|
| 779 |
+
set locales [ListComplement $LoadedLocales $locales]
|
| 780 |
+
if {0 == [llength $locales]} { return {} }
|
| 781 |
+
lappend LoadedLocales {*}$locales
|
| 782 |
+
|
| 783 |
+
set packages [lsort -unique [concat\
|
| 784 |
+
[dict keys [dict get $PackageConfig loadcmd]]\
|
| 785 |
+
[dict keys [dict get $PackageConfig mcfolder]]]]
|
| 786 |
+
foreach ns $packages {
|
| 787 |
+
if {! [dict exists $PackageConfig loclist $ns] } {
|
| 788 |
+
Load $ns $locales
|
| 789 |
+
}
|
| 790 |
+
}
|
| 791 |
+
return $locales
|
| 792 |
+
}
|
| 793 |
+
|
| 794 |
+
# msgcat::Load --
|
| 795 |
+
#
|
| 796 |
+
# Invoke message load callback and load message catalog files.
|
| 797 |
+
#
|
| 798 |
+
# Arguments:
|
| 799 |
+
# ns Namespace (equal package) to load the message catalog.
|
| 800 |
+
# locales List of locales to load.
|
| 801 |
+
# callbackonly true if only callback should be invoked
|
| 802 |
+
#
|
| 803 |
+
# Results:
|
| 804 |
+
# Returns the number of message catalogs that were loaded.
|
| 805 |
+
|
| 806 |
+
proc msgcat::Load {ns locales {callbackonly 0}} {
|
| 807 |
+
variable FileLocale
|
| 808 |
+
variable PackageConfig
|
| 809 |
+
variable LoadedLocals
|
| 810 |
+
|
| 811 |
+
if {0 == [llength $locales]} { return 0 }
|
| 812 |
+
|
| 813 |
+
# Invoke callback
|
| 814 |
+
Invoke loadcmd $locales $ns
|
| 815 |
+
|
| 816 |
+
if {$callbackonly || ![dict exists $PackageConfig mcfolder $ns]} {
|
| 817 |
+
return 0
|
| 818 |
+
}
|
| 819 |
+
|
| 820 |
+
# Invoke file load
|
| 821 |
+
set langdir [dict get $PackageConfig mcfolder $ns]
|
| 822 |
+
|
| 823 |
+
# Save the file locale if we are recursively called
|
| 824 |
+
if {[info exists FileLocale]} {
|
| 825 |
+
set nestedFileLocale $FileLocale
|
| 826 |
+
}
|
| 827 |
+
set x 0
|
| 828 |
+
foreach p $locales {
|
| 829 |
+
if {$p eq {}} {
|
| 830 |
+
set p ROOT
|
| 831 |
+
}
|
| 832 |
+
set langfile [file join $langdir $p.msg]
|
| 833 |
+
if {[file exists $langfile]} {
|
| 834 |
+
incr x
|
| 835 |
+
set FileLocale [string tolower\
|
| 836 |
+
[file tail [file rootname $langfile]]]
|
| 837 |
+
if {"root" eq $FileLocale} {
|
| 838 |
+
set FileLocale ""
|
| 839 |
+
}
|
| 840 |
+
namespace inscope $ns [list ::source -encoding utf-8 $langfile]
|
| 841 |
+
unset FileLocale
|
| 842 |
+
}
|
| 843 |
+
}
|
| 844 |
+
if {[info exists nestedFileLocale]} {
|
| 845 |
+
set FileLocale $nestedFileLocale
|
| 846 |
+
}
|
| 847 |
+
return $x
|
| 848 |
+
}
|
| 849 |
+
|
| 850 |
+
# msgcat::Invoke --
|
| 851 |
+
#
|
| 852 |
+
# Invoke a set of registered callbacks.
|
| 853 |
+
# The callback is only invoked, if its registered namespace exists.
|
| 854 |
+
#
|
| 855 |
+
# Arguments:
|
| 856 |
+
# index Index into PackageConfig to get callback command
|
| 857 |
+
# arglist parameters to the callback invocation
|
| 858 |
+
# ns (Optional) package to call.
|
| 859 |
+
# If not given or empty, check all registered packages.
|
| 860 |
+
# resultname Variable to save the callback result of the last called
|
| 861 |
+
# callback to. May be set to "" to discard the result.
|
| 862 |
+
# failerror (0) Fail on error if true. Otherwise call bgerror.
|
| 863 |
+
#
|
| 864 |
+
# Results:
|
| 865 |
+
# Possible values:
|
| 866 |
+
# - 0: no valid command registered
|
| 867 |
+
# - 1: registered command was the empty string
|
| 868 |
+
# - 2: registered command called, resultname is set
|
| 869 |
+
# - 3: registered command failed
|
| 870 |
+
# If multiple commands are called, the maximum of all results is returned.
|
| 871 |
+
|
| 872 |
+
proc msgcat::Invoke {index arglist {ns ""} {resultname ""} {failerror 0}} {
|
| 873 |
+
variable PackageConfig
|
| 874 |
+
variable Config
|
| 875 |
+
if {"" ne $resultname} {
|
| 876 |
+
upvar 1 $resultname result
|
| 877 |
+
}
|
| 878 |
+
if {"" eq $ns} {
|
| 879 |
+
set packageList [dict keys [dict get $PackageConfig $index]]
|
| 880 |
+
} else {
|
| 881 |
+
set packageList [list $ns]
|
| 882 |
+
}
|
| 883 |
+
set ret 0
|
| 884 |
+
foreach ns $packageList {
|
| 885 |
+
if {[dict exists $PackageConfig $index $ns] && [namespace exists $ns]} {
|
| 886 |
+
set cmd [dict get $PackageConfig $index $ns]
|
| 887 |
+
if {"" eq $cmd} {
|
| 888 |
+
if {$ret == 0} {set ret 1}
|
| 889 |
+
} else {
|
| 890 |
+
if {$failerror} {
|
| 891 |
+
set result [namespace inscope $ns $cmd {*}$arglist]
|
| 892 |
+
set ret 2
|
| 893 |
+
} elseif {1 == [catch {
|
| 894 |
+
set result [namespace inscope $ns $cmd {*}$arglist]
|
| 895 |
+
if {$ret < 2} {set ret 2}
|
| 896 |
+
} err derr]} {
|
| 897 |
+
after idle [concat [::interp bgerror ""]\
|
| 898 |
+
[list $err $derr]]
|
| 899 |
+
set ret 3
|
| 900 |
+
}
|
| 901 |
+
}
|
| 902 |
+
}
|
| 903 |
+
}
|
| 904 |
+
return $ret
|
| 905 |
+
}
|
| 906 |
+
|
| 907 |
+
# msgcat::mcset --
|
| 908 |
+
#
|
| 909 |
+
# Set the translation for a given string in a specified locale.
|
| 910 |
+
#
|
| 911 |
+
# Arguments:
|
| 912 |
+
# locale The locale to use.
|
| 913 |
+
# src The source string.
|
| 914 |
+
# dest (Optional) The translated string. If omitted,
|
| 915 |
+
# the source string is used.
|
| 916 |
+
#
|
| 917 |
+
# Results:
|
| 918 |
+
# Returns the new locale.
|
| 919 |
+
|
| 920 |
+
proc msgcat::mcset {locale src {dest ""}} {
|
| 921 |
+
variable Msgs
|
| 922 |
+
if {[llength [info level 0]] == 3} { ;# dest not specified
|
| 923 |
+
set dest $src
|
| 924 |
+
}
|
| 925 |
+
|
| 926 |
+
set ns [uplevel 1 [list ::namespace current]]
|
| 927 |
+
|
| 928 |
+
set locale [string tolower $locale]
|
| 929 |
+
|
| 930 |
+
dict set Msgs $ns $locale $src $dest
|
| 931 |
+
return $dest
|
| 932 |
+
}
|
| 933 |
+
|
| 934 |
+
# msgcat::mcflset --
|
| 935 |
+
#
|
| 936 |
+
# Set the translation for a given string in the current file locale.
|
| 937 |
+
#
|
| 938 |
+
# Arguments:
|
| 939 |
+
# src The source string.
|
| 940 |
+
# dest (Optional) The translated string. If omitted,
|
| 941 |
+
# the source string is used.
|
| 942 |
+
#
|
| 943 |
+
# Results:
|
| 944 |
+
# Returns the new locale.
|
| 945 |
+
|
| 946 |
+
proc msgcat::mcflset {src {dest ""}} {
|
| 947 |
+
variable FileLocale
|
| 948 |
+
variable Msgs
|
| 949 |
+
|
| 950 |
+
if {![info exists FileLocale]} {
|
| 951 |
+
return -code error "must only be used inside a message catalog loaded\
|
| 952 |
+
with ::msgcat::mcload"
|
| 953 |
+
}
|
| 954 |
+
return [uplevel 1 [list [namespace origin mcset] $FileLocale $src $dest]]
|
| 955 |
+
}
|
| 956 |
+
|
| 957 |
+
# msgcat::mcmset --
|
| 958 |
+
#
|
| 959 |
+
# Set the translation for multiple strings in a specified locale.
|
| 960 |
+
#
|
| 961 |
+
# Arguments:
|
| 962 |
+
# locale The locale to use.
|
| 963 |
+
# pairs One or more src/dest pairs (must be even length)
|
| 964 |
+
#
|
| 965 |
+
# Results:
|
| 966 |
+
# Returns the number of pairs processed
|
| 967 |
+
|
| 968 |
+
proc msgcat::mcmset {locale pairs} {
|
| 969 |
+
variable Msgs
|
| 970 |
+
|
| 971 |
+
set length [llength $pairs]
|
| 972 |
+
if {$length % 2} {
|
| 973 |
+
return -code error "bad translation list:\
|
| 974 |
+
should be \"[lindex [info level 0] 0] locale {src dest ...}\""
|
| 975 |
+
}
|
| 976 |
+
|
| 977 |
+
set locale [string tolower $locale]
|
| 978 |
+
set ns [uplevel 1 [list ::namespace current]]
|
| 979 |
+
|
| 980 |
+
foreach {src dest} $pairs {
|
| 981 |
+
dict set Msgs $ns $locale $src $dest
|
| 982 |
+
}
|
| 983 |
+
|
| 984 |
+
return [expr {$length / 2}]
|
| 985 |
+
}
|
| 986 |
+
|
| 987 |
+
# msgcat::mcflmset --
|
| 988 |
+
#
|
| 989 |
+
# Set the translation for multiple strings in the mc file locale.
|
| 990 |
+
#
|
| 991 |
+
# Arguments:
|
| 992 |
+
# pairs One or more src/dest pairs (must be even length)
|
| 993 |
+
#
|
| 994 |
+
# Results:
|
| 995 |
+
# Returns the number of pairs processed
|
| 996 |
+
|
| 997 |
+
proc msgcat::mcflmset {pairs} {
|
| 998 |
+
variable FileLocale
|
| 999 |
+
variable Msgs
|
| 1000 |
+
|
| 1001 |
+
if {![info exists FileLocale]} {
|
| 1002 |
+
return -code error "must only be used inside a message catalog loaded\
|
| 1003 |
+
with ::msgcat::mcload"
|
| 1004 |
+
}
|
| 1005 |
+
return [uplevel 1 [list [namespace origin mcmset] $FileLocale $pairs]]
|
| 1006 |
+
}
|
| 1007 |
+
|
| 1008 |
+
# msgcat::mcunknown --
|
| 1009 |
+
#
|
| 1010 |
+
# This routine is called by msgcat::mc if a translation cannot
|
| 1011 |
+
# be found for a string and no unknowncmd is set for the current
|
| 1012 |
+
# package. This routine is intended to be replaced
|
| 1013 |
+
# by an application specific routine for error reporting
|
| 1014 |
+
# purposes. The default behavior is to return the source string.
|
| 1015 |
+
# If additional args are specified, the format command will be used
|
| 1016 |
+
# to work them into the translated string.
|
| 1017 |
+
#
|
| 1018 |
+
# Arguments:
|
| 1019 |
+
# locale The current locale.
|
| 1020 |
+
# src The string to be translated.
|
| 1021 |
+
# args Args to pass to the format command
|
| 1022 |
+
#
|
| 1023 |
+
# Results:
|
| 1024 |
+
# Returns the translated value.
|
| 1025 |
+
|
| 1026 |
+
proc msgcat::mcunknown {args} {
|
| 1027 |
+
return [uplevel 1 [list [namespace origin DefaultUnknown] {*}$args]]
|
| 1028 |
+
}
|
| 1029 |
+
|
| 1030 |
+
# msgcat::DefaultUnknown --
|
| 1031 |
+
#
|
| 1032 |
+
# This routine is called by msgcat::mc if a translation cannot
|
| 1033 |
+
# be found for a string in the following circumstances:
|
| 1034 |
+
# - Default global handler, if mcunknown is not redefined.
|
| 1035 |
+
# - Per package handler, if the package sets unknowncmd to the empty
|
| 1036 |
+
# string.
|
| 1037 |
+
# It returns the source string if the argument list is empty.
|
| 1038 |
+
# If additional args are specified, the format command will be used
|
| 1039 |
+
# to work them into the translated string.
|
| 1040 |
+
#
|
| 1041 |
+
# Arguments:
|
| 1042 |
+
# locale (unused) The current locale.
|
| 1043 |
+
# src The string to be translated.
|
| 1044 |
+
# args Args to pass to the format command
|
| 1045 |
+
#
|
| 1046 |
+
# Results:
|
| 1047 |
+
# Returns the translated value.
|
| 1048 |
+
|
| 1049 |
+
proc msgcat::DefaultUnknown {locale src args} {
|
| 1050 |
+
if {[llength $args]} {
|
| 1051 |
+
return [format $src {*}$args]
|
| 1052 |
+
} else {
|
| 1053 |
+
return $src
|
| 1054 |
+
}
|
| 1055 |
+
}
|
| 1056 |
+
|
| 1057 |
+
# msgcat::mcmax --
|
| 1058 |
+
#
|
| 1059 |
+
# Calculates the maximum length of the translated strings of the given
|
| 1060 |
+
# list.
|
| 1061 |
+
#
|
| 1062 |
+
# Arguments:
|
| 1063 |
+
# args strings to translate.
|
| 1064 |
+
#
|
| 1065 |
+
# Results:
|
| 1066 |
+
# Returns the length of the longest translated string.
|
| 1067 |
+
|
| 1068 |
+
proc msgcat::mcmax {args} {
|
| 1069 |
+
set max 0
|
| 1070 |
+
foreach string $args {
|
| 1071 |
+
set translated [uplevel 1 [list [namespace origin mc] $string]]
|
| 1072 |
+
set len [string length $translated]
|
| 1073 |
+
if {$len>$max} {
|
| 1074 |
+
set max $len
|
| 1075 |
+
}
|
| 1076 |
+
}
|
| 1077 |
+
return $max
|
| 1078 |
+
}
|
| 1079 |
+
|
| 1080 |
+
# Convert the locale values stored in environment variables to a form
|
| 1081 |
+
# suitable for passing to [mclocale]
|
| 1082 |
+
proc msgcat::ConvertLocale {value} {
|
| 1083 |
+
# Assume $value is of form: $language[_$territory][.$codeset][@modifier]
|
| 1084 |
+
# Convert to form: $language[_$territory][_$modifier]
|
| 1085 |
+
#
|
| 1086 |
+
# Comment out expanded RE version -- bugs alleged
|
| 1087 |
+
# regexp -expanded {
|
| 1088 |
+
# ^ # Match all the way to the beginning
|
| 1089 |
+
# ([^_.@]*) # Match "lanugage"; ends with _, ., or @
|
| 1090 |
+
# (_([^.@]*))? # Match (optional) "territory"; starts with _
|
| 1091 |
+
# ([.]([^@]*))? # Match (optional) "codeset"; starts with .
|
| 1092 |
+
# (@(.*))? # Match (optional) "modifier"; starts with @
|
| 1093 |
+
# $ # Match all the way to the end
|
| 1094 |
+
# } $value -> language _ territory _ codeset _ modifier
|
| 1095 |
+
if {![regexp {^([^_.@]+)(_([^.@]*))?([.]([^@]*))?(@(.*))?$} $value \
|
| 1096 |
+
-> language _ territory _ codeset _ modifier]} {
|
| 1097 |
+
return -code error "invalid locale '$value': empty language part"
|
| 1098 |
+
}
|
| 1099 |
+
set ret $language
|
| 1100 |
+
if {[string length $territory]} {
|
| 1101 |
+
append ret _$territory
|
| 1102 |
+
}
|
| 1103 |
+
if {[string length $modifier]} {
|
| 1104 |
+
append ret _$modifier
|
| 1105 |
+
}
|
| 1106 |
+
return $ret
|
| 1107 |
+
}
|
| 1108 |
+
|
| 1109 |
+
# Initialize the default locale
|
| 1110 |
+
proc msgcat::Init {} {
|
| 1111 |
+
global env
|
| 1112 |
+
|
| 1113 |
+
#
|
| 1114 |
+
# set default locale, try to get from environment
|
| 1115 |
+
#
|
| 1116 |
+
foreach varName {LC_ALL LC_MESSAGES LANG} {
|
| 1117 |
+
if {[info exists env($varName)] && ("" ne $env($varName))} {
|
| 1118 |
+
if {![catch {
|
| 1119 |
+
mclocale [ConvertLocale $env($varName)]
|
| 1120 |
+
}]} {
|
| 1121 |
+
return
|
| 1122 |
+
}
|
| 1123 |
+
}
|
| 1124 |
+
}
|
| 1125 |
+
#
|
| 1126 |
+
# On Darwin, fallback to current CFLocale identifier if available.
|
| 1127 |
+
#
|
| 1128 |
+
if {[info exists ::tcl::mac::locale] && $::tcl::mac::locale ne ""} {
|
| 1129 |
+
if {![catch {
|
| 1130 |
+
mclocale [ConvertLocale $::tcl::mac::locale]
|
| 1131 |
+
}]} {
|
| 1132 |
+
return
|
| 1133 |
+
}
|
| 1134 |
+
}
|
| 1135 |
+
#
|
| 1136 |
+
# The rest of this routine is special processing for Windows or
|
| 1137 |
+
# Cygwin. All other platforms, get out now.
|
| 1138 |
+
#
|
| 1139 |
+
if {([info sharedlibextension] ne ".dll")
|
| 1140 |
+
|| [catch {package require registry}]} {
|
| 1141 |
+
mclocale C
|
| 1142 |
+
return
|
| 1143 |
+
}
|
| 1144 |
+
#
|
| 1145 |
+
# On Windows or Cygwin, try to set locale depending on registry
|
| 1146 |
+
# settings, or fall back on locale of "C".
|
| 1147 |
+
#
|
| 1148 |
+
|
| 1149 |
+
# On Vista and later:
|
| 1150 |
+
# HCU/Control Panel/Desktop : PreferredUILanguages is for language packs,
|
| 1151 |
+
# HCU/Control Pannel/International : localName is the default locale.
|
| 1152 |
+
#
|
| 1153 |
+
# They contain the local string as RFC5646, composed of:
|
| 1154 |
+
# [a-z]{2,3} : language
|
| 1155 |
+
# -[a-z]{4} : script (optional, translated by table Latn->latin)
|
| 1156 |
+
# -[a-z]{2}|[0-9]{3} : territory (optional, numerical region codes not used)
|
| 1157 |
+
# (-.*)* : variant, extension, private use (optional, not used)
|
| 1158 |
+
# Those are translated to local strings.
|
| 1159 |
+
# Examples: de-CH -> de_ch, sr-Latn-CS -> sr_cs@latin, es-419 -> es
|
| 1160 |
+
#
|
| 1161 |
+
foreach key {{HKEY_CURRENT_USER\Control Panel\Desktop} {HKEY_CURRENT_USER\Control Panel\International}}\
|
| 1162 |
+
value {PreferredUILanguages localeName} {
|
| 1163 |
+
if {![catch {registry get $key $value} localeName]
|
| 1164 |
+
&& [regexp {^([a-z]{2,3})(?:-([a-z]{4}))?(?:-([a-z]{2}))?(?:-.+)?$}\
|
| 1165 |
+
[string tolower $localeName] match locale script territory]} {
|
| 1166 |
+
if {"" ne $territory} {
|
| 1167 |
+
append locale _ $territory
|
| 1168 |
+
}
|
| 1169 |
+
set modifierDict [dict create latn latin cyrl cyrillic]
|
| 1170 |
+
if {[dict exists $modifierDict $script]} {
|
| 1171 |
+
append locale @ [dict get $modifierDict $script]
|
| 1172 |
+
}
|
| 1173 |
+
if {![catch {mclocale [ConvertLocale $locale]}]} {
|
| 1174 |
+
return
|
| 1175 |
+
}
|
| 1176 |
+
}
|
| 1177 |
+
}
|
| 1178 |
+
|
| 1179 |
+
# then check value locale which contains a numerical language ID
|
| 1180 |
+
if {[catch {
|
| 1181 |
+
set locale [registry get $key "locale"]
|
| 1182 |
+
}]} {
|
| 1183 |
+
mclocale C
|
| 1184 |
+
return
|
| 1185 |
+
}
|
| 1186 |
+
#
|
| 1187 |
+
# Keep trying to match against smaller and smaller suffixes
|
| 1188 |
+
# of the registry value, since the latter hexadigits appear
|
| 1189 |
+
# to determine general language and earlier hexadigits determine
|
| 1190 |
+
# more precise information, such as territory. For example,
|
| 1191 |
+
# 0409 - English - United States
|
| 1192 |
+
# 0809 - English - United Kingdom
|
| 1193 |
+
# Add more translations to the WinRegToISO639 array above.
|
| 1194 |
+
#
|
| 1195 |
+
variable WinRegToISO639
|
| 1196 |
+
set locale [string tolower $locale]
|
| 1197 |
+
while {[string length $locale]} {
|
| 1198 |
+
if {![catch {
|
| 1199 |
+
mclocale [ConvertLocale [dict get $WinRegToISO639 $locale]]
|
| 1200 |
+
}]} {
|
| 1201 |
+
return
|
| 1202 |
+
}
|
| 1203 |
+
set locale [string range $locale 1 end]
|
| 1204 |
+
}
|
| 1205 |
+
#
|
| 1206 |
+
# No translation known. Fall back on "C" locale
|
| 1207 |
+
#
|
| 1208 |
+
mclocale C
|
| 1209 |
+
}
|
| 1210 |
+
msgcat::Init
|
evalkit_llava/lib/tcl8/8.5/tcltest-2.5.7.tm
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
evalkit_llava/lib/tcl8/8.6/http-2.9.8.tm
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
evalkit_llava/lib/tcl8/8.6/tdbc/sqlite3-1.1.7.tm
ADDED
|
@@ -0,0 +1,723 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
# Copyright (c) 2008 by Kevin B. Kenny.
|
| 6 |
+
# See the file "license.terms" for information on usage and redistribution
|
| 7 |
+
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
|
| 8 |
+
#
|
| 9 |
+
# RCS: @(#) $Id: tdbcodbc.tcl,v 1.47 2008/02/27 02:08:27 kennykb Exp $
|
| 10 |
+
#
|
| 11 |
+
#------------------------------------------------------------------------------
|
| 12 |
+
|
| 13 |
+
package require tdbc
|
| 14 |
+
package require sqlite3
|
| 15 |
+
|
| 16 |
+
package provide tdbc::sqlite3 1.1.7
|
| 17 |
+
|
| 18 |
+
namespace eval tdbc::sqlite3 {
|
| 19 |
+
namespace export connection
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
#------------------------------------------------------------------------------
|
| 23 |
+
#
|
| 24 |
+
# tdbc::sqlite3::connection --
|
| 25 |
+
#
|
| 26 |
+
# Class representing a SQLite3 database connection
|
| 27 |
+
#
|
| 28 |
+
#------------------------------------------------------------------------------
|
| 29 |
+
|
| 30 |
+
::oo::class create ::tdbc::sqlite3::connection {
|
| 31 |
+
|
| 32 |
+
superclass ::tdbc::connection
|
| 33 |
+
|
| 34 |
+
variable timeout
|
| 35 |
+
variable keepcase
|
| 36 |
+
|
| 37 |
+
# The constructor accepts a database name and opens the database.
|
| 38 |
+
|
| 39 |
+
constructor {databaseName args} {
|
| 40 |
+
set timeout 0
|
| 41 |
+
set keepcase 0
|
| 42 |
+
if {[llength $args] % 2 != 0} {
|
| 43 |
+
set cmd [lrange [info level 0] 0 end-[llength $args]]
|
| 44 |
+
return -code error \
|
| 45 |
+
-errorcode {TDBC GENERAL_ERROR HY000 SQLITE3 WRONGNUMARGS} \
|
| 46 |
+
"wrong # args, should be \"$cmd ?-option value?...\""
|
| 47 |
+
}
|
| 48 |
+
next
|
| 49 |
+
sqlite3 [namespace current]::db $databaseName
|
| 50 |
+
if {[llength $args] > 0} {
|
| 51 |
+
my configure {*}$args
|
| 52 |
+
}
|
| 53 |
+
db nullvalue \ufffd
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
# The 'statementCreate' method forwards to the constructor of the
|
| 57 |
+
# statement class
|
| 58 |
+
|
| 59 |
+
forward statementCreate ::tdbc::sqlite3::statement create
|
| 60 |
+
|
| 61 |
+
# The 'configure' method queries and sets options to the database
|
| 62 |
+
|
| 63 |
+
method configure args {
|
| 64 |
+
if {[llength $args] == 0} {
|
| 65 |
+
|
| 66 |
+
# Query all configuration options
|
| 67 |
+
|
| 68 |
+
set result {-encoding utf-8}
|
| 69 |
+
lappend result -isolation
|
| 70 |
+
if {[db onecolumn {PRAGMA read_uncommitted}]} {
|
| 71 |
+
lappend result readuncommitted
|
| 72 |
+
} else {
|
| 73 |
+
lappend result serializable
|
| 74 |
+
}
|
| 75 |
+
lappend result -keepcase $keepcase
|
| 76 |
+
lappend result -readonly 0
|
| 77 |
+
lappend result -timeout $timeout
|
| 78 |
+
return $result
|
| 79 |
+
|
| 80 |
+
} elseif {[llength $args] == 1} {
|
| 81 |
+
|
| 82 |
+
# Query a single option
|
| 83 |
+
|
| 84 |
+
set option [lindex $args 0]
|
| 85 |
+
if {[catch {::tcl::prefix match -message "option" {
|
| 86 |
+
-encoding -isolation -keepcase -readonly -timeout
|
| 87 |
+
} $option} opt]} {
|
| 88 |
+
return -code error \
|
| 89 |
+
-errorcode [list TDBC GENERAL_ERROR HY000 SQLITE3 \
|
| 90 |
+
BADOPTION $option] $opt
|
| 91 |
+
}
|
| 92 |
+
switch -exact -- $opt {
|
| 93 |
+
-encoding {
|
| 94 |
+
return utf-8
|
| 95 |
+
}
|
| 96 |
+
-isolation {
|
| 97 |
+
if {[db onecolumn {PRAGMA read_uncommitted}]} {
|
| 98 |
+
return readuncommitted
|
| 99 |
+
} else {
|
| 100 |
+
return serializable
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
-keepcase {
|
| 104 |
+
return $keepcase
|
| 105 |
+
}
|
| 106 |
+
-readonly {
|
| 107 |
+
return 0
|
| 108 |
+
}
|
| 109 |
+
-timeout {
|
| 110 |
+
return $timeout
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
} elseif {[llength $args] % 2 != 0} {
|
| 115 |
+
|
| 116 |
+
# Syntax error
|
| 117 |
+
|
| 118 |
+
set cmd [lrange [info level 0] 0 end-[llength $args]]
|
| 119 |
+
return -code error \
|
| 120 |
+
-errorcode [list TDBC GENERAL_ERROR HY000 \
|
| 121 |
+
SQLITE3 WRONGNUMARGS] \
|
| 122 |
+
"wrong # args, should be \" $cmd ?-option value?...\""
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
# Set one or more options
|
| 126 |
+
|
| 127 |
+
foreach {option value} $args {
|
| 128 |
+
if {[catch {::tcl::prefix match -message "option" {
|
| 129 |
+
-encoding -isolation -keepcase -readonly -timeout
|
| 130 |
+
} $option} opt]} {
|
| 131 |
+
return -code error \
|
| 132 |
+
-errorcode [list TDBC GENERAL_ERROR HY000 SQLITE3 \
|
| 133 |
+
BADOPTION $option] $opt
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
switch -exact -- $opt {
|
| 137 |
+
-encoding {
|
| 138 |
+
if {$value ne {utf-8}} {
|
| 139 |
+
return -code error \
|
| 140 |
+
-errorcode [list TDBC FEATURE_NOT_SUPPORTED 0A000 \
|
| 141 |
+
SQLITE3 ENCODING] \
|
| 142 |
+
"-encoding not supported. SQLite3 is always\
|
| 143 |
+
Unicode."
|
| 144 |
+
}
|
| 145 |
+
}
|
| 146 |
+
-isolation {
|
| 147 |
+
if {[catch {::tcl::prefix match -message "isolation level" {
|
| 148 |
+
readuncommitted readcommitted repeatableread
|
| 149 |
+
serializable readonly
|
| 150 |
+
} $value} val]} {
|
| 151 |
+
return -code error \
|
| 152 |
+
-errorcode [list TDBC GENERAL_ERROR HY000 \
|
| 153 |
+
SQLITE3 BADISOLATION $value] \
|
| 154 |
+
$val
|
| 155 |
+
}
|
| 156 |
+
switch -exact -- $val {
|
| 157 |
+
readuncommitted {
|
| 158 |
+
db eval {PRAGMA read_uncommitted = 1}
|
| 159 |
+
}
|
| 160 |
+
readcommitted -
|
| 161 |
+
repeatableread -
|
| 162 |
+
serializable -
|
| 163 |
+
readonly {
|
| 164 |
+
db eval {PRAGMA read_uncommitted = 0}
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
-keepcase {
|
| 169 |
+
if {![string is boolean -strict $value]} {
|
| 170 |
+
return -code error \
|
| 171 |
+
-errorcode [list TDBC DATA_EXCEPTION 22018 \
|
| 172 |
+
SQLITE3 $value] \
|
| 173 |
+
"expected boolean but got \"$value\""
|
| 174 |
+
}
|
| 175 |
+
# Normalize boolean value to 0/1
|
| 176 |
+
set keepcase [expr {bool($value)}]
|
| 177 |
+
}
|
| 178 |
+
-readonly {
|
| 179 |
+
if {$value} {
|
| 180 |
+
return -code error \
|
| 181 |
+
-errorcode [list TDBC FEATURE_NOT_SUPPORTED 0A000 \
|
| 182 |
+
SQLITE3 READONLY] \
|
| 183 |
+
"SQLite3's Tcl API does not support read-only\
|
| 184 |
+
access"
|
| 185 |
+
}
|
| 186 |
+
}
|
| 187 |
+
-timeout {
|
| 188 |
+
if {![string is integer -strict $value]} {
|
| 189 |
+
return -code error \
|
| 190 |
+
-errorcode [list TDBC DATA_EXCEPTION 22018 \
|
| 191 |
+
SQLITE3 $value] \
|
| 192 |
+
"expected integer but got \"$value\""
|
| 193 |
+
}
|
| 194 |
+
db timeout $value
|
| 195 |
+
set timeout $value
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
return
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
# The 'tables' method introspects on the tables in the database.
|
| 203 |
+
|
| 204 |
+
method tables {{pattern %}} {
|
| 205 |
+
set retval {}
|
| 206 |
+
my foreach row {
|
| 207 |
+
SELECT * from sqlite_master
|
| 208 |
+
WHERE type IN ('table', 'view')
|
| 209 |
+
AND name LIKE :pattern
|
| 210 |
+
} {
|
| 211 |
+
if {!$keepcase} {
|
| 212 |
+
dict set row name [string tolower [dict get $row name]]
|
| 213 |
+
}
|
| 214 |
+
dict set retval [dict get $row name] $row
|
| 215 |
+
}
|
| 216 |
+
return $retval
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
# The 'columns' method introspects on columns of a table.
|
| 220 |
+
|
| 221 |
+
method columns {table {pattern %}} {
|
| 222 |
+
regsub -all ' $table '' table
|
| 223 |
+
set retval {}
|
| 224 |
+
set pattern [string map [list \
|
| 225 |
+
* {[*]} \
|
| 226 |
+
? {[?]} \
|
| 227 |
+
\[ \\\[ \
|
| 228 |
+
\] \\\[ \
|
| 229 |
+
_ ? \
|
| 230 |
+
% *] [string tolower $pattern]]
|
| 231 |
+
my foreach origrow "PRAGMA table_info('$table')" {
|
| 232 |
+
set row {}
|
| 233 |
+
dict for {key value} $origrow {
|
| 234 |
+
dict set row [string tolower $key] $value
|
| 235 |
+
}
|
| 236 |
+
if {!$keepcase} {
|
| 237 |
+
dict set row name [string tolower [dict get $row name]]
|
| 238 |
+
}
|
| 239 |
+
if {![string match $pattern \
|
| 240 |
+
[string tolower [dict get $row name]]]} {
|
| 241 |
+
continue
|
| 242 |
+
}
|
| 243 |
+
switch -regexp -matchvar info [dict get $row type] {
|
| 244 |
+
{^(.+)\(\s*([[:digit:]]+)\s*,\s*([[:digit:]]+)\s*\)\s*$} {
|
| 245 |
+
dict set row type \
|
| 246 |
+
[string trim [string tolower [lindex $info 1]]]
|
| 247 |
+
dict set row precision [lindex $info 2]
|
| 248 |
+
dict set row scale [lindex $info 3]
|
| 249 |
+
}
|
| 250 |
+
{^(.+)\(\s*([[:digit:]]+)\s*\)\s*$} {
|
| 251 |
+
dict set row type [string tolower [lindex $info 1]]
|
| 252 |
+
dict set row precision [lindex $info 2]
|
| 253 |
+
dict set row scale 0
|
| 254 |
+
}
|
| 255 |
+
default {
|
| 256 |
+
dict set row type [string tolower [dict get $row type]]
|
| 257 |
+
dict set row precision 0
|
| 258 |
+
dict set row scale 0
|
| 259 |
+
}
|
| 260 |
+
}
|
| 261 |
+
dict set row nullable [expr {![dict get $row notnull]}]
|
| 262 |
+
dict set retval [dict get $row name] $row
|
| 263 |
+
}
|
| 264 |
+
return $retval
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
# The 'primarykeys' method enumerates the primary keys on a table.
|
| 268 |
+
|
| 269 |
+
method primarykeys {table} {
|
| 270 |
+
set result {}
|
| 271 |
+
my foreach row "PRAGMA table_info($table)" {
|
| 272 |
+
if {[dict get $row pk]} {
|
| 273 |
+
lappend result [dict create ordinalPosition \
|
| 274 |
+
[expr {[dict get $row cid]+1}] \
|
| 275 |
+
columnName \
|
| 276 |
+
[dict get $row name]]
|
| 277 |
+
}
|
| 278 |
+
}
|
| 279 |
+
return $result
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
# The 'foreignkeys' method enumerates the foreign keys that are
|
| 283 |
+
# declared in a table or that refer to a given table.
|
| 284 |
+
|
| 285 |
+
method foreignkeys {args} {
|
| 286 |
+
|
| 287 |
+
variable ::tdbc::generalError
|
| 288 |
+
|
| 289 |
+
# Check arguments
|
| 290 |
+
|
| 291 |
+
set argdict {}
|
| 292 |
+
if {[llength $args] % 2 != 0} {
|
| 293 |
+
set errorcode $generalError
|
| 294 |
+
lappend errorcode wrongNumArgs
|
| 295 |
+
return -code error -errorcode $errorcode \
|
| 296 |
+
"wrong # args: should be [lrange [info level 0] 0 1]\
|
| 297 |
+
?-option value?..."
|
| 298 |
+
}
|
| 299 |
+
foreach {key value} $args {
|
| 300 |
+
if {$key ni {-primary -foreign}} {
|
| 301 |
+
set errorcode $generalError
|
| 302 |
+
lappend errorcode badOption
|
| 303 |
+
return -code error -errorcode $errorcode \
|
| 304 |
+
"bad option \"$key\", must be -primary or -foreign"
|
| 305 |
+
}
|
| 306 |
+
set key [string range $key 1 end]
|
| 307 |
+
if {[dict exists $argdict $key]} {
|
| 308 |
+
set errorcode $generalError
|
| 309 |
+
lappend errorcode dupOption
|
| 310 |
+
return -code error -errorcode $errorcode \
|
| 311 |
+
"duplicate option \"$key\" supplied"
|
| 312 |
+
}
|
| 313 |
+
dict set argdict $key $value
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
# If we know the table with the foreign key, search just its
|
| 317 |
+
# foreign keys. Otherwise, iterate over all the tables in the
|
| 318 |
+
# database.
|
| 319 |
+
|
| 320 |
+
if {[dict exists $argdict foreign]} {
|
| 321 |
+
return [my ForeignKeysForTable [dict get $argdict foreign] \
|
| 322 |
+
$argdict]
|
| 323 |
+
} else {
|
| 324 |
+
set result {}
|
| 325 |
+
foreach foreignTable [dict keys [my tables]] {
|
| 326 |
+
lappend result {*}[my ForeignKeysForTable \
|
| 327 |
+
$foreignTable $argdict]
|
| 328 |
+
}
|
| 329 |
+
return $result
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
# The private ForeignKeysForTable method enumerates the foreign keys
|
| 335 |
+
# in a specific table.
|
| 336 |
+
#
|
| 337 |
+
# Parameters:
|
| 338 |
+
#
|
| 339 |
+
# foreignTable - Name of the table containing foreign keys.
|
| 340 |
+
# argdict - Dictionary that may or may not contain a key,
|
| 341 |
+
# 'primary', whose value is the name of a table that
|
| 342 |
+
# must hold the primary key corresponding to the foreign
|
| 343 |
+
# key. If the 'primary' key is absent, all tables are
|
| 344 |
+
# candidates.
|
| 345 |
+
# Results:
|
| 346 |
+
#
|
| 347 |
+
# Returns the list of foreign keys that meed the specified
|
| 348 |
+
# conditions, as a list of dictionaries, each containing the
|
| 349 |
+
# keys, foreignConstraintName, foreignTable, foreignColumn,
|
| 350 |
+
# primaryTable, primaryColumn, and ordinalPosition. Note that the
|
| 351 |
+
# foreign constraint name is constructed arbitrarily, since SQLite3
|
| 352 |
+
# does not report this information.
|
| 353 |
+
|
| 354 |
+
method ForeignKeysForTable {foreignTable argdict} {
|
| 355 |
+
|
| 356 |
+
set result {}
|
| 357 |
+
set n 0
|
| 358 |
+
|
| 359 |
+
# Go through the foreign keys in the given table, looking for
|
| 360 |
+
# ones that refer to the primary table (if one is given), or
|
| 361 |
+
# for any primary keys if none is given.
|
| 362 |
+
my foreach row "PRAGMA foreign_key_list($foreignTable)" {
|
| 363 |
+
if {(![dict exists $argdict primary])
|
| 364 |
+
|| ([string tolower [dict get $row table]]
|
| 365 |
+
eq [string tolower [dict get $argdict primary]])} {
|
| 366 |
+
|
| 367 |
+
# Construct a dictionary for each key, translating
|
| 368 |
+
# SQLite names to TDBC ones and converting sequence
|
| 369 |
+
# numbers to 1-based indexing.
|
| 370 |
+
|
| 371 |
+
set rrow [dict create foreignTable $foreignTable \
|
| 372 |
+
foreignConstraintName \
|
| 373 |
+
?$foreignTable?[dict get $row id]]
|
| 374 |
+
if {[dict exists $row seq]} {
|
| 375 |
+
dict set rrow ordinalPosition \
|
| 376 |
+
[expr {1 + [dict get $row seq]}]
|
| 377 |
+
}
|
| 378 |
+
foreach {to from} {
|
| 379 |
+
foreignColumn from
|
| 380 |
+
primaryTable table
|
| 381 |
+
primaryColumn to
|
| 382 |
+
deleteAction on_delete
|
| 383 |
+
updateAction on_update
|
| 384 |
+
} {
|
| 385 |
+
if {[dict exists $row $from]} {
|
| 386 |
+
dict set rrow $to [dict get $row $from]
|
| 387 |
+
}
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
# Add the newly-constucted dictionary to the result list
|
| 391 |
+
|
| 392 |
+
lappend result $rrow
|
| 393 |
+
}
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
return $result
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
# The 'preparecall' method prepares a call to a stored procedure.
|
| 400 |
+
# SQLite3 does not have stored procedures, since it's an in-process
|
| 401 |
+
# server.
|
| 402 |
+
|
| 403 |
+
method preparecall {call} {
|
| 404 |
+
return -code error \
|
| 405 |
+
-errorcode [list TDBC FEATURE_NOT_SUPPORTED 0A000 \
|
| 406 |
+
SQLITE3 PREPARECALL] \
|
| 407 |
+
{SQLite3 does not support stored procedures}
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
# The 'begintransaction' method launches a database transaction
|
| 411 |
+
|
| 412 |
+
method begintransaction {} {
|
| 413 |
+
db eval {BEGIN TRANSACTION}
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
# The 'commit' method commits a database transaction
|
| 417 |
+
|
| 418 |
+
method commit {} {
|
| 419 |
+
db eval {COMMIT}
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
# The 'rollback' method abandons a database transaction
|
| 423 |
+
|
| 424 |
+
method rollback {} {
|
| 425 |
+
db eval {ROLLBACK}
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
# The 'transaction' method executes a script as a single transaction.
|
| 429 |
+
# We override the 'transaction' method of the base class, since SQLite3
|
| 430 |
+
# has a faster implementation of the same thing. (The base class's generic
|
| 431 |
+
# method should also work.)
|
| 432 |
+
# (Don't overload the base class method, because 'break', 'continue'
|
| 433 |
+
# and 'return' in the transaction body don't work!)
|
| 434 |
+
|
| 435 |
+
#method transaction {script} {
|
| 436 |
+
# uplevel 1 [list {*}[namespace code db] transaction $script]
|
| 437 |
+
#}
|
| 438 |
+
|
| 439 |
+
method prepare {sqlCode} {
|
| 440 |
+
set result [next $sqlCode]
|
| 441 |
+
return $result
|
| 442 |
+
}
|
| 443 |
+
|
| 444 |
+
method getDBhandle {} {
|
| 445 |
+
return [namespace which db]
|
| 446 |
+
}
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
#------------------------------------------------------------------------------
|
| 450 |
+
#
|
| 451 |
+
# tdbc::sqlite3::statement --
|
| 452 |
+
#
|
| 453 |
+
# Class representing a statement to execute against a SQLite3 database
|
| 454 |
+
#
|
| 455 |
+
#------------------------------------------------------------------------------
|
| 456 |
+
|
| 457 |
+
::oo::class create ::tdbc::sqlite3::statement {
|
| 458 |
+
|
| 459 |
+
superclass ::tdbc::statement
|
| 460 |
+
|
| 461 |
+
variable Params db sql
|
| 462 |
+
|
| 463 |
+
# The constructor accepts the handle to the connection and the SQL
|
| 464 |
+
# code for the statement to prepare. All that it does is to parse the
|
| 465 |
+
# statement and store it. The parse is used to support the
|
| 466 |
+
# 'params' and 'paramtype' methods.
|
| 467 |
+
|
| 468 |
+
constructor {connection sqlcode} {
|
| 469 |
+
next
|
| 470 |
+
set Params {}
|
| 471 |
+
set db [$connection getDBhandle]
|
| 472 |
+
set sql $sqlcode
|
| 473 |
+
foreach token [::tdbc::tokenize $sqlcode] {
|
| 474 |
+
if {[string index $token 0] in {$ : @}} {
|
| 475 |
+
dict set Params [string range $token 1 end] \
|
| 476 |
+
{type Tcl_Obj precision 0 scale 0 nullable 1 direction in}
|
| 477 |
+
}
|
| 478 |
+
}
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
# The 'resultSetCreate' method relays to the result set constructor
|
| 482 |
+
|
| 483 |
+
forward resultSetCreate ::tdbc::sqlite3::resultset create
|
| 484 |
+
|
| 485 |
+
# The 'params' method returns descriptions of the parameters accepted
|
| 486 |
+
# by the statement
|
| 487 |
+
|
| 488 |
+
method params {} {
|
| 489 |
+
return $Params
|
| 490 |
+
}
|
| 491 |
+
|
| 492 |
+
# The 'paramtype' method need do nothing; Sqlite3 uses manifest typing.
|
| 493 |
+
|
| 494 |
+
method paramtype args {;}
|
| 495 |
+
|
| 496 |
+
method getDBhandle {} {
|
| 497 |
+
return $db
|
| 498 |
+
}
|
| 499 |
+
|
| 500 |
+
method getSql {} {
|
| 501 |
+
return $sql
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
}
|
| 505 |
+
|
| 506 |
+
#-------------------------------------------------------------------------------
|
| 507 |
+
#
|
| 508 |
+
# tdbc::sqlite3::resultset --
|
| 509 |
+
#
|
| 510 |
+
# Class that represents a SQLlite result set in Tcl
|
| 511 |
+
#
|
| 512 |
+
#-------------------------------------------------------------------------------
|
| 513 |
+
|
| 514 |
+
::oo::class create ::tdbc::sqlite3::resultset {
|
| 515 |
+
|
| 516 |
+
superclass ::tdbc::resultset
|
| 517 |
+
|
| 518 |
+
# The variables of this class all have peculiar names. The reason is
|
| 519 |
+
# that the RunQuery method needs to execute with an activation record
|
| 520 |
+
# that has no local variables whose names could conflict with names
|
| 521 |
+
# in the SQL query. We start the variable names with hyphens because
|
| 522 |
+
# they can't be bind variables.
|
| 523 |
+
|
| 524 |
+
variable -set {*}{
|
| 525 |
+
-columns -db -needcolumns -resultArray
|
| 526 |
+
-results -sql -Cursor -RowCount -END
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
constructor {statement args} {
|
| 530 |
+
next
|
| 531 |
+
set -db [$statement getDBhandle]
|
| 532 |
+
set -sql [$statement getSql]
|
| 533 |
+
set -columns {}
|
| 534 |
+
set -results {}
|
| 535 |
+
${-db} trace [namespace code {my RecordStatement}]
|
| 536 |
+
if {[llength $args] == 0} {
|
| 537 |
+
|
| 538 |
+
# Variable substitutions are evaluated in caller's context
|
| 539 |
+
|
| 540 |
+
uplevel 1 [list ${-db} eval ${-sql} \
|
| 541 |
+
[namespace which -variable -resultArray] \
|
| 542 |
+
[namespace code {my RecordResult}]]
|
| 543 |
+
|
| 544 |
+
} elseif {[llength $args] == 1} {
|
| 545 |
+
|
| 546 |
+
# Variable substitutions are in the dictionary at [lindex $args 0].
|
| 547 |
+
|
| 548 |
+
set -paramDict [lindex $args 0]
|
| 549 |
+
|
| 550 |
+
# At this point, the activation record must contain no variables
|
| 551 |
+
# that might be bound within the query. All variables at this point
|
| 552 |
+
# begin with hyphens so that they are syntactically incorrect
|
| 553 |
+
# as bound variables in SQL.
|
| 554 |
+
|
| 555 |
+
unset args
|
| 556 |
+
unset statement
|
| 557 |
+
|
| 558 |
+
dict with -paramDict {
|
| 559 |
+
${-db} eval ${-sql} -resultArray {
|
| 560 |
+
my RecordResult
|
| 561 |
+
}
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
} else {
|
| 565 |
+
|
| 566 |
+
${-db} trace {}
|
| 567 |
+
|
| 568 |
+
# Too many args
|
| 569 |
+
|
| 570 |
+
return -code error \
|
| 571 |
+
-errorcode [list TDBC GENERAL_ERROR HY000 \
|
| 572 |
+
SQLITE3 WRONGNUMARGS] \
|
| 573 |
+
"wrong # args: should be\
|
| 574 |
+
[lrange [info level 0] 0 1] statement ?dictionary?"
|
| 575 |
+
|
| 576 |
+
}
|
| 577 |
+
${-db} trace {}
|
| 578 |
+
set -Cursor 0
|
| 579 |
+
if {${-Cursor} < [llength ${-results}]
|
| 580 |
+
&& [lindex ${-results} ${-Cursor}] eq {statement}} {
|
| 581 |
+
incr -Cursor 2
|
| 582 |
+
}
|
| 583 |
+
if {${-Cursor} < [llength ${-results}]
|
| 584 |
+
&& [lindex ${-results} ${-Cursor}] eq {columns}} {
|
| 585 |
+
incr -Cursor
|
| 586 |
+
set -columns [lindex ${-results} ${-Cursor}]
|
| 587 |
+
incr -Cursor
|
| 588 |
+
}
|
| 589 |
+
set -RowCount [${-db} changes]
|
| 590 |
+
}
|
| 591 |
+
|
| 592 |
+
# Record the start of a SQL statement
|
| 593 |
+
|
| 594 |
+
method RecordStatement {stmt} {
|
| 595 |
+
set -needcolumns 1
|
| 596 |
+
lappend -results statement {}
|
| 597 |
+
}
|
| 598 |
+
|
| 599 |
+
# Record one row of results from a query by appending it as a dictionary
|
| 600 |
+
# to the 'results' list. As a side effect, set 'columns' to a list
|
| 601 |
+
# comprising the names of the columns of the result.
|
| 602 |
+
|
| 603 |
+
method RecordResult {} {
|
| 604 |
+
set columns ${-resultArray(*)}
|
| 605 |
+
if {[info exists -needcolumns]} {
|
| 606 |
+
lappend -results columns $columns
|
| 607 |
+
unset -needcolumns
|
| 608 |
+
}
|
| 609 |
+
set dict {}
|
| 610 |
+
foreach key $columns {
|
| 611 |
+
if {[set -resultArray($key)] ne "\ufffd"} {
|
| 612 |
+
dict set dict $key [set -resultArray($key)]
|
| 613 |
+
}
|
| 614 |
+
}
|
| 615 |
+
lappend -results row $dict
|
| 616 |
+
}
|
| 617 |
+
|
| 618 |
+
# Advance to the next result set
|
| 619 |
+
|
| 620 |
+
method nextresults {} {
|
| 621 |
+
set have 0
|
| 622 |
+
while {${-Cursor} < [llength ${-results}]} {
|
| 623 |
+
if {[lindex ${-results} ${-Cursor}] eq {statement}} {
|
| 624 |
+
set have 1
|
| 625 |
+
incr -Cursor 2
|
| 626 |
+
break
|
| 627 |
+
}
|
| 628 |
+
incr -Cursor 2
|
| 629 |
+
}
|
| 630 |
+
if {!$have} {
|
| 631 |
+
set -END {}
|
| 632 |
+
}
|
| 633 |
+
if {${-Cursor} >= [llength ${-results}]} {
|
| 634 |
+
set -columns {}
|
| 635 |
+
} elseif {[lindex ${-results} ${-Cursor}] eq {columns}} {
|
| 636 |
+
incr -Cursor
|
| 637 |
+
set -columns [lindex ${-results} ${-Cursor}]
|
| 638 |
+
incr -Cursor
|
| 639 |
+
} else {
|
| 640 |
+
set -columns {}
|
| 641 |
+
}
|
| 642 |
+
return $have
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
method getDBhandle {} {
|
| 646 |
+
return ${-db}
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
# Return a list of the columns
|
| 650 |
+
|
| 651 |
+
method columns {} {
|
| 652 |
+
if {[info exists -END]} {
|
| 653 |
+
return -code error \
|
| 654 |
+
-errorcode {TDBC GENERAL_ERROR HY010 SQLITE3 FUNCTIONSEQ} \
|
| 655 |
+
"Function sequence error: result set is exhausted."
|
| 656 |
+
}
|
| 657 |
+
return ${-columns}
|
| 658 |
+
}
|
| 659 |
+
|
| 660 |
+
# Return the next row of the result set as a list
|
| 661 |
+
|
| 662 |
+
method nextlist var {
|
| 663 |
+
|
| 664 |
+
upvar 1 $var row
|
| 665 |
+
|
| 666 |
+
if {[info exists -END]} {
|
| 667 |
+
return -code error \
|
| 668 |
+
-errorcode {TDBC GENERAL_ERROR HY010 SQLITE3 FUNCTIONSEQ} \
|
| 669 |
+
"Function sequence error: result set is exhausted."
|
| 670 |
+
}
|
| 671 |
+
if {${-Cursor} >= [llength ${-results}]
|
| 672 |
+
|| [lindex ${-results} ${-Cursor}] ne {row}} {
|
| 673 |
+
return 0
|
| 674 |
+
} else {
|
| 675 |
+
set row {}
|
| 676 |
+
incr -Cursor
|
| 677 |
+
set d [lindex ${-results} ${-Cursor}]
|
| 678 |
+
incr -Cursor
|
| 679 |
+
foreach key ${-columns} {
|
| 680 |
+
if {[dict exists $d $key]} {
|
| 681 |
+
lappend row [dict get $d $key]
|
| 682 |
+
} else {
|
| 683 |
+
lappend row {}
|
| 684 |
+
}
|
| 685 |
+
}
|
| 686 |
+
}
|
| 687 |
+
return 1
|
| 688 |
+
}
|
| 689 |
+
|
| 690 |
+
# Return the next row of the result set as a dict
|
| 691 |
+
|
| 692 |
+
method nextdict var {
|
| 693 |
+
|
| 694 |
+
upvar 1 $var row
|
| 695 |
+
|
| 696 |
+
if {[info exists -END]} {
|
| 697 |
+
return -code error \
|
| 698 |
+
-errorcode {TDBC GENERAL_ERROR HY010 SQLITE3 FUNCTIONSEQ} \
|
| 699 |
+
"Function sequence error: result set is exhausted."
|
| 700 |
+
}
|
| 701 |
+
if {${-Cursor} >= [llength ${-results}]
|
| 702 |
+
|| [lindex ${-results} ${-Cursor}] ne {row}} {
|
| 703 |
+
return 0
|
| 704 |
+
} else {
|
| 705 |
+
incr -Cursor
|
| 706 |
+
set row [lindex ${-results} ${-Cursor}]
|
| 707 |
+
incr -Cursor
|
| 708 |
+
}
|
| 709 |
+
return 1
|
| 710 |
+
}
|
| 711 |
+
|
| 712 |
+
# Return the number of rows affected by a statement
|
| 713 |
+
|
| 714 |
+
method rowcount {} {
|
| 715 |
+
if {[info exists -END]} {
|
| 716 |
+
return -code error \
|
| 717 |
+
-errorcode {TDBC GENERAL_ERROR HY010 SQLITE3 FUNCTIONSEQ} \
|
| 718 |
+
"Function sequence error: result set is exhausted."
|
| 719 |
+
}
|
| 720 |
+
return ${-RowCount}
|
| 721 |
+
}
|
| 722 |
+
|
| 723 |
+
}
|
evalkit_llava/lib/tdbc1.1.7/libtdbc1.1.7.so
ADDED
|
Binary file (24.3 kB). View file
|
|
|
evalkit_llava/lib/tdbc1.1.7/libtdbcstub1.1.7.a
ADDED
|
Binary file (3.04 kB). View file
|
|
|
evalkit_llava/lib/tdbc1.1.7/pkgIndex.tcl
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- tcl -*-
|
| 2 |
+
# Tcl package index file, version 1.1
|
| 3 |
+
#
|
| 4 |
+
# Make sure that TDBC is running in a compatible version of Tcl, and
|
| 5 |
+
# that TclOO is available.
|
| 6 |
+
|
| 7 |
+
if {![package vsatisfies [package provide Tcl] 8.6-]} {
|
| 8 |
+
return
|
| 9 |
+
}
|
| 10 |
+
apply {{dir} {
|
| 11 |
+
set libraryfile [file join $dir tdbc.tcl]
|
| 12 |
+
if {![file exists $libraryfile] && [info exists ::env(TDBC_LIBRARY)]} {
|
| 13 |
+
set libraryfile [file join $::env(TDBC_LIBRARY) tdbc.tcl]
|
| 14 |
+
}
|
| 15 |
+
if {[package vsatisfies [package provide Tcl] 9.0-]} {
|
| 16 |
+
package ifneeded tdbc 1.1.7 \
|
| 17 |
+
"package require TclOO;\
|
| 18 |
+
[list load [file join $dir libtcl9tdbc1.1.7.so] [string totitle tdbc]]\;\
|
| 19 |
+
[list source $libraryfile]"
|
| 20 |
+
} else {
|
| 21 |
+
package ifneeded tdbc 1.1.7 \
|
| 22 |
+
"package require TclOO;\
|
| 23 |
+
[list load [file join $dir libtdbc1.1.7.so] [string totitle tdbc]]\;\
|
| 24 |
+
[list source $libraryfile]"
|
| 25 |
+
}
|
| 26 |
+
}} $dir
|
evalkit_llava/lib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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# tdbc.tcl --
|
| 2 |
+
#
|
| 3 |
+
# Definitions of base classes from which TDBC drivers' connections,
|
| 4 |
+
# statements and result sets may inherit.
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2008 by Kevin B. Kenny
|
| 7 |
+
# See the file "license.terms" for information on usage and redistribution
|
| 8 |
+
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
|
| 9 |
+
#
|
| 10 |
+
# RCS: @(#) $Id$
|
| 11 |
+
#
|
| 12 |
+
#------------------------------------------------------------------------------
|
| 13 |
+
|
| 14 |
+
package require TclOO
|
| 15 |
+
|
| 16 |
+
namespace eval ::tdbc {
|
| 17 |
+
namespace export connection statement resultset
|
| 18 |
+
variable generalError [list TDBC GENERAL_ERROR HY000 {}]
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
#------------------------------------------------------------------------------
|
| 22 |
+
#
|
| 23 |
+
# tdbc::ParseConvenienceArgs --
|
| 24 |
+
#
|
| 25 |
+
# Parse the convenience arguments to a TDBC 'execute',
|
| 26 |
+
# 'executewithdictionary', or 'foreach' call.
|
| 27 |
+
#
|
| 28 |
+
# Parameters:
|
| 29 |
+
# argv - Arguments to the call
|
| 30 |
+
# optsVar -- Name of a variable in caller's scope that will receive
|
| 31 |
+
# a dictionary of the supplied options
|
| 32 |
+
#
|
| 33 |
+
# Results:
|
| 34 |
+
# Returns any args remaining after parsing the options.
|
| 35 |
+
#
|
| 36 |
+
# Side effects:
|
| 37 |
+
# Sets the 'opts' dictionary to the options.
|
| 38 |
+
#
|
| 39 |
+
#------------------------------------------------------------------------------
|
| 40 |
+
|
| 41 |
+
proc tdbc::ParseConvenienceArgs {argv optsVar} {
|
| 42 |
+
|
| 43 |
+
variable generalError
|
| 44 |
+
upvar 1 $optsVar opts
|
| 45 |
+
|
| 46 |
+
set opts [dict create -as dicts]
|
| 47 |
+
set i 0
|
| 48 |
+
|
| 49 |
+
# Munch keyword options off the front of the command arguments
|
| 50 |
+
|
| 51 |
+
foreach {key value} $argv {
|
| 52 |
+
if {[string index $key 0] eq {-}} {
|
| 53 |
+
switch -regexp -- $key {
|
| 54 |
+
-as? {
|
| 55 |
+
if {$value ne {dicts} && $value ne {lists}} {
|
| 56 |
+
set errorcode $generalError
|
| 57 |
+
lappend errorcode badVarType $value
|
| 58 |
+
return -code error \
|
| 59 |
+
-errorcode $errorcode \
|
| 60 |
+
"bad variable type \"$value\":\
|
| 61 |
+
must be lists or dicts"
|
| 62 |
+
}
|
| 63 |
+
dict set opts -as $value
|
| 64 |
+
}
|
| 65 |
+
-c(?:o(?:l(?:u(?:m(?:n(?:s(?:v(?:a(?:r(?:i(?:a(?:b(?:le?)?)?)?)?)?)?)?)?)?)?)?)?) {
|
| 66 |
+
dict set opts -columnsvariable $value
|
| 67 |
+
}
|
| 68 |
+
-- {
|
| 69 |
+
incr i
|
| 70 |
+
break
|
| 71 |
+
}
|
| 72 |
+
default {
|
| 73 |
+
set errorcode $generalError
|
| 74 |
+
lappend errorcode badOption $key
|
| 75 |
+
return -code error \
|
| 76 |
+
-errorcode $errorcode \
|
| 77 |
+
"bad option \"$key\":\
|
| 78 |
+
must be -as or -columnsvariable"
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
} else {
|
| 82 |
+
break
|
| 83 |
+
}
|
| 84 |
+
incr i 2
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
return [lrange $argv[set argv {}] $i end]
|
| 88 |
+
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
#------------------------------------------------------------------------------
|
| 94 |
+
#
|
| 95 |
+
# tdbc::connection --
|
| 96 |
+
#
|
| 97 |
+
# Class that represents a generic connection to a database.
|
| 98 |
+
#
|
| 99 |
+
#-----------------------------------------------------------------------------
|
| 100 |
+
|
| 101 |
+
oo::class create ::tdbc::connection {
|
| 102 |
+
|
| 103 |
+
# statementSeq is the sequence number of the last statement created.
|
| 104 |
+
# statementClass is the name of the class that implements the
|
| 105 |
+
# 'statement' API.
|
| 106 |
+
# primaryKeysStatement is the statement that queries primary keys
|
| 107 |
+
# foreignKeysStatement is the statement that queries foreign keys
|
| 108 |
+
|
| 109 |
+
variable statementSeq primaryKeysStatement foreignKeysStatement
|
| 110 |
+
|
| 111 |
+
# The base class constructor accepts no arguments. It sets up the
|
| 112 |
+
# machinery to do the bookkeeping to keep track of what statements
|
| 113 |
+
# are associated with the connection. The derived class constructor
|
| 114 |
+
# is expected to set the variable, 'statementClass' to the name
|
| 115 |
+
# of the class that represents statements, so that the 'prepare'
|
| 116 |
+
# method can invoke it.
|
| 117 |
+
|
| 118 |
+
constructor {} {
|
| 119 |
+
set statementSeq 0
|
| 120 |
+
namespace eval Stmt {}
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
# The 'close' method is simply an alternative syntax for destroying
|
| 124 |
+
# the connection.
|
| 125 |
+
|
| 126 |
+
method close {} {
|
| 127 |
+
my destroy
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
# The 'prepare' method creates a new statement against the connection,
|
| 131 |
+
# giving its constructor the current statement and the SQL code to
|
| 132 |
+
# prepare. It uses the 'statementClass' variable set by the constructor
|
| 133 |
+
# to get the class to instantiate.
|
| 134 |
+
|
| 135 |
+
method prepare {sqlcode} {
|
| 136 |
+
return [my statementCreate Stmt::[incr statementSeq] [self] $sqlcode]
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
# The 'statementCreate' method delegates to the constructor
|
| 140 |
+
# of the class specified by the 'statementClass' variable. It's
|
| 141 |
+
# intended for drivers designed before tdbc 1.0b10. Current ones
|
| 142 |
+
# should forward this method to the constructor directly.
|
| 143 |
+
|
| 144 |
+
method statementCreate {name instance sqlcode} {
|
| 145 |
+
my variable statementClass
|
| 146 |
+
return [$statementClass create $name $instance $sqlcode]
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
# Derived classes are expected to implement the 'prepareCall' method,
|
| 150 |
+
# and have it call 'prepare' as needed (or do something else and
|
| 151 |
+
# install the resulting statement)
|
| 152 |
+
|
| 153 |
+
# The 'statements' method lists the statements active against this
|
| 154 |
+
# connection.
|
| 155 |
+
|
| 156 |
+
method statements {} {
|
| 157 |
+
info commands Stmt::*
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
# The 'resultsets' method lists the result sets active against this
|
| 161 |
+
# connection.
|
| 162 |
+
|
| 163 |
+
method resultsets {} {
|
| 164 |
+
set retval {}
|
| 165 |
+
foreach statement [my statements] {
|
| 166 |
+
foreach resultset [$statement resultsets] {
|
| 167 |
+
lappend retval $resultset
|
| 168 |
+
}
|
| 169 |
+
}
|
| 170 |
+
return $retval
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
# The 'transaction' method executes a block of Tcl code as an
|
| 174 |
+
# ACID transaction against the database.
|
| 175 |
+
|
| 176 |
+
method transaction {script} {
|
| 177 |
+
my begintransaction
|
| 178 |
+
set status [catch {uplevel 1 $script} result options]
|
| 179 |
+
if {$status in {0 2 3 4}} {
|
| 180 |
+
set status2 [catch {my commit} result2 options2]
|
| 181 |
+
if {$status2 == 1} {
|
| 182 |
+
set status 1
|
| 183 |
+
set result $result2
|
| 184 |
+
set options $options2
|
| 185 |
+
}
|
| 186 |
+
}
|
| 187 |
+
switch -exact -- $status {
|
| 188 |
+
0 {
|
| 189 |
+
# do nothing
|
| 190 |
+
}
|
| 191 |
+
2 - 3 - 4 {
|
| 192 |
+
set options [dict merge {-level 1} $options[set options {}]]
|
| 193 |
+
dict incr options -level
|
| 194 |
+
}
|
| 195 |
+
default {
|
| 196 |
+
my rollback
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
return -options $options $result
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
# The 'allrows' method prepares a statement, then executes it with
|
| 203 |
+
# a given set of substituents, returning a list of all the rows
|
| 204 |
+
# that the statement returns. Optionally, it stores the names of
|
| 205 |
+
# the columns in '-columnsvariable'.
|
| 206 |
+
# Usage:
|
| 207 |
+
# $db allrows ?-as lists|dicts? ?-columnsvariable varName? ?--?
|
| 208 |
+
# sql ?dictionary?
|
| 209 |
+
|
| 210 |
+
method allrows args {
|
| 211 |
+
|
| 212 |
+
variable ::tdbc::generalError
|
| 213 |
+
|
| 214 |
+
# Grab keyword-value parameters
|
| 215 |
+
|
| 216 |
+
set args [::tdbc::ParseConvenienceArgs $args[set args {}] opts]
|
| 217 |
+
|
| 218 |
+
# Check postitional parameters
|
| 219 |
+
|
| 220 |
+
set cmd [list [self] prepare]
|
| 221 |
+
if {[llength $args] == 1} {
|
| 222 |
+
set sqlcode [lindex $args 0]
|
| 223 |
+
} elseif {[llength $args] == 2} {
|
| 224 |
+
lassign $args sqlcode dict
|
| 225 |
+
} else {
|
| 226 |
+
set errorcode $generalError
|
| 227 |
+
lappend errorcode wrongNumArgs
|
| 228 |
+
return -code error -errorcode $errorcode \
|
| 229 |
+
"wrong # args: should be [lrange [info level 0] 0 1]\
|
| 230 |
+
?-option value?... ?--? sqlcode ?dictionary?"
|
| 231 |
+
}
|
| 232 |
+
lappend cmd $sqlcode
|
| 233 |
+
|
| 234 |
+
# Prepare the statement
|
| 235 |
+
|
| 236 |
+
set stmt [uplevel 1 $cmd]
|
| 237 |
+
|
| 238 |
+
# Delegate to the statement to accumulate the results
|
| 239 |
+
|
| 240 |
+
set cmd [list $stmt allrows {*}$opts --]
|
| 241 |
+
if {[info exists dict]} {
|
| 242 |
+
lappend cmd $dict
|
| 243 |
+
}
|
| 244 |
+
set status [catch {
|
| 245 |
+
uplevel 1 $cmd
|
| 246 |
+
} result options]
|
| 247 |
+
|
| 248 |
+
# Destroy the statement
|
| 249 |
+
|
| 250 |
+
catch {
|
| 251 |
+
$stmt close
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
return -options $options $result
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
# The 'foreach' method prepares a statement, then executes it with
|
| 258 |
+
# a supplied set of substituents. For each row of the result,
|
| 259 |
+
# it sets a variable to the row and invokes a script in the caller's
|
| 260 |
+
# scope.
|
| 261 |
+
#
|
| 262 |
+
# Usage:
|
| 263 |
+
# $db foreach ?-as lists|dicts? ?-columnsVariable varName? ?--?
|
| 264 |
+
# varName sql ?dictionary? script
|
| 265 |
+
|
| 266 |
+
method foreach args {
|
| 267 |
+
|
| 268 |
+
variable ::tdbc::generalError
|
| 269 |
+
|
| 270 |
+
# Grab keyword-value parameters
|
| 271 |
+
|
| 272 |
+
set args [::tdbc::ParseConvenienceArgs $args[set args {}] opts]
|
| 273 |
+
|
| 274 |
+
# Check postitional parameters
|
| 275 |
+
|
| 276 |
+
set cmd [list [self] prepare]
|
| 277 |
+
if {[llength $args] == 3} {
|
| 278 |
+
lassign $args varname sqlcode script
|
| 279 |
+
} elseif {[llength $args] == 4} {
|
| 280 |
+
lassign $args varname sqlcode dict script
|
| 281 |
+
} else {
|
| 282 |
+
set errorcode $generalError
|
| 283 |
+
lappend errorcode wrongNumArgs
|
| 284 |
+
return -code error -errorcode $errorcode \
|
| 285 |
+
"wrong # args: should be [lrange [info level 0] 0 1]\
|
| 286 |
+
?-option value?... ?--? varname sqlcode ?dictionary? script"
|
| 287 |
+
}
|
| 288 |
+
lappend cmd $sqlcode
|
| 289 |
+
|
| 290 |
+
# Prepare the statement
|
| 291 |
+
|
| 292 |
+
set stmt [uplevel 1 $cmd]
|
| 293 |
+
|
| 294 |
+
# Delegate to the statement to iterate over the results
|
| 295 |
+
|
| 296 |
+
set cmd [list $stmt foreach {*}$opts -- $varname]
|
| 297 |
+
if {[info exists dict]} {
|
| 298 |
+
lappend cmd $dict
|
| 299 |
+
}
|
| 300 |
+
lappend cmd $script
|
| 301 |
+
set status [catch {
|
| 302 |
+
uplevel 1 $cmd
|
| 303 |
+
} result options]
|
| 304 |
+
|
| 305 |
+
# Destroy the statement
|
| 306 |
+
|
| 307 |
+
catch {
|
| 308 |
+
$stmt close
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
# Adjust return level in the case that the script [return]s
|
| 312 |
+
|
| 313 |
+
if {$status == 2} {
|
| 314 |
+
set options [dict merge {-level 1} $options[set options {}]]
|
| 315 |
+
dict incr options -level
|
| 316 |
+
}
|
| 317 |
+
return -options $options $result
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
# The 'BuildPrimaryKeysStatement' method builds a SQL statement to
|
| 321 |
+
# retrieve the primary keys from a database. (It executes once the
|
| 322 |
+
# first time the 'primaryKeys' method is executed, and retains the
|
| 323 |
+
# prepared statement for reuse.)
|
| 324 |
+
|
| 325 |
+
method BuildPrimaryKeysStatement {} {
|
| 326 |
+
|
| 327 |
+
# On some databases, CONSTRAINT_CATALOG is always NULL and
|
| 328 |
+
# JOINing to it fails. Check for this case and include that
|
| 329 |
+
# JOIN only if catalog names are supplied.
|
| 330 |
+
|
| 331 |
+
set catalogClause {}
|
| 332 |
+
if {[lindex [set count [my allrows -as lists {
|
| 333 |
+
SELECT COUNT(*)
|
| 334 |
+
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
|
| 335 |
+
WHERE CONSTRAINT_CATALOG IS NOT NULL}]] 0 0] != 0} {
|
| 336 |
+
set catalogClause \
|
| 337 |
+
{AND xtable.CONSTRAINT_CATALOG = xcolumn.CONSTRAINT_CATALOG}
|
| 338 |
+
}
|
| 339 |
+
set primaryKeysStatement [my prepare "
|
| 340 |
+
SELECT xtable.TABLE_SCHEMA AS \"tableSchema\",
|
| 341 |
+
xtable.TABLE_NAME AS \"tableName\",
|
| 342 |
+
xtable.CONSTRAINT_CATALOG AS \"constraintCatalog\",
|
| 343 |
+
xtable.CONSTRAINT_SCHEMA AS \"constraintSchema\",
|
| 344 |
+
xtable.CONSTRAINT_NAME AS \"constraintName\",
|
| 345 |
+
xcolumn.COLUMN_NAME AS \"columnName\",
|
| 346 |
+
xcolumn.ORDINAL_POSITION AS \"ordinalPosition\"
|
| 347 |
+
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS xtable
|
| 348 |
+
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE xcolumn
|
| 349 |
+
ON xtable.CONSTRAINT_SCHEMA = xcolumn.CONSTRAINT_SCHEMA
|
| 350 |
+
AND xtable.TABLE_NAME = xcolumn.TABLE_NAME
|
| 351 |
+
AND xtable.CONSTRAINT_NAME = xcolumn.CONSTRAINT_NAME
|
| 352 |
+
$catalogClause
|
| 353 |
+
WHERE xtable.TABLE_NAME = :tableName
|
| 354 |
+
AND xtable.CONSTRAINT_TYPE = 'PRIMARY KEY'
|
| 355 |
+
"]
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
# The default implementation of the 'primarykeys' method uses the
|
| 359 |
+
# SQL INFORMATION_SCHEMA to retrieve primary key information. Databases
|
| 360 |
+
# that might not have INFORMATION_SCHEMA must overload this method.
|
| 361 |
+
|
| 362 |
+
method primarykeys {tableName} {
|
| 363 |
+
if {![info exists primaryKeysStatement]} {
|
| 364 |
+
my BuildPrimaryKeysStatement
|
| 365 |
+
}
|
| 366 |
+
tailcall $primaryKeysStatement allrows [list tableName $tableName]
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
# The 'BuildForeignKeysStatements' method builds a SQL statement to
|
| 370 |
+
# retrieve the foreign keys from a database. (It executes once the
|
| 371 |
+
# first time the 'foreignKeys' method is executed, and retains the
|
| 372 |
+
# prepared statements for reuse.)
|
| 373 |
+
|
| 374 |
+
method BuildForeignKeysStatement {} {
|
| 375 |
+
|
| 376 |
+
# On some databases, CONSTRAINT_CATALOG is always NULL and
|
| 377 |
+
# JOINing to it fails. Check for this case and include that
|
| 378 |
+
# JOIN only if catalog names are supplied.
|
| 379 |
+
|
| 380 |
+
set catalogClause1 {}
|
| 381 |
+
set catalogClause2 {}
|
| 382 |
+
if {[lindex [set count [my allrows -as lists {
|
| 383 |
+
SELECT COUNT(*)
|
| 384 |
+
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
|
| 385 |
+
WHERE CONSTRAINT_CATALOG IS NOT NULL}]] 0 0] != 0} {
|
| 386 |
+
set catalogClause1 \
|
| 387 |
+
{AND fkc.CONSTRAINT_CATALOG = rc.CONSTRAINT_CATALOG}
|
| 388 |
+
set catalogClause2 \
|
| 389 |
+
{AND pkc.CONSTRAINT_CATALOG = rc.CONSTRAINT_CATALOG}
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
foreach {exists1 clause1} {
|
| 393 |
+
0 {}
|
| 394 |
+
1 { AND pkc.TABLE_NAME = :primary}
|
| 395 |
+
} {
|
| 396 |
+
foreach {exists2 clause2} {
|
| 397 |
+
0 {}
|
| 398 |
+
1 { AND fkc.TABLE_NAME = :foreign}
|
| 399 |
+
} {
|
| 400 |
+
set stmt [my prepare "
|
| 401 |
+
SELECT rc.CONSTRAINT_CATALOG AS \"foreignConstraintCatalog\",
|
| 402 |
+
rc.CONSTRAINT_SCHEMA AS \"foreignConstraintSchema\",
|
| 403 |
+
rc.CONSTRAINT_NAME AS \"foreignConstraintName\",
|
| 404 |
+
rc.UNIQUE_CONSTRAINT_CATALOG
|
| 405 |
+
AS \"primaryConstraintCatalog\",
|
| 406 |
+
rc.UNIQUE_CONSTRAINT_SCHEMA AS \"primaryConstraintSchema\",
|
| 407 |
+
rc.UNIQUE_CONSTRAINT_NAME AS \"primaryConstraintName\",
|
| 408 |
+
rc.UPDATE_RULE AS \"updateAction\",
|
| 409 |
+
rc.DELETE_RULE AS \"deleteAction\",
|
| 410 |
+
pkc.TABLE_CATALOG AS \"primaryCatalog\",
|
| 411 |
+
pkc.TABLE_SCHEMA AS \"primarySchema\",
|
| 412 |
+
pkc.TABLE_NAME AS \"primaryTable\",
|
| 413 |
+
pkc.COLUMN_NAME AS \"primaryColumn\",
|
| 414 |
+
fkc.TABLE_CATALOG AS \"foreignCatalog\",
|
| 415 |
+
fkc.TABLE_SCHEMA AS \"foreignSchema\",
|
| 416 |
+
fkc.TABLE_NAME AS \"foreignTable\",
|
| 417 |
+
fkc.COLUMN_NAME AS \"foreignColumn\",
|
| 418 |
+
pkc.ORDINAL_POSITION AS \"ordinalPosition\"
|
| 419 |
+
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
|
| 420 |
+
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE fkc
|
| 421 |
+
ON fkc.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
|
| 422 |
+
AND fkc.CONSTRAINT_SCHEMA = rc.CONSTRAINT_SCHEMA
|
| 423 |
+
$catalogClause1
|
| 424 |
+
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE pkc
|
| 425 |
+
ON pkc.CONSTRAINT_NAME = rc.UNIQUE_CONSTRAINT_NAME
|
| 426 |
+
AND pkc.CONSTRAINT_SCHEMA = rc.UNIQUE_CONSTRAINT_SCHEMA
|
| 427 |
+
$catalogClause2
|
| 428 |
+
AND pkc.ORDINAL_POSITION = fkc.ORDINAL_POSITION
|
| 429 |
+
WHERE 1=1
|
| 430 |
+
$clause1
|
| 431 |
+
$clause2
|
| 432 |
+
ORDER BY \"foreignConstraintCatalog\", \"foreignConstraintSchema\", \"foreignConstraintName\", \"ordinalPosition\"
|
| 433 |
+
"]
|
| 434 |
+
dict set foreignKeysStatement $exists1 $exists2 $stmt
|
| 435 |
+
}
|
| 436 |
+
}
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
# The default implementation of the 'foreignkeys' method uses the
|
| 440 |
+
# SQL INFORMATION_SCHEMA to retrieve primary key information. Databases
|
| 441 |
+
# that might not have INFORMATION_SCHEMA must overload this method.
|
| 442 |
+
|
| 443 |
+
method foreignkeys {args} {
|
| 444 |
+
|
| 445 |
+
variable ::tdbc::generalError
|
| 446 |
+
|
| 447 |
+
# Check arguments
|
| 448 |
+
|
| 449 |
+
set argdict {}
|
| 450 |
+
if {[llength $args] % 2 != 0} {
|
| 451 |
+
set errorcode $generalError
|
| 452 |
+
lappend errorcode wrongNumArgs
|
| 453 |
+
return -code error -errorcode $errorcode \
|
| 454 |
+
"wrong # args: should be [lrange [info level 0] 0 1]\
|
| 455 |
+
?-option value?..."
|
| 456 |
+
}
|
| 457 |
+
foreach {key value} $args {
|
| 458 |
+
if {$key ni {-primary -foreign}} {
|
| 459 |
+
set errorcode $generalError
|
| 460 |
+
lappend errorcode badOption
|
| 461 |
+
return -code error -errorcode $errorcode \
|
| 462 |
+
"bad option \"$key\", must be -primary or -foreign"
|
| 463 |
+
}
|
| 464 |
+
set key [string range $key 1 end]
|
| 465 |
+
if {[dict exists $argdict $key]} {
|
| 466 |
+
set errorcode $generalError
|
| 467 |
+
lappend errorcode dupOption
|
| 468 |
+
return -code error -errorcode $errorcode \
|
| 469 |
+
"duplicate option \"$key\" supplied"
|
| 470 |
+
}
|
| 471 |
+
dict set argdict $key $value
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
# Build the statements that query foreign keys. There are four
|
| 475 |
+
# of them, one for each combination of whether -primary
|
| 476 |
+
# and -foreign is specified.
|
| 477 |
+
|
| 478 |
+
if {![info exists foreignKeysStatement]} {
|
| 479 |
+
my BuildForeignKeysStatement
|
| 480 |
+
}
|
| 481 |
+
set stmt [dict get $foreignKeysStatement \
|
| 482 |
+
[dict exists $argdict primary] \
|
| 483 |
+
[dict exists $argdict foreign]]
|
| 484 |
+
tailcall $stmt allrows $argdict
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
# Derived classes are expected to implement the 'begintransaction',
|
| 488 |
+
# 'commit', and 'rollback' methods.
|
| 489 |
+
|
| 490 |
+
# Derived classes are expected to implement 'tables' and 'columns' method.
|
| 491 |
+
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
#------------------------------------------------------------------------------
|
| 495 |
+
#
|
| 496 |
+
# Class: tdbc::statement
|
| 497 |
+
#
|
| 498 |
+
# Class that represents a SQL statement in a generic database
|
| 499 |
+
#
|
| 500 |
+
#------------------------------------------------------------------------------
|
| 501 |
+
|
| 502 |
+
oo::class create tdbc::statement {
|
| 503 |
+
|
| 504 |
+
# resultSetSeq is the sequence number of the last result set created.
|
| 505 |
+
# resultSetClass is the name of the class that implements the 'resultset'
|
| 506 |
+
# API.
|
| 507 |
+
|
| 508 |
+
variable resultSetClass resultSetSeq
|
| 509 |
+
|
| 510 |
+
# The base class constructor accepts no arguments. It initializes
|
| 511 |
+
# the machinery for tracking the ownership of result sets. The derived
|
| 512 |
+
# constructor is expected to invoke the base constructor, and to
|
| 513 |
+
# set a variable 'resultSetClass' to the fully-qualified name of the
|
| 514 |
+
# class that represents result sets.
|
| 515 |
+
|
| 516 |
+
constructor {} {
|
| 517 |
+
set resultSetSeq 0
|
| 518 |
+
namespace eval ResultSet {}
|
| 519 |
+
}
|
| 520 |
+
|
| 521 |
+
# The 'execute' method on a statement runs the statement with
|
| 522 |
+
# a particular set of substituted variables. It actually works
|
| 523 |
+
# by creating the result set object and letting that objects
|
| 524 |
+
# constructor do the work of running the statement. The creation
|
| 525 |
+
# is wrapped in an [uplevel] call because the substitution proces
|
| 526 |
+
# may need to access variables in the caller's scope.
|
| 527 |
+
|
| 528 |
+
# WORKAROUND: Take out the '0 &&' from the next line when
|
| 529 |
+
# Bug 2649975 is fixed
|
| 530 |
+
if {0 && [package vsatisfies [package provide Tcl] 8.6]} {
|
| 531 |
+
method execute args {
|
| 532 |
+
tailcall my resultSetCreate \
|
| 533 |
+
[namespace current]::ResultSet::[incr resultSetSeq] \
|
| 534 |
+
[self] {*}$args
|
| 535 |
+
}
|
| 536 |
+
} else {
|
| 537 |
+
method execute args {
|
| 538 |
+
return \
|
| 539 |
+
[uplevel 1 \
|
| 540 |
+
[list \
|
| 541 |
+
[self] resultSetCreate \
|
| 542 |
+
[namespace current]::ResultSet::[incr resultSetSeq] \
|
| 543 |
+
[self] {*}$args]]
|
| 544 |
+
}
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
# The 'ResultSetCreate' method is expected to be a forward to the
|
| 548 |
+
# appropriate result set constructor. If it's missing, the driver must
|
| 549 |
+
# have been designed for tdbc 1.0b9 and earlier, and the 'resultSetClass'
|
| 550 |
+
# variable holds the class name.
|
| 551 |
+
|
| 552 |
+
method resultSetCreate {name instance args} {
|
| 553 |
+
return [uplevel 1 [list $resultSetClass create \
|
| 554 |
+
$name $instance {*}$args]]
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
# The 'resultsets' method returns a list of result sets produced by
|
| 558 |
+
# the current statement
|
| 559 |
+
|
| 560 |
+
method resultsets {} {
|
| 561 |
+
info commands ResultSet::*
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
# The 'allrows' method executes a statement with a given set of
|
| 565 |
+
# substituents, and returns a list of all the rows that the statement
|
| 566 |
+
# returns. Optionally, it stores the names of columns in
|
| 567 |
+
# '-columnsvariable'.
|
| 568 |
+
#
|
| 569 |
+
# Usage:
|
| 570 |
+
# $statement allrows ?-as lists|dicts? ?-columnsvariable varName? ?--?
|
| 571 |
+
# ?dictionary?
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
method allrows args {
|
| 575 |
+
|
| 576 |
+
variable ::tdbc::generalError
|
| 577 |
+
|
| 578 |
+
# Grab keyword-value parameters
|
| 579 |
+
|
| 580 |
+
set args [::tdbc::ParseConvenienceArgs $args[set args {}] opts]
|
| 581 |
+
|
| 582 |
+
# Check postitional parameters
|
| 583 |
+
|
| 584 |
+
set cmd [list [self] execute]
|
| 585 |
+
if {[llength $args] == 0} {
|
| 586 |
+
# do nothing
|
| 587 |
+
} elseif {[llength $args] == 1} {
|
| 588 |
+
lappend cmd [lindex $args 0]
|
| 589 |
+
} else {
|
| 590 |
+
set errorcode $generalError
|
| 591 |
+
lappend errorcode wrongNumArgs
|
| 592 |
+
return -code error -errorcode $errorcode \
|
| 593 |
+
"wrong # args: should be [lrange [info level 0] 0 1]\
|
| 594 |
+
?-option value?... ?--? ?dictionary?"
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
# Get the result set
|
| 598 |
+
|
| 599 |
+
set resultSet [uplevel 1 $cmd]
|
| 600 |
+
|
| 601 |
+
# Delegate to the result set's [allrows] method to accumulate
|
| 602 |
+
# the rows of the result.
|
| 603 |
+
|
| 604 |
+
set cmd [list $resultSet allrows {*}$opts]
|
| 605 |
+
set status [catch {
|
| 606 |
+
uplevel 1 $cmd
|
| 607 |
+
} result options]
|
| 608 |
+
|
| 609 |
+
# Destroy the result set
|
| 610 |
+
|
| 611 |
+
catch {
|
| 612 |
+
rename $resultSet {}
|
| 613 |
+
}
|
| 614 |
+
|
| 615 |
+
# Adjust return level in the case that the script [return]s
|
| 616 |
+
|
| 617 |
+
if {$status == 2} {
|
| 618 |
+
set options [dict merge {-level 1} $options[set options {}]]
|
| 619 |
+
dict incr options -level
|
| 620 |
+
}
|
| 621 |
+
return -options $options $result
|
| 622 |
+
}
|
| 623 |
+
|
| 624 |
+
# The 'foreach' method executes a statement with a given set of
|
| 625 |
+
# substituents. It runs the supplied script, substituting the supplied
|
| 626 |
+
# named variable. Optionally, it stores the names of columns in
|
| 627 |
+
# '-columnsvariable'.
|
| 628 |
+
#
|
| 629 |
+
# Usage:
|
| 630 |
+
# $statement foreach ?-as lists|dicts? ?-columnsvariable varName? ?--?
|
| 631 |
+
# variableName ?dictionary? script
|
| 632 |
+
|
| 633 |
+
method foreach args {
|
| 634 |
+
|
| 635 |
+
variable ::tdbc::generalError
|
| 636 |
+
|
| 637 |
+
# Grab keyword-value parameters
|
| 638 |
+
|
| 639 |
+
set args [::tdbc::ParseConvenienceArgs $args[set args {}] opts]
|
| 640 |
+
|
| 641 |
+
# Check positional parameters
|
| 642 |
+
|
| 643 |
+
set cmd [list [self] execute]
|
| 644 |
+
if {[llength $args] == 2} {
|
| 645 |
+
lassign $args varname script
|
| 646 |
+
} elseif {[llength $args] == 3} {
|
| 647 |
+
lassign $args varname dict script
|
| 648 |
+
lappend cmd $dict
|
| 649 |
+
} else {
|
| 650 |
+
set errorcode $generalError
|
| 651 |
+
lappend errorcode wrongNumArgs
|
| 652 |
+
return -code error -errorcode $errorcode \
|
| 653 |
+
"wrong # args: should be [lrange [info level 0] 0 1]\
|
| 654 |
+
?-option value?... ?--? varName ?dictionary? script"
|
| 655 |
+
}
|
| 656 |
+
|
| 657 |
+
# Get the result set
|
| 658 |
+
|
| 659 |
+
set resultSet [uplevel 1 $cmd]
|
| 660 |
+
|
| 661 |
+
# Delegate to the result set's [foreach] method to evaluate
|
| 662 |
+
# the script for each row of the result.
|
| 663 |
+
|
| 664 |
+
set cmd [list $resultSet foreach {*}$opts -- $varname $script]
|
| 665 |
+
set status [catch {
|
| 666 |
+
uplevel 1 $cmd
|
| 667 |
+
} result options]
|
| 668 |
+
|
| 669 |
+
# Destroy the result set
|
| 670 |
+
|
| 671 |
+
catch {
|
| 672 |
+
rename $resultSet {}
|
| 673 |
+
}
|
| 674 |
+
|
| 675 |
+
# Adjust return level in the case that the script [return]s
|
| 676 |
+
|
| 677 |
+
if {$status == 2} {
|
| 678 |
+
set options [dict merge {-level 1} $options[set options {}]]
|
| 679 |
+
dict incr options -level
|
| 680 |
+
}
|
| 681 |
+
return -options $options $result
|
| 682 |
+
}
|
| 683 |
+
|
| 684 |
+
# The 'close' method is syntactic sugar for invoking the destructor
|
| 685 |
+
|
| 686 |
+
method close {} {
|
| 687 |
+
my destroy
|
| 688 |
+
}
|
| 689 |
+
|
| 690 |
+
# Derived classes are expected to implement their own constructors,
|
| 691 |
+
# plus the following methods:
|
| 692 |
+
|
| 693 |
+
# paramtype paramName ?direction? type ?scale ?precision??
|
| 694 |
+
# Declares the type of a parameter in the statement
|
| 695 |
+
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
#------------------------------------------------------------------------------
|
| 699 |
+
#
|
| 700 |
+
# Class: tdbc::resultset
|
| 701 |
+
#
|
| 702 |
+
# Class that represents a result set in a generic database.
|
| 703 |
+
#
|
| 704 |
+
#------------------------------------------------------------------------------
|
| 705 |
+
|
| 706 |
+
oo::class create tdbc::resultset {
|
| 707 |
+
|
| 708 |
+
constructor {} { }
|
| 709 |
+
|
| 710 |
+
# The 'allrows' method returns a list of all rows that a given
|
| 711 |
+
# result set returns.
|
| 712 |
+
|
| 713 |
+
method allrows args {
|
| 714 |
+
|
| 715 |
+
variable ::tdbc::generalError
|
| 716 |
+
|
| 717 |
+
# Parse args
|
| 718 |
+
|
| 719 |
+
set args [::tdbc::ParseConvenienceArgs $args[set args {}] opts]
|
| 720 |
+
if {[llength $args] != 0} {
|
| 721 |
+
set errorcode $generalError
|
| 722 |
+
lappend errorcode wrongNumArgs
|
| 723 |
+
return -code error -errorcode $errorcode \
|
| 724 |
+
"wrong # args: should be [lrange [info level 0] 0 1]\
|
| 725 |
+
?-option value?... ?--? varName script"
|
| 726 |
+
}
|
| 727 |
+
|
| 728 |
+
# Do -columnsvariable if requested
|
| 729 |
+
|
| 730 |
+
if {[dict exists $opts -columnsvariable]} {
|
| 731 |
+
upvar 1 [dict get $opts -columnsvariable] columns
|
| 732 |
+
}
|
| 733 |
+
|
| 734 |
+
# Assemble the results
|
| 735 |
+
|
| 736 |
+
if {[dict get $opts -as] eq {lists}} {
|
| 737 |
+
set delegate nextlist
|
| 738 |
+
} else {
|
| 739 |
+
set delegate nextdict
|
| 740 |
+
}
|
| 741 |
+
set results [list]
|
| 742 |
+
while {1} {
|
| 743 |
+
set columns [my columns]
|
| 744 |
+
while {[my $delegate row]} {
|
| 745 |
+
lappend results $row
|
| 746 |
+
}
|
| 747 |
+
if {![my nextresults]} break
|
| 748 |
+
}
|
| 749 |
+
return $results
|
| 750 |
+
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
# The 'foreach' method runs a script on each row from a result set.
|
| 754 |
+
|
| 755 |
+
method foreach args {
|
| 756 |
+
|
| 757 |
+
variable ::tdbc::generalError
|
| 758 |
+
|
| 759 |
+
# Grab keyword-value parameters
|
| 760 |
+
|
| 761 |
+
set args [::tdbc::ParseConvenienceArgs $args[set args {}] opts]
|
| 762 |
+
|
| 763 |
+
# Check positional parameters
|
| 764 |
+
|
| 765 |
+
if {[llength $args] != 2} {
|
| 766 |
+
set errorcode $generalError
|
| 767 |
+
lappend errorcode wrongNumArgs
|
| 768 |
+
return -code error -errorcode $errorcode \
|
| 769 |
+
"wrong # args: should be [lrange [info level 0] 0 1]\
|
| 770 |
+
?-option value?... ?--? varName script"
|
| 771 |
+
}
|
| 772 |
+
|
| 773 |
+
# Do -columnsvariable if requested
|
| 774 |
+
|
| 775 |
+
if {[dict exists $opts -columnsvariable]} {
|
| 776 |
+
upvar 1 [dict get $opts -columnsvariable] columns
|
| 777 |
+
}
|
| 778 |
+
|
| 779 |
+
# Iterate over the groups of results
|
| 780 |
+
while {1} {
|
| 781 |
+
|
| 782 |
+
# Export column names to caller
|
| 783 |
+
|
| 784 |
+
set columns [my columns]
|
| 785 |
+
|
| 786 |
+
# Iterate over the rows of one group of results
|
| 787 |
+
|
| 788 |
+
upvar 1 [lindex $args 0] row
|
| 789 |
+
if {[dict get $opts -as] eq {lists}} {
|
| 790 |
+
set delegate nextlist
|
| 791 |
+
} else {
|
| 792 |
+
set delegate nextdict
|
| 793 |
+
}
|
| 794 |
+
while {[my $delegate row]} {
|
| 795 |
+
set status [catch {
|
| 796 |
+
uplevel 1 [lindex $args 1]
|
| 797 |
+
} result options]
|
| 798 |
+
switch -exact -- $status {
|
| 799 |
+
0 - 4 { # OK or CONTINUE
|
| 800 |
+
}
|
| 801 |
+
2 { # RETURN
|
| 802 |
+
set options \
|
| 803 |
+
[dict merge {-level 1} $options[set options {}]]
|
| 804 |
+
dict incr options -level
|
| 805 |
+
return -options $options $result
|
| 806 |
+
}
|
| 807 |
+
3 { # BREAK
|
| 808 |
+
set broken 1
|
| 809 |
+
break
|
| 810 |
+
}
|
| 811 |
+
default { # ERROR or unknown status
|
| 812 |
+
return -options $options $result
|
| 813 |
+
}
|
| 814 |
+
}
|
| 815 |
+
}
|
| 816 |
+
|
| 817 |
+
# Advance to the next group of results if there is one
|
| 818 |
+
|
| 819 |
+
if {[info exists broken] || ![my nextresults]} {
|
| 820 |
+
break
|
| 821 |
+
}
|
| 822 |
+
}
|
| 823 |
+
|
| 824 |
+
return
|
| 825 |
+
}
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
# The 'nextrow' method retrieves a row in the form of either
|
| 829 |
+
# a list or a dictionary.
|
| 830 |
+
|
| 831 |
+
method nextrow {args} {
|
| 832 |
+
|
| 833 |
+
variable ::tdbc::generalError
|
| 834 |
+
|
| 835 |
+
set opts [dict create -as dicts]
|
| 836 |
+
set i 0
|
| 837 |
+
|
| 838 |
+
# Munch keyword options off the front of the command arguments
|
| 839 |
+
|
| 840 |
+
foreach {key value} $args {
|
| 841 |
+
if {[string index $key 0] eq {-}} {
|
| 842 |
+
switch -regexp -- $key {
|
| 843 |
+
-as? {
|
| 844 |
+
dict set opts -as $value
|
| 845 |
+
}
|
| 846 |
+
-- {
|
| 847 |
+
incr i
|
| 848 |
+
break
|
| 849 |
+
}
|
| 850 |
+
default {
|
| 851 |
+
set errorcode $generalError
|
| 852 |
+
lappend errorcode badOption $key
|
| 853 |
+
return -code error -errorcode $errorcode \
|
| 854 |
+
"bad option \"$key\":\
|
| 855 |
+
must be -as or -columnsvariable"
|
| 856 |
+
}
|
| 857 |
+
}
|
| 858 |
+
} else {
|
| 859 |
+
break
|
| 860 |
+
}
|
| 861 |
+
incr i 2
|
| 862 |
+
}
|
| 863 |
+
|
| 864 |
+
set args [lrange $args $i end]
|
| 865 |
+
if {[llength $args] != 1} {
|
| 866 |
+
set errorcode $generalError
|
| 867 |
+
lappend errorcode wrongNumArgs
|
| 868 |
+
return -code error -errorcode $errorcode \
|
| 869 |
+
"wrong # args: should be [lrange [info level 0] 0 1]\
|
| 870 |
+
?-option value?... ?--? varName"
|
| 871 |
+
}
|
| 872 |
+
upvar 1 [lindex $args 0] row
|
| 873 |
+
if {[dict get $opts -as] eq {lists}} {
|
| 874 |
+
set delegate nextlist
|
| 875 |
+
} else {
|
| 876 |
+
set delegate nextdict
|
| 877 |
+
}
|
| 878 |
+
return [my $delegate row]
|
| 879 |
+
}
|
| 880 |
+
|
| 881 |
+
# Derived classes must override 'nextresults' if a single
|
| 882 |
+
# statement execution can yield multiple sets of results
|
| 883 |
+
|
| 884 |
+
method nextresults {} {
|
| 885 |
+
return 0
|
| 886 |
+
}
|
| 887 |
+
|
| 888 |
+
# Derived classes must override 'outputparams' if statements can
|
| 889 |
+
# have output parameters.
|
| 890 |
+
|
| 891 |
+
method outputparams {} {
|
| 892 |
+
return {}
|
| 893 |
+
}
|
| 894 |
+
|
| 895 |
+
# The 'close' method is syntactic sugar for destroying the result set.
|
| 896 |
+
|
| 897 |
+
method close {} {
|
| 898 |
+
my destroy
|
| 899 |
+
}
|
| 900 |
+
|
| 901 |
+
# Derived classes are expected to implement the following methods:
|
| 902 |
+
|
| 903 |
+
# constructor and destructor.
|
| 904 |
+
# Constructor accepts a statement and an optional
|
| 905 |
+
# a dictionary of substituted parameters and
|
| 906 |
+
# executes the statement against the database. If
|
| 907 |
+
# the dictionary is not supplied, then the default
|
| 908 |
+
# is to get params from variables in the caller's scope).
|
| 909 |
+
# columns
|
| 910 |
+
# -- Returns a list of the names of the columns in the result.
|
| 911 |
+
# nextdict variableName
|
| 912 |
+
# -- Stores the next row of the result set in the given variable
|
| 913 |
+
# in caller's scope, in the form of a dictionary that maps
|
| 914 |
+
# column names to values.
|
| 915 |
+
# nextlist variableName
|
| 916 |
+
# -- Stores the next row of the result set in the given variable
|
| 917 |
+
# in caller's scope, in the form of a list of cells.
|
| 918 |
+
# rowcount
|
| 919 |
+
# -- Returns a count of rows affected by the statement, or -1
|
| 920 |
+
# if the count of rows has not been determined.
|
| 921 |
+
|
| 922 |
+
}
|
evalkit_llava/lib/tdbc1.1.7/tdbcConfig.sh
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# tdbcConfig.sh --
|
| 2 |
+
#
|
| 3 |
+
# This shell script (for sh) is generated automatically by TDBC's configure
|
| 4 |
+
# script. It will create shell variables for most of the configuration options
|
| 5 |
+
# discovered by the configure script. This script is intended to be included
|
| 6 |
+
# by the configure scripts for TDBC extensions so that they don't have to
|
| 7 |
+
# figure this all out for themselves.
|
| 8 |
+
#
|
| 9 |
+
# The information in this file is specific to a single platform.
|
| 10 |
+
#
|
| 11 |
+
# RCS: @(#) $Id$
|
| 12 |
+
|
| 13 |
+
# TDBC's version number
|
| 14 |
+
tdbc_VERSION=1.1.7
|
| 15 |
+
TDBC_VERSION=1.1.7
|
| 16 |
+
|
| 17 |
+
# Name of the TDBC library - may be either a static or shared library
|
| 18 |
+
tdbc_LIB_FILE=libtdbc1.1.7.so
|
| 19 |
+
TDBC_LIB_FILE=libtdbc1.1.7.so
|
| 20 |
+
|
| 21 |
+
# String to pass to the linker to pick up the TDBC library from its build dir
|
| 22 |
+
tdbc_BUILD_LIB_SPEC="-L/croot/tk_1714770549989/work/tcl8.6.14/unix/pkgs/tdbc1.1.7 -ltdbc1.1.7"
|
| 23 |
+
TDBC_BUILD_LIB_SPEC="-L/croot/tk_1714770549989/work/tcl8.6.14/unix/pkgs/tdbc1.1.7 -ltdbc1.1.7"
|
| 24 |
+
|
| 25 |
+
# String to pass to the linker to pick up the TDBC library from its installed
|
| 26 |
+
# dir.
|
| 27 |
+
tdbc_LIB_SPEC="-L/root/envs/evalkit_llava/lib/tdbc1.1.7 -ltdbc1.1.7"
|
| 28 |
+
TDBC_LIB_SPEC="-L/root/envs/evalkit_llava/lib/tdbc1.1.7 -ltdbc1.1.7"
|
| 29 |
+
|
| 30 |
+
# Name of the TBDC stub library
|
| 31 |
+
tdbc_STUB_LIB_FILE="libtdbcstub1.1.7.a"
|
| 32 |
+
TDBC_STUB_LIB_FILE="libtdbcstub1.1.7.a"
|
| 33 |
+
|
| 34 |
+
# String to pass to the linker to pick up the TDBC stub library from its
|
| 35 |
+
# build directory
|
| 36 |
+
tdbc_BUILD_STUB_LIB_SPEC="-L/croot/tk_1714770549989/work/tcl8.6.14/unix/pkgs/tdbc1.1.7 -ltdbcstub1.1.7"
|
| 37 |
+
TDBC_BUILD_STUB_LIB_SPEC="-L/croot/tk_1714770549989/work/tcl8.6.14/unix/pkgs/tdbc1.1.7 -ltdbcstub1.1.7"
|
| 38 |
+
|
| 39 |
+
# String to pass to the linker to pick up the TDBC stub library from its
|
| 40 |
+
# installed directory
|
| 41 |
+
tdbc_STUB_LIB_SPEC="-L/root/envs/evalkit_llava/lib/tdbc1.1.7 -ltdbcstub1.1.7"
|
| 42 |
+
TDBC_STUB_LIB_SPEC="-L/root/envs/evalkit_llava/lib/tdbc1.1.7 -ltdbcstub1.1.7"
|
| 43 |
+
|
| 44 |
+
# Path name of the TDBC stub library in its build directory
|
| 45 |
+
tdbc_BUILD_STUB_LIB_PATH="/croot/tk_1714770549989/work/tcl8.6.14/unix/pkgs/tdbc1.1.7/libtdbcstub1.1.7.a"
|
| 46 |
+
TDBC_BUILD_STUB_LIB_PATH="/croot/tk_1714770549989/work/tcl8.6.14/unix/pkgs/tdbc1.1.7/libtdbcstub1.1.7.a"
|
| 47 |
+
|
| 48 |
+
# Path name of the TDBC stub library in its installed directory
|
| 49 |
+
tdbc_STUB_LIB_PATH="/root/envs/evalkit_llava/lib/tdbc1.1.7/libtdbcstub1.1.7.a"
|
| 50 |
+
TDBC_STUB_LIB_PATH="/root/envs/evalkit_llava/lib/tdbc1.1.7/libtdbcstub1.1.7.a"
|
| 51 |
+
|
| 52 |
+
# Location of the top-level source directories from which TDBC was built.
|
| 53 |
+
# This is the directory that contains doc/, generic/ and so on. If TDBC
|
| 54 |
+
# was compiled in a directory other than the source directory, this still
|
| 55 |
+
# points to the location of the sources, not the location where TDBC was
|
| 56 |
+
# compiled.
|
| 57 |
+
tdbc_SRC_DIR="/croot/tk_1714770549989/work/tcl8.6.14/pkgs/tdbc1.1.7"
|
| 58 |
+
TDBC_SRC_DIR="/croot/tk_1714770549989/work/tcl8.6.14/pkgs/tdbc1.1.7"
|
| 59 |
+
|
| 60 |
+
# String to pass to the compiler so that an extension can find installed TDBC
|
| 61 |
+
# headers
|
| 62 |
+
tdbc_INCLUDE_SPEC="-I/root/envs/evalkit_llava/include"
|
| 63 |
+
TDBC_INCLUDE_SPEC="-I/root/envs/evalkit_llava/include"
|
| 64 |
+
|
| 65 |
+
# String to pass to the compiler so that an extension can find TDBC headers
|
| 66 |
+
# in the source directory
|
| 67 |
+
tdbc_BUILD_INCLUDE_SPEC="-I/croot/tk_1714770549989/work/tcl8.6.14/pkgs/tdbc1.1.7/generic"
|
| 68 |
+
TDBC_BUILD_INCLUDE_SPEC="-I/croot/tk_1714770549989/work/tcl8.6.14/pkgs/tdbc1.1.7/generic"
|
| 69 |
+
|
| 70 |
+
# Path name where .tcl files in the tdbc package appear at run time.
|
| 71 |
+
tdbc_LIBRARY_PATH="/root/envs/evalkit_llava/lib/tdbc1.1.7"
|
| 72 |
+
TDBC_LIBRARY_PATH="/root/envs/evalkit_llava/lib/tdbc1.1.7"
|
| 73 |
+
|
| 74 |
+
# Path name where .tcl files in the tdbc package appear at build time.
|
| 75 |
+
tdbc_BUILD_LIBRARY_PATH="/croot/tk_1714770549989/work/tcl8.6.14/pkgs/tdbc1.1.7/library"
|
| 76 |
+
TDBC_BUILD_LIBRARY_PATH="/croot/tk_1714770549989/work/tcl8.6.14/pkgs/tdbc1.1.7/library"
|
| 77 |
+
|
| 78 |
+
# Additional flags that must be passed to the C compiler to use tdbc
|
| 79 |
+
tdbc_CFLAGS=
|
| 80 |
+
TDBC_CFLAGS=
|
| 81 |
+
|