What changed, and why it matters
This commit swaps Monero's command-line input library from GNU readline to a bundled, customized version of linenoise. The stated goal is to reduce external dependencies, but the change also removes several risky behaviors: bracketed-paste handling that could execute pasted commands, terminal control-character passthrough, and UTF-8 parsing that could read past buffer ends. The new code adds input sanitization, caps paste sizes, and makes Ctrl+C/\ signal handling more predictable. It is a large refactor, so it may introduce new bugs even while fixing old ones.
Treat this as a dependency-hardening change rather than a discrete vulnerability patch. Review the vendored linenoise.c diff for remaining terminal escape handling and signal races, run interactive wallet/daemon tests on TTY and piped input, and monitor for regressions in command history, completion, and pasted input behavior. Because the commit is large and replaces a mature library, consider fuzzing the linenoise input parser and auditing the new poll/select loops for deadlock or missed wakeups.
Security signals we found
Replaced external readline/ncurses with vendored linenoise to reduce attack surface
Removed bracketed-paste mode that can auto-submit pasted commands
Added control-character and C1-control sanitization in display and returned input
Hardened UTF-8 decoder with availability checks to prevent out-of-bounds reads
Capped line/paste length and added time-budgeted paste feeding
Changed terminal raw-mode flags to keep signal generation enabled and disable suspend
Applied C security hardening flags to the new linenoise target
Evidence from the diff
The patch removes the readline/ncurses dependency tree and embeds a modified linenoise. Security-relevant changes in the vendored linenoise.c include: bounds-aware utf8DecodeChar() that no longer assumes valid UTF-8; removal of bracketed-paste mode (ESC[?2004h/l) and the synchronous linenoiseEditPaste() that could auto-execute multi-line pasted input; replacement with a chunked, time-budgeted paste feeder; sanitization of control characters and C1 controls before display; disabling of OPOST stripping and ISIG removal while keeping ECHO/ICANON/IEXTEN off; VSUSP disabled to avoid ^Z suspend; TCSADRAIN instead of TCSAFLUSH to preserve typed-ahead input; a 1 MiB line buffer cap; and stripping of unsafe bytes in the Monero wrapper before returning a line. The commit does not frame itself as a security fix, but the modifications address well-known terminal-paste and control-sequence attack patterns.
Changed components
contrib/epee/src/readline_buffer.cppexternal/linenoise/linenoise.cexternal/linenoise/CMakeLists.txtcontrib/epee/include/readline_buffer.hcontrib/epee/include/console_handler.hsrc/simplewallet/CMakeLists.txtsrc/daemon/CMakeLists.txtsrc/gen_multisig/CMakeLists.txtCMakeLists.txtInspect captured patch +600 / −7183
### .github/workflows/build.yml
@@ -117,7 +117,7 @@ jobs:
image: archlinux:latest
steps:
- name: install dependencies
- run: pacman -Syyu --noconfirm base-devel git rust cmake boost boost-libs openssl zeromq unbound libsodium readline expat gtest python3 doxygen graphviz hidapi libusb protobuf ccache
+ run: pacman -Syyu --noconfirm base-devel git rust cmake boost boost-libs openssl zeromq unbound libsodium expat gtest python3 doxygen graphviz hidapi libusb protobuf ccache
- name: configure git
run: git config --global --add safe.directory '*'
- uses: actions/checkout@v5
### CMakeLists.txt
@@ -651,6 +651,11 @@ endfunction ()
add_subdirectory(external)
+# Final setup for linenoise
+if(NOT WIN32)
+ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/external/linenoise)
+endif()
+
# Final setup for libunbound
include_directories(${UNBOUND_INCLUDE_DIR})
@@ -876,6 +881,9 @@ include(CheckTrezor)
# external/ is added before the hardening flags are computed
# apply them to its input-facing C libraries
set_property(TARGET polyseed_static utf8proc APPEND_STRING PROPERTY COMPILE_FLAGS " ${C_SECURITY_FLAGS}")
+ if(TARGET linenoise)
+ set_property(TARGET linenoise APPEND_STRING PROPERTY COMPILE_FLAGS " ${C_SECURITY_FLAGS}")
+ endif()
# With GCC 6.1.1 the compiled binary malfunctions due to aliasing. Until that
# is fixed in the code (Issue #847), force compiler to be conservative.
@@ -1016,25 +1024,7 @@ if ((CMAKE_CXX_COMPILER_ID STREQUAL "GNU") AND (CMAKE_CXX_COMPILER_VERSION VERSI
list(APPEND EXTRA_LIBRARIES "stdc++fs")
endif()
-if(NOT OPENBSD)
- option(USE_READLINE "Build with GNU readline support." ON)
-endif()
-if(USE_READLINE AND NOT DEPENDS)
- find_package(Readline)
- if(READLINE_FOUND AND GNU_READLINE_FOUND)
- add_definitions(-DHAVE_READLINE)
- include_directories(${Readline_INCLUDE_DIR})
- message(STATUS "Found readline library at: ${Readline_ROOT_DIR}")
- set(EPEE_READLINE epee_readline)
- else()
- message(STATUS "Could not find GNU readline library so building without readline support")
- endif()
-elseif(USE_READLINE AND DEPENDS AND NOT MINGW)
- find_path(Readline_INCLUDE_PATH readline/readline.h)
- find_library(Readline_LIBRARY readline)
- find_library(Terminfo_LIBRARY tinfo)
- set(Readline_LIBRARY "${Readline_LIBRARY};${Terminfo_LIBRARY}")
- set(GNU_READLINE_LIBRARY ${Readline_LIBRARY})
+if(NOT WIN32 AND NOT OPENBSD)
add_definitions(-DHAVE_READLINE)
set(EPEE_READLINE epee_readline)
endif()
### Dockerfile
@@ -4,20 +4,18 @@ COPY --from=stagex/core-openssl:sx2026.06.0@sha256:5fbecea19913b8c9bb2e5976b0383
COPY --from=stagex/core-ca-certificates:sx2026.06.0@sha256:ea7076d1bb83693fa4766c9cbd8132e59ac0981799fd8b58961c245cd360b66d . /
COPY --from=stagex/user-patch:sx2026.06.0@sha256:1d4428893f0ea9abfabc1fb5e365c5593fe10c6ed8ffc592d6528157a4299942 . /
COPY --from=stagex/core-cmake:sx2026.06.0@sha256:626a3fdf157efacd00c3ceb0529ae80dde1072d64fa1925aafe9819bebc92047 . /
-COPY --from=stagex/core-ncurses:sx2026.06.0@sha256:90cc5d029c5073405f9db39c88b9509b8959bbd8f19d8cd02c20e9350cc40254 . /
COPY --from=stagex/pallet-rust:sx2026.06.0@sha256:59d4d0c9e232a05ecb99348f7216b521af1b914a430059dbdb9130018f2afde1 . /
ENV TARGET="x86_64-pc-linux-musl"
WORKDIR /monero
COPY . .
-RUN make -C contrib/depends -j$(nproc) download-linux NO_WALLET=1 NO_READLINE=1
+RUN make -C contrib/depends -j$(nproc) download-linux NO_WALLET=1
-RUN make -C contrib/depends -j$(nproc) HOST="${TARGET}" NO_WALLET=1 NO_READLINE=1
+RUN make -C contrib/depends -j$(nproc) HOST="${TARGET}" NO_WALLET=1
RUN cmake --toolchain "contrib/depends/${TARGET}/share/toolchain.cmake" -S . -B build \
-DSTACK_TRACE=OFF \
- -DUSE_READLINE=OFF \
-DUSE_DEVICE_TREZOR=OFF \
-DSTATIC_FLAGS="-static-pie" && \
cmake --build build --target daemon --parallel $(nproc)
### README.md
@@ -148,7 +148,6 @@ The following table summarizes the tools and libraries required to build. A few
| libunbound | 1.4.16 | NO | `libunbound-dev` | `unbound` | `unbound-devel` | `unbound-devel` | NO | DNS resolver |
| libsodium | ? | NO | `libsodium-dev` | `libsodium` | `libsodium-devel` | `libsodium-devel` | NO | cryptography |
| libunwind | any | NO | `libunwind-dev` | `libunwind` | `libunwind-devel` | `libunwind-devel` | YES | Stack traces |
-| libreadline | 6.3.0 | NO | `libreadline-dev` | `readline` | `readline-devel` | `readline-devel` | YES | Input editing |
| GTest | 1.5 | YES | `libgtest-dev` | `gtest` | `gtest-devel` | `gtest-devel` | YES | Test suite |
| ccache | any | NO | `ccache` | `ccache` | `ccache` | `ccache` | YES | Compil. cache |
| Doxygen | any | NO | `doxygen` | `doxygen` | `doxygen` | `doxygen` | YES | Documentation |
@@ -162,23 +161,23 @@ The following table summarizes the tools and libraries required to build. A few
Install all dependencies at once on Debian/Ubuntu:
```
-sudo apt update && sudo apt install build-essential cmake pkg-config libssl-dev libzmq3-dev libunbound-dev libsodium-dev libunwind-dev libreadline-dev libhidapi-dev libusb-1.0-0-dev libprotobuf-dev protobuf-compiler libboost-chrono-dev libboost-date-time-dev libboost-filesystem-dev libboost-locale-dev libboost-program-options-dev libboost-regex-dev libboost-serialization-dev libboost-system-dev libboost-thread-dev python3 ccache doxygen graphviz git curl
+sudo apt update && sudo apt install build-essential cmake pkg-config libssl-dev libzmq3-dev libunbound-dev libsodium-dev libunwind-dev libhidapi-dev libusb-1.0-0-dev libprotobuf-dev protobuf-compiler libboost-chrono-dev libboost-date-time-dev libboost-filesystem-dev libboost-locale-dev libboost-program-options-dev libboost-regex-dev libboost-serialization-dev libboost-system-dev libboost-thread-dev python3 ccache doxygen graphviz git curl
```
Install all dependencies at once on Arch:
```
-sudo pacman -Syu --needed base-devel cmake boost boost-libs openssl zeromq unbound libsodium libunwind readline python ccache doxygen graphviz hidapi libusb protobuf rust
+sudo pacman -Syu --needed base-devel cmake boost boost-libs openssl zeromq unbound libsodium libunwind python ccache doxygen graphviz hidapi libusb protobuf rust
```
Install all dependencies at once on Fedora:
```
-sudo dnf install gcc gcc-c++ cmake pkgconf boost-devel openssl-devel zeromq-devel unbound-devel libsodium-devel libunwind-devel readline-devel ccache doxygen graphviz hidapi-devel libusb1-devel protobuf-devel protobuf-compiler rust cargo
+sudo dnf install gcc gcc-c++ cmake pkgconf boost-devel openssl-devel zeromq-devel unbound-devel libsodium-devel libunwind-devel ccache doxygen graphviz hidapi-devel libusb1-devel protobuf-devel protobuf-compiler rust cargo
```
Install all dependencies at once on openSUSE:
```
-sudo zypper ref && sudo zypper in cppzmq-devel libboost_chrono-devel libboost_date_time-devel libboost_filesystem-devel libboost_locale-devel libboost_program_options-devel libboost_regex-devel libboost_serialization-devel libboost_system-devel libboost_thread-devel libsodium-devel libunwind-devel unbound-devel cmake doxygen ccache fdupes gcc-c++ libevent-devel libopenssl-devel pkgconf-pkg-config readline-devel patterns-devel-C-C++-devel_C_C++ rust cargo
+sudo zypper ref && sudo zypper in cppzmq-devel libboost_chrono-devel libboost_date_time-devel libboost_filesystem-devel libboost_locale-devel libboost_program_options-devel libboost_regex-devel libboost_serialization-devel libboost_system-devel libboost_thread-devel libsodium-devel libunwind-devel unbound-devel cmake doxygen ccache fdupes gcc-c++ libevent-devel libopenssl-devel pkgconf-pkg-config patterns-devel-C-C++-devel_C_C++ rust cargo
```
Install all dependencies at once on macOS with the provided Brewfile:
@@ -390,7 +389,7 @@ Then you need to increase the data ulimit size to 2GB and try again: `ulimit -d
### On NetBSD:
-Check that the dependencies are present: `pkg_info -c libexecinfo boost-headers boost-libs protobuf readline libusb1 zeromq git-base pkgconf gmake cmake | more`, and install any that are reported missing, using `pkg_add` or from your pkgsrc tree. Readline is optional but worth having.
+Check that the dependencies are present: `pkg_info -c libexecinfo boost-headers boost-libs protobuf libusb1 zeromq git-base pkgconf gmake cmake | more`, and install any that are reported missing, using `pkg_add` or from your pkgsrc tree.
Third-party dependencies are usually under `/usr/pkg/`, but if you have a custom setup, adjust the "/usr/pkg" (below) accordingly.
### cmake/FindReadline.cmake
@@ -1,90 +0,0 @@
-# - Try to find readline include dirs and libraries
-#
-# Usage of this module as follows:
-#
-# find_package(Readline)
-#
-# Variables used by this module, they can change the default behaviour and need
-# to be set before calling find_package:
-#
-# Readline_ROOT_DIR Set this variable to the root installation of
-# readline if the module has problems finding the
-# proper installation path.
-#
-# Variables defined by this module:
-#
-# READLINE_FOUND System has readline, include and lib dirs found
-# GNU_READLINE_FOUND Version of readline found is GNU readline, not libedit!
-# LIBEDIT_FOUND Version of readline found is libedit, not GNU readline!
-# Readline_INCLUDE_DIR The readline include directories.
-# Readline_LIBRARY The readline library.
-# GNU_READLINE_LIBRARY The GNU readline library or empty string.
-# LIBEDIT_LIBRARY The libedit library or empty string.
-
-find_path(Readline_ROOT_DIR
- NAMES include/readline/readline.h
- HINTS /usr/local/opt/readline/ /opt/homebrew/opt/readline/ /opt/local/ /usr/local/ /usr/
-)
-
-find_path(Readline_INCLUDE_DIR
- NAMES readline/readline.h
- PATHS ${Readline_ROOT_DIR}/include
- NO_DEFAULT_PATH
-)
-
-find_library(Readline_LIBRARY
- NAMES readline
- PATHS ${Readline_ROOT_DIR}/lib
- NO_DEFAULT_PATH
-)
-
-find_library(Termcap_LIBRARY
- NAMES tinfo termcap ncursesw ncurses cursesw curses
-)
-
-if(Readline_INCLUDE_DIR AND Readline_LIBRARY)
- set(READLINE_FOUND TRUE)
-else(Readline_INCLUDE_DIR AND Readline_LIBRARY)
- FIND_LIBRARY(Readline_LIBRARY NAMES readline PATHS Readline_ROOT_DIR)
- include(FindPackageHandleStandardArgs)
- FIND_PACKAGE_HANDLE_STANDARD_ARGS(Readline DEFAULT_MSG Readline_INCLUDE_DIR Readline_LIBRARY )
- MARK_AS_ADVANCED(Readline_INCLUDE_DIR Readline_LIBRARY)
-endif(Readline_INCLUDE_DIR AND Readline_LIBRARY)
-
-mark_as_advanced(
- Readline_ROOT_DIR
- Readline_INCLUDE_DIR
- Readline_LIBRARY
-)
-
-set(CMAKE_REQUIRED_INCLUDES ${Readline_INCLUDE_DIR})
-set(CMAKE_REQUIRED_LIBRARIES ${Readline_LIBRARY})
-
-include(CheckFunctionExists)
-check_function_exists(rl_copy_text HAVE_COPY_TEXT)
-check_function_exists(rl_filename_completion_function HAVE_COMPLETION_FUNCTION)
-
-if(NOT HAVE_COMPLETION_FUNCTION)
- if (Readline_LIBRARY)
- set(CMAKE_REQUIRED_LIBRARIES ${Readline_LIBRARY} ${Termcap_LIBRARY})
- endif(Readline_LIBRARY)
- check_function_exists(rl_copy_text HAVE_COPY_TEXT_TC)
- check_function_exists(rl_filename_completion_function HAVE_COMPLETION_FUNCTION_TC)
- set(HAVE_COMPLETION_FUNCTION ${HAVE_COMPLETION_FUNCTION_TC})
- set(HAVE_COPY_TEXT ${HAVE_COPY_TEXT_TC})
- if(HAVE_COMPLETION_FUNCTION)
- set(Readline_LIBRARY ${Readline_LIBRARY} ${Termcap_LIBRARY})
- endif(HAVE_COMPLETION_FUNCTION)
-endif(NOT HAVE_COMPLETION_FUNCTION)
-
-set(LIBEDIT_LIBRARY "")
-set(GNU_READLINE_LIBRARY "")
-
-if(HAVE_COMPLETION_FUNCTION AND HAVE_COPY_TEXT)
- set(GNU_READLINE_FOUND TRUE)
- set(GNU_READLINE_LIBRARY ${Readline_LIBRARY})
-elseif(READLINE_FOUND AND NOT HAVE_COPY_TEXT)
- set(LIBEDIT_FOUND TRUE)
- set(LIBEDIT_LIBRARY ${Readline_LIBRARY})
-endif(HAVE_COMPLETION_FUNCTION AND HAVE_COPY_TEXT)
-
### contrib/brew/Brewfile
@@ -15,7 +15,6 @@ brew "hidapi"
brew "zmq"
brew "unbound"
brew "libsodium"
-brew "readline"
brew "ccache"
brew "doxygen"
brew "graphviz"
### contrib/depends/Makefile
@@ -12,7 +12,6 @@ C_STANDARD ?= c11
CXX_STANDARD ?= c++17
NO_WALLET ?=
-NO_READLINE ?=
BUILD = $(shell ./config.guess)
HOST ?= $(BUILD)
@@ -116,12 +115,10 @@ build_id_string:=$(realpath $(GUIX_ENVIRONMENT))
$(host_arch)_$(host_os)_id_string:=$(realpath $(GUIX_ENVIRONMENT))
endif
-readline_packages_$(NO_READLINE) = $(readline_packages)
-
wallet_packages_$(NO_WALLET) = $(wallet_packages)
wallet_native_packages_$(NO_WALLET) = $(wallet_native_packages)
-packages += $($(host_arch)_$(host_os)_packages) $($(host_os)_packages) $(wallet_packages_) $(readline_packages_)
+packages += $($(host_arch)_$(host_os)_packages) $($(host_os)_packages) $(wallet_packages_)
native_packages += $($(host_arch)_$(host_os)_native_packages) $($(host_os)_native_packages) $(wallet_native_packages_)
all_packages = $(packages) $(native_packages)
### contrib/depends/packages/darwin_sdk.mk
@@ -4,11 +4,7 @@ $(package)_download_path=https://bitcoincore.org/depends-sources/sdks
$(package)_file_name=Xcode-12.2-12B45b-extracted-SDK-with-libcxx-headers.tar.gz
$(package)_sha256_hash=df75d30ecafc429e905134333aeae56ac65fac67cb4182622398fd717df77619
-# Prevent clang from including readline headers from the SDK. We statically link
-# our own version of readline.
-
define $(package)_stage_cmds
mkdir -p $($(package)_staging_prefix_dir)/SDK &&\
- rm -rf usr/include/readline && \
mv * $($(package)_staging_prefix_dir)/SDK
endef
### contrib/depends/packages/ncurses.mk
@@ -1,64 +0,0 @@
-package=ncurses
-$(package)_version=6.1
-$(package)_download_path=https://ftp.gnu.org/gnu/ncurses
-$(package)_file_name=$(package)-$($(package)_version).tar.gz
-$(package)_sha256_hash=aa057eeeb4a14d470101eff4597d5833dcef5965331be3528c08d99cebaa0d17
-$(package)_patches=fallback.c
-
-define $(package)_set_vars
- $(package)_build_opts=CC="$($(package)_cc)"
- $(package)_config_env=cf_cv_ar_flags=""
- $(package)_config_opts=--prefix=$(host_prefix)
- $(package)_config_opts+=--disable-shared
- $(package)_config_opts+=--with-build-cc=$(build_CC)
- $(package)_config_opts+=--without-debug
- $(package)_config_opts+=--without-ada
- $(package)_config_opts+=--without-cxx-binding
- $(package)_config_opts+=--without-cxx
- $(package)_config_opts+=--without-ticlib
- $(package)_config_opts+=--without-tic
- $(package)_config_opts+=--without-progs
- $(package)_config_opts+=--without-tests
- $(package)_config_opts+=--without-tack
- $(package)_config_opts+=--without-manpages
- $(package)_config_opts+=--with-termlib=tinfo
- $(package)_config_opts+=--disable-tic-depends
- $(package)_config_opts+=--disable-big-strings
- $(package)_config_opts+=--disable-ext-colors
- $(package)_config_opts+=--enable-pc-files
- $(package)_config_opts+=--host=$(HOST)
- $(pacakge)_config_opts+=--without-shared
- $(pacakge)_config_opts+=--without-pthread
- $(pacakge)_config_opts+=--disable-rpath
- $(pacakge)_config_opts+=--disable-colorfgbg
- $(pacakge)_config_opts+=--disable-ext-mouse
- $(pacakge)_config_opts+=--disable-symlinks
- $(pacakge)_config_opts+=--enable-warnings
- $(pacakge)_config_opts+=--enable-assertions
- $(package)_config_opts+=--with-default-terminfo-dir=/etc/_terminfo_
- $(package)_config_opts+=--with-terminfo-dirs=/etc/_terminfo_
- $(pacakge)_config_opts+=--enable-database
- $(pacakge)_config_opts+=--enable-sp-funcs
- $(pacakge)_config_opts+=--disable-term-driver
- $(pacakge)_config_opts+=--enable-interop
- $(pacakge)_config_opts+=--enable-widec
- $(package)_build_opts=CFLAGS="$($(package)_cflags) $($(package)_cppflags) -fPIC"
-endef
-
-define $(package)_preprocess_cmds
- cp -f $(BASEDIR)/config.guess $(BASEDIR)/config.sub . && \
- cp $($(package)_patch_dir)/fallback.c ncurses
-endef
-
-define $(package)_config_cmds
- $($(package)_autoconf)
-endef
-
-define $(package)_build_cmds
- $(MAKE) $($(package)_build_opts) V=1
-endef
-
-define $(package)_stage_cmds
- $(MAKE) install.libs DESTDIR=$($(package)_staging_dir)
-endef
-
### contrib/depends/packages/packages.mk
@@ -1,10 +1,6 @@
native_packages :=
packages := boost openssl zeromq unbound sodium
-ifneq ($(host_os),mingw32)
-readline_packages += ncurses readline
-endif
-
wallet_native_packages := native_protobuf
wallet_packages = protobuf
### contrib/depends/packages/readline.mk
@@ -1,33 +0,0 @@
-package=readline
-$(package)_version=8.0
-$(package)_download_path=https://ftp.gnu.org/gnu/readline
-$(package)_file_name=$(package)-$($(package)_version).tar.gz
-$(package)_sha256_hash=e339f51971478d369f8a053a330a190781acb9864cf4c541060f12078948e461
-$(package)_dependencies=ncurses
-
-define $(package)_set_vars
- $(package)_build_opts=CC="$($(package)_cc)"
- $(package)_config_opts+=--prefix=$(host_prefix)
- $(package)_config_opts+=--exec-prefix=$(host_prefix)
- $(package)_config_opts+=--host=$(HOST)
- $(package)_config_opts+=--disable-shared --with-curses
- $(package)_config_opts_release=--disable-debug-mode
- $(package)_build_opts=CFLAGS="$($(package)_cflags) $($(package)_cppflags) -fPIC"
-endef
-
-define $(package)_preprocess_cmds
- cp -f $(BASEDIR)/config.guess $(BASEDIR)/config.sub support
-endef
-
-define $(package)_config_cmds
- $($(package)_autoconf)
-endef
-
-define $(package)_build_cmds
- $(MAKE) $($(package)_build_opts)
-endef
-
-define $(package)_stage_cmds
- $(MAKE) install DESTDIR=$($(package)_staging_dir) prefix=$(host_prefix) exec-prefix=$(host_prefix)
-endef
-
### contrib/depends/patches/ncurses/fallback.c
[binary or diff unavailable]
### contrib/depends/toolchain.cmake.in
@@ -18,11 +18,6 @@ SET(CMAKE_FIND_ROOT_PATH @prefix@ /usr)
SET(ENV{PKG_CONFIG_PATH} @prefix@/lib/pkgconfig)
-SET(Readline_ROOT_DIR @prefix@)
-SET(Readline_INCLUDE_DIR @prefix@/include)
-SET(Readline_LIBRARY @prefix@/lib/libreadline.a)
-SET(Terminfo_LIBRARY @prefix@/lib/libtinfo.a)
-
SET(LIBUSB-1.0_LIBRARY @prefix@/lib/libusb-1.0.a)
SET(LIBUDEV_LIBRARY @prefix@/lib/libudev.a)
### contrib/epee/include/console_handler.h
@@ -342,10 +342,10 @@ namespace epee
if (!prompt.empty())
{
#ifdef HAVE_READLINE
- std::string color_prompt = "\001\033[1;33m\002" + prompt;
+ std::string color_prompt = "\033[1;33m" + prompt;
if (' ' != prompt.back())
color_prompt += " ";
- color_prompt += "\001\033[0m\002";
+ color_prompt += "\033[0m";
m_stdin_reader.get_readline_buffer().set_prompt(color_prompt);
#else
epee::set_console_color(epee::console_color_yellow, true);
### contrib/epee/include/readline_buffer.h
@@ -17,7 +17,7 @@ namespace rdln
{
return m_cout_buf != NULL;
}
- linestatus get_line(std::string& line) const;
+ linestatus get_line(std::string& line);
void set_prompt(const std::string& prompt);
static void add_completion(const std::string& command);
static const std::vector<std::string>& get_completions();
@@ -27,7 +27,6 @@ namespace rdln
private:
std::streambuf* m_cout_buf;
- size_t m_prompt_length;
static std::vector<std::string>& completion_commands();
};
@@ -43,4 +42,3 @@ namespace rdln
void clear_screen();
}
-
### contrib/epee/src/CMakeLists.txt
@@ -40,7 +40,7 @@ monero_add_library(epee byte_slice.cpp byte_stream.cpp hex.cpp abstract_http_cli
${EPEE_HEADERS_PUBLIC}
)
-if (USE_READLINE AND (GNU_READLINE_FOUND OR (DEPENDS AND NOT MINGW)))
+if (EPEE_READLINE)
monero_add_library(epee_readline readline_buffer.cpp)
endif()
@@ -55,7 +55,7 @@ if (BUILD_GUI_DEPS)
endif()
install(TARGETS epee
ARCHIVE DESTINATION ${lib_folder})
- if (USE_READLINE AND GNU_READLINE_FOUND)
+ if (EPEE_READLINE)
install(TARGETS epee_readline
ARCHIVE DESTINATION ${lib_folder})
endif()
@@ -73,13 +73,13 @@ target_link_libraries(epee
PRIVATE
${EXTRA_LIBRARIES})
-if (USE_READLINE AND (GNU_READLINE_FOUND OR (DEPENDS AND NOT MINGW)))
+if (EPEE_READLINE)
target_link_libraries(epee_readline
PUBLIC
easylogging
${Boost_SYSTEM_LIBRARY}
PRIVATE
- ${GNU_READLINE_LIBRARY})
+ linenoise)
endif()
target_include_directories(epee
### contrib/epee/src/readline_buffer.cpp
@@ -1,23 +1,127 @@
#include "readline_buffer.h"
-#include <readline/readline.h>
-#include <readline/history.h>
+#include <linenoise.h>
#include <iostream>
-#include <memory>
+#include <cerrno>
+#include <csignal>
+#include <cstdlib>
+#include <cstdio>
+#include <chrono>
+#include <thread>
+#include <system_error>
+#include <poll.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
#include <boost/thread/mutex.hpp>
#include <boost/thread/lock_guard.hpp>
+#include <boost/thread/lock_types.hpp>
#include <boost/algorithm/string.hpp>
-static bool same_as_last_line(const std::string&);
-static void install_line_handler();
-static void remove_line_handler();
+namespace
+{
+ rdln::readline_buffer* current = NULL;
+
+ std::string strip_unsafe_bytes(const std::string& line)
+ {
+ std::string out;
+ out.reserve(line.size());
+ for (size_t i = 0; i < line.size(); )
+ {
+ const unsigned char c = static_cast<unsigned char>(line[i]);
+ if (c == 0xC2 && i + 1 < line.size())
+ {
+ const unsigned char c1 = static_cast<unsigned char>(line[i + 1]);
+ if (c1 >= 0x80 && c1 <= 0x9F) { i += 2; continue; } // UTF-8 encoded C1 control
+ }
+ if ((c < 0x20 && c != '\n') || c == 0x7F) { ++i; continue; } // C0 (keep \n) / DEL
+ out += line[i];
+ ++i;
+ }
+ return out;
+ }
+}
+
+static const size_t LINE_BUFFER_MAX = 1024 * 1024;
static boost::mutex sync_mutex;
-static rdln::linestatus line_stat;
-static char *the_line;
+static linenoiseState line_state;
+static bool editing_active = false;
+static bool tty_editing = false;
+static std::string current_prompt;
-namespace
+static void completion_callback(const char* buf, linenoiseCompletions* lc)
{
- rdln::readline_buffer* current = NULL;
+ const std::string text(buf);
+
+ // Completing an empty line would let TAB, Enter run "exit".
+ if (text.empty() || text.find(' ') != std::string::npos) return;
+
+ for (const std::string& cmd : rdln::readline_buffer::get_completions())
+ {
+ if (cmd.compare(0, text.size(), text) == 0)
+ linenoiseAddCompletion(lc, (cmd + " ").c_str());
+ }
+}
+
+// linenoise only reads the terminal width when editing starts.
+static void update_columns()
+{
+ struct winsize ws;
+ if (tty_editing && ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col)
+ line_state.cols = ws.ws_col;
+}
+
+static void begin_edit()
+{
+ if (editing_active) return;
+
+ char* buf = line_state.buf;
+ size_t buflen = line_state.buflen + 1;
+ bool allocated = false;
+ if (!buf)
+ {
+ buflen = 4096;
+ buf = static_cast<char*>(malloc(buflen));
+ if (!buf) return;
+ allocated = true;
+ }
+
+ if (linenoiseEditStart(&line_state, -1, -1, buf, buflen, current_prompt.c_str()) == 0)
+ {
+ editing_active = true;
+ line_state.buflen_max = LINE_BUFFER_MAX;
+ }
+ else if (allocated)
+ {
+ free(buf);
+ }
+}
+
+static void end_edit()
+{
+ if (!editing_active) return;
+ linenoiseEditStop(&line_state);
+ editing_active = false;
+}
+
+static void reset_line()
+{
+ // A non-tty session never drew a prompt, so skip the redraw.
+ if (editing_active && tty_editing && write(line_state.ofd, "\n", 1) == -1) {}
+ line_state.in_completion = 0;
+ line_state.completion_idx = 0;
+ line_state.buf[0] = '\0';
+ line_state.pos = 0;
+ line_state.oldpos = 0;
+ line_state.len = 0;
+ line_state.oldrows = 0;
+ line_state.oldrpos = 1;
+ line_state.history_index = 0;
+ line_state.fold_count = 0;
+ if (editing_active && tty_editing)
+ {
+ linenoiseHistoryAdd("");
+ linenoiseShow(&line_state);
+ }
}
rdln::suspend_readline::suspend_readline()
@@ -46,7 +150,7 @@ std::vector<std::string>& rdln::readline_buffer::completion_commands()
}
rdln::readline_buffer::readline_buffer()
-: std::stringbuf(), m_cout_buf(NULL), m_prompt_length(0)
+: std::stringbuf(), m_cout_buf(NULL)
{
current = this;
}
@@ -56,9 +160,19 @@ void rdln::readline_buffer::start()
boost::lock_guard<boost::mutex> lock(sync_mutex);
if(m_cout_buf != NULL)
return;
+ static bool stdin_unbuffered = false;
+ if (!stdin_unbuffered && !isatty(STDIN_FILENO))
+ {
+ setvbuf(stdin, NULL, _IONBF, 0);
+ stdin_unbuffered = true;
+ }
+ // Mirrors linenoiseEditStart()'s own no-tty check.
+ tty_editing = (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) || getenv("LINENOISE_ASSUME_TTY");
m_cout_buf = std::cout.rdbuf();
std::cout.rdbuf(this);
- install_line_handler();
+ linenoiseSetCompletionCallback(&completion_callback);
+ linenoiseHistorySetMaxLen(500);
+ begin_edit();
}
void rdln::readline_buffer::stop()
@@ -68,38 +182,90 @@ void rdln::readline_buffer::stop()
return;
std::cout.rdbuf(m_cout_buf);
m_cout_buf = NULL;
- remove_line_handler();
+ if (editing_active && tty_editing)
+ linenoiseHide(&line_state);
+ end_edit();
}
-rdln::linestatus rdln::readline_buffer::get_line(std::string& line) const
+rdln::linestatus rdln::readline_buffer::get_line(std::string& line)
{
- boost::lock_guard<boost::mutex> lock(sync_mutex);
- line_stat = rdln::partial;
+ boost::unique_lock<boost::mutex> lock(sync_mutex);
if (!m_cout_buf)
{
line = "";
return rdln::full;
}
- rl_callback_read_char();
- if (line_stat == rdln::full)
+
+ begin_edit();
+ if (!editing_active)
{
- line = the_line;
- free(the_line);
- the_line = NULL;
+ // Raw mode could not be set up: don't spin on the input left unread.
+ lock.unlock();
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ return rdln::partial;
}
- return line_stat;
+
+ // Avoid blocking in read() while holding sync_mutex: another thread
+ // may have already consumed the byte that made select() wake us.
+ struct pollfd pfd = {STDIN_FILENO, POLLIN, 0};
+ if (poll(&pfd, 1, 0) <= 0)
+ return rdln::partial;
+
+ update_columns();
+ errno = 0;
+ char* result = linenoiseEditFeed(&line_state);
+
+ if (result == linenoiseEditMore)
+ return rdln::partial;
+
+ if (result == NULL && errno == EINTR)
+ {
+ return rdln::partial;
+ }
+
+ const bool cancelled = (result == NULL && errno == EAGAIN);
+
+ if (result == NULL)
+ {
+ if (!cancelled)
+ {
+ end_edit();
+ return rdln::empty;
+ }
+ reset_line();
+ try { std::thread([]{ raise(SIGINT); }).detach(); }
+ catch (const std::system_error&) { raise(SIGINT); }
+ return rdln::partial;
+ }
+
+ line = strip_unsafe_bytes(result);
+ std::string test_line = line;
+ boost::trim_right(test_line);
+ if (!test_line.empty())
+ linenoiseHistoryAdd(test_line.c_str());
+ linenoiseFree(result);
+ reset_line();
+ return rdln::full;
}
void rdln::readline_buffer::set_prompt(const std::string& prompt)
{
boost::lock_guard<boost::mutex> lock(sync_mutex);
if(m_cout_buf == NULL)
return;
- rl_set_prompt(std::string(m_prompt_length, ' ').c_str());
- rl_redisplay();
- rl_set_prompt(prompt.c_str());
- rl_redisplay();
- m_prompt_length = prompt.size();
+ if (editing_active)
+ {
+ if (tty_editing) linenoiseHide(&line_state);
+ current_prompt = prompt;
+ line_state.prompt = current_prompt.c_str();
+ line_state.plen = current_prompt.size();
+ if (tty_editing) linenoiseShow(&line_state);
+ }
+ else
+ {
+ current_prompt = prompt;
+ begin_edit();
+ }
}
void rdln::readline_buffer::add_completion(const std::string& command)
@@ -123,141 +289,25 @@ int rdln::readline_buffer::sync()
return -1;
}
-#if RL_READLINE_VERSION < 0x0700
- char lbuf[2] = {0,0};
- char *line = NULL;
- int end = 0, point = 0;
-#endif
-
- if (rl_end || (rl_prompt && *rl_prompt))
- {
-#if RL_READLINE_VERSION >= 0x0700
- rl_clear_visible_line();
-#else
- line = rl_line_buffer;
- end = rl_end;
- point = rl_point;
- rl_line_buffer = lbuf;
- rl_end = 0;
- rl_point = 0;
- rl_save_prompt();
- rl_redisplay();
-#endif
- }
+ update_columns();
+ if (editing_active && tty_editing)
+ linenoiseHide(&line_state);
- do
+ while ( this->sgetc() != EOF )
{
m_cout_buf->sputc( this->sgetc() );
+ this->snextc();
}
- while ( this->snextc() != EOF );
-
-#if RL_READLINE_VERSION < 0x0700
- if (end || (rl_prompt && *rl_prompt))
- {
- rl_restore_prompt();
- rl_line_buffer = line;
- rl_end = end;
- rl_point = point;
- }
-#endif
- rl_on_new_line();
- rl_redisplay();
- return 0;
-}
+ m_cout_buf->pubsync();
-static void handle_line(char* line)
-{
- bool exit = false;
- if (line)
- {
- line_stat = rdln::full;
- the_line = line;
- std::string test_line = line;
- boost::trim_right(test_line);
- if(!test_line.empty())
- {
- if (!same_as_last_line(test_line))
- {
- add_history(test_line.c_str());
- history_set_pos(history_length);
- }
- if (test_line == "exit" || test_line == "q")
- exit = true;
- }
- } else
- /* EOF */
- {
- line_stat = rdln::empty;
- exit = true;
- }
- rl_done = 1;
- if (exit)
- rl_set_prompt("");
- return;
-}
+ if (editing_active && tty_editing)
+ linenoiseShow(&line_state);
-// same_as_last_line returns true, if the last line in the history is
-// equal to test_line.
-static bool same_as_last_line(const std::string& test_line)
-{
- // Note that state->offset == state->length, when a new line was entered.
- auto state = std::unique_ptr<HISTORY_STATE, decltype(free)*>{history_get_history_state(), free};
- return state->length > 0
- && test_line.compare(state->entries[state->length-1]->line) == 0;
-}
-
-static char* completion_matches(const char* text, int state)
-{
- static size_t list_index;
- static size_t len;
-
- if(state == 0)
- {
- list_index = 0;
- len = strlen(text);
- }
-
- const std::vector<std::string>& completions = rdln::readline_buffer::get_completions();
- for(; list_index<completions.size(); )
- {
- const std::string& cmd = completions[list_index++];
- if(cmd.compare(0, len, text) == 0)
- {
- return strdup(cmd.c_str());
- }
- }
-
- return NULL;
-}
-
-static char** attempted_completion(const char* text, int start, int end)
-{
- rl_attempted_completion_over = 1;
- return rl_completion_matches(text, completion_matches);
-}
-
-static void install_line_handler()
-{
-#if RL_READLINE_VERSION >= 0x0801
- rl_variable_bind("enable-bracketed-paste", "off");
-#endif
-
- rl_attempted_completion_function = attempted_completion;
- rl_callback_handler_install("", handle_line);
- stifle_history(500);
-}
-
-static void remove_line_handler()
-{
- rl_replace_line("", 0);
- rl_set_prompt("");
- rl_redisplay();
- rl_callback_handler_remove();
+ return 0;
}
void rdln::clear_screen()
{
- rl_clear_screen(0, 0);
+ linenoiseClearScreen();
}
-
### external/CMakeLists.txt
@@ -37,6 +37,9 @@ option(MX25519_COPYLEFT "Include the MPL-2.0 licensed assembly backends (ARM64,
add_subdirectory(db_drivers)
add_subdirectory(easylogging++)
+if(NOT WIN32)
+ add_subdirectory(linenoise)
+endif()
add_subdirectory(mx25519 EXCLUDE_FROM_ALL)
add_subdirectory(qrcodegen)
add_subdirectory(randomx EXCLUDE_FROM_ALL)
### external/linenoise/CMakeLists.txt
@@ -0,0 +1,8 @@
+project(linenoise C)
+
+add_library(linenoise STATIC linenoise.c)
+set_target_properties(linenoise PROPERTIES POSITION_INDEPENDENT_CODE ON)
+
+target_compile_definitions(linenoise PRIVATE _DEFAULT_SOURCE)
+
+target_include_directories(linenoise PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
### external/linenoise/linenoise.c
@@ -114,14 +114,15 @@
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
+#include <sys/select.h>
#include <unistd.h>
#include <stdint.h>
+#include <time.h>
#include "linenoise.h"
#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
#define LINENOISE_MAX_LINE (1024*1024) // That will get dynamically allocated
#define LINENOISE_INITIAL_BUFLEN 4096
-#define PASTE_FOLD_THRESHOLD 200 // Min bytes to fold a single-line paste.
#define PASTE_FOLD_CONTEXT 8 // Context chars kept around generic folds.
#define PASTE_MAX_BYTES LINENOISE_MAX_LINE
static char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
@@ -130,14 +131,15 @@ static linenoiseHintsCallback *hintsCallback = NULL;
static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
static char *linenoiseReadLine(FILE *fp, int *err);
static char *linenoiseNoTTY(void);
+static char *linenoiseNoTTYFeed(void);
+static char *linenoiseEditPasteFeed(struct linenoiseState *l);
static void refreshLineWithCompletion(struct linenoiseState *ls, linenoiseCompletions *lc, int flags);
static void refreshLineWithFlags(struct linenoiseState *l, int flags);
static void linenoiseFoldClear(struct linenoiseState *l);
static struct termios orig_termios; /* In order to restore at exit.*/
static int maskmode = 0; /* Show "***" instead of input. For passwords. */
static int rawmode = 0; /* For atexit() function to check if restore is needed*/
-static int rawmode_output = STDOUT_FILENO; /* fd used for terminal escapes. */
static int mlmode = 0; /* Multi line mode. Default is single line. */
static int atexit_registered = 0; /* Register atexit just 1 time. */
static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
@@ -162,27 +164,40 @@ static int utf8ByteLen(char c) {
return 1; /* Fallback for invalid encoding, treat as single byte. */
}
-/* Decode a UTF-8 sequence starting at 's' into a Unicode codepoint.
- * Returns the codepoint value. Assumes valid UTF-8 encoding. */
-static uint32_t utf8DecodeChar(const char *s, size_t *len) {
+/* Decode a UTF-8 sequence starting at 's' into a Unicode codepoint. 'avail'
+ * is the number of bytes actually available at 's'; a lead byte declaring a
+ * sequence longer than 'avail' is treated as invalid/truncated rather than
+ * reading past the available bytes. Returns the codepoint value. */
+static int utf8IsCont(unsigned char b) {
+ return (b & 0xC0) == 0x80;
+}
+
+static uint32_t utf8DecodeChar(const char *s, size_t avail, size_t *len) {
unsigned char *p = (unsigned char *)s;
uint32_t cp;
+ if (avail == 0) {
+ *len = 0;
+ return 0;
+ }
if ((*p & 0x80) == 0) {
*len = 1;
return *p;
- } else if ((*p & 0xE0) == 0xC0) {
+ } else if ((*p & 0xE0) == 0xC0 && avail >= 2 &&
+ utf8IsCont(p[1])) {
*len = 2;
cp = (*p & 0x1F) << 6;
cp |= (p[1] & 0x3F);
return cp;
- } else if ((*p & 0xF0) == 0xE0) {
+ } else if ((*p & 0xF0) == 0xE0 && avail >= 3 &&
+ utf8IsCont(p[1]) && utf8IsCont(p[2])) {
*len = 3;
cp = (*p & 0x0F) << 12;
cp |= (p[1] & 0x3F) << 6;
cp |= (p[2] & 0x3F);
return cp;
- } else if ((*p & 0xF8) == 0xF0) {
+ } else if ((*p & 0xF8) == 0xF0 && avail >= 4 &&
+ utf8IsCont(p[1]) && utf8IsCont(p[2]) && utf8IsCont(p[3])) {
*len = 4;
cp = (*p & 0x07) << 18;
cp |= (p[1] & 0x3F) << 12;
@@ -191,7 +206,7 @@ static uint32_t utf8DecodeChar(const char *s, size_t *len) {
return cp;
}
*len = 1;
- return *p; /* Fallback for invalid sequences. */
+ return *p; /* Fallback for invalid or truncated sequences. */
}
/* Check if codepoint is a variation selector (emoji style modifiers). */
@@ -243,7 +258,7 @@ static uint32_t utf8DecodePrev(const char *buf, size_t pos, size_t *cplen) {
} while (i > 0 && (pos - i) < 4 && ((unsigned char)buf[i] & 0xC0) == 0x80);
*cplen = pos - i;
size_t dummy;
- return utf8DecodeChar(buf + i, &dummy);
+ return utf8DecodeChar(buf + i, pos - i, &dummy);
}
/* Given a buffer and a position, return the byte length of the grapheme
@@ -316,7 +331,7 @@ static size_t utf8NextCharLen(const char *buf, size_t pos, size_t len) {
/* Get the first codepoint. */
size_t cplen;
- uint32_t cp = utf8DecodeChar(buf + curpos, &cplen);
+ uint32_t cp = utf8DecodeChar(buf + curpos, len - curpos, &cplen);
total += cplen;
curpos += cplen;
@@ -325,14 +340,14 @@ static size_t utf8NextCharLen(const char *buf, size_t pos, size_t len) {
/* Consume any extending characters that follow. */
while (curpos < len) {
size_t nextlen;
- uint32_t nextcp = utf8DecodeChar(buf + curpos, &nextlen);
+ uint32_t nextcp = utf8DecodeChar(buf + curpos, len - curpos, &nextlen);
if (isZWJ(nextcp) && curpos + nextlen < len) {
/* ZWJ: include it and the following character. */
total += nextlen;
curpos += nextlen;
/* Get the character after ZWJ. */
- nextcp = utf8DecodeChar(buf + curpos, &nextlen);
+ nextcp = utf8DecodeChar(buf + curpos, len - curpos, &nextlen);
total += nextlen;
curpos += nextlen;
continue; /* Check for more extending after the joined char. */
@@ -443,7 +458,7 @@ static size_t utf8StrWidth(const char *s, size_t len) {
while (i < len) {
size_t clen;
- uint32_t cp = utf8DecodeChar(s + i, &clen);
+ uint32_t cp = utf8DecodeChar(s + i, len - i, &clen);
/* Skip ANSI CSI escape sequences entirely: they produce no
* glyph, so they must not contribute to the display width.
@@ -479,7 +494,7 @@ static size_t utf8StrWidth(const char *s, size_t len) {
static int utf8SingleCharWidth(const char *s, size_t len) {
if (len == 0) return 0;
size_t clen;
- uint32_t cp = utf8DecodeChar(s, &clen);
+ uint32_t cp = utf8DecodeChar(s, len, &clen);
return utf8CharWidth(cp);
}
@@ -585,22 +600,21 @@ static int enableRawMode(int fd) {
/* input modes: no break, no CR to NL, no parity check, no strip char,
* no start/stop output control. */
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
- /* output modes - disable post processing */
- raw.c_oflag &= ~(OPOST);
/* control modes - set 8 bit chars */
raw.c_cflag |= (CS8);
- /* local modes - choing off, canonical off, no extended functions,
- * no signal chars (^Z,^C) */
- raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
+ /* local modes - choing off, canonical off, no extended functions.
+ * ISIG stays enabled so ^C/^\ still deliver SIGINT/SIGQUIT through the
+ * kernel even while no read() is pending (e.g. while a command runs). */
+ raw.c_lflag &= ~(ECHO | ICANON | IEXTEN);
/* control chars - set return condition: min number of bytes and timer.
* We want read to return every single byte, without timeout. */
raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
+ raw.c_cc[VSUSP] = _POSIX_VDISABLE; /* keep ^Z from suspending the process */
- /* put terminal in raw mode after flushing */
- if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
+ /* put terminal in raw mode; TCSADRAIN (not TCSAFLUSH) so input already
+ * queued by the terminal driver survives the mode switch. */
+ if (tcsetattr(fd,TCSADRAIN,&raw) < 0) goto fatal;
rawmode = 1;
- /* Ask the terminal to wrap paste input between ESC[200~ and ESC[201~. */
- if (write(rawmode_output, "\x1b[?2004h", 8) == -1) {}
return 0;
fatal:
@@ -614,10 +628,10 @@ static void disableRawMode(int fd) {
rawmode = 0;
return;
}
- /* Don't even check the return value as it's too late. */
- if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1) {
- /* Leave bracketed paste mode when leaving raw mode. */
- if (write(rawmode_output, "\x1b[?2004l", 8) == -1) {}
+ /* Don't even check the return value as it's too late. TCSADRAIN, not
+ * TCSAFLUSH: this runs on every PAUSE_READLINE, and TCSAFLUSH discards
+ * whatever the user typed ahead while a background message was printing. */
+ if (rawmode && tcsetattr(fd,TCSADRAIN,&orig_termios) != -1) {
rawmode = 0;
}
}
@@ -741,7 +755,7 @@ static void refreshLineWithCompletion(struct linenoiseState *ls, linenoiseComple
}
/* Free the completions table if needed. */
- if (lc != &ctable) freeCompletions(&ctable);
+ if (lc == &ctable) freeCompletions(&ctable);
}
/* This is an helper function for linenoiseEdit*() and is called when the
@@ -784,7 +798,6 @@ static int completeLine(struct linenoiseState *ls, int keypressed) {
/* Re-show original buffer */
if (ls->completion_idx < lc.len) refreshLine(ls);
ls->in_completion = 0;
- c = 0;
break;
default:
/* Update buffer and return */
@@ -900,10 +913,10 @@ static size_t foldCountLines(const char *buf, size_t len) {
return lines;
}
-/* Return true if the text should be folded: if it contains newlines or is at
- * least PASTE_FOLD_THRESHOLD bytes long. */
+/* Return true if the text should be folded: only multi-line text is, so a
+ * long single-line paste (e.g. a wallet's own base58 output) stays visible. */
static int shouldFoldText(const char *buf, size_t len) {
- return memchr(buf, '\n', len) != NULL || len >= PASTE_FOLD_THRESHOLD;
+ return memchr(buf, '\n', len) != NULL;
}
/* Fill f->display with the text shown instead of the folded range. */
@@ -990,6 +1003,45 @@ static int linenoiseGetRenderFolds(struct linenoiseState *l, struct linenoiseFol
return fs->count != 0;
}
+static size_t sanitizeForDisplay(const char *s, size_t len, char *out) {
+ size_t i, o = 0;
+ for (i = 0; i < len; ) {
+ unsigned char c = (unsigned char)s[i];
+ if (c < 0x20 || c == 0x7f) {
+ if (out) { out[o] = '^'; out[o+1] = (c == 0x7f) ? '?' : (char)(c ^ 0x40); }
+ o += 2;
+ i += 1;
+ continue;
+ }
+ {
+ size_t clen;
+ uint32_t cp = utf8DecodeChar(s+i, len-i, &clen);
+ if (clen == 0) clen = 1;
+ if (cp < 0x20 || cp == 0x7f || (cp >= 0x80 && cp <= 0x9f)) {
+ char tmp[8];
+ int n = snprintf(tmp,sizeof(tmp),"\\x%02X",(unsigned)cp);
+ if (n < 0) n = 0;
+ if (out) memcpy(out+o,tmp,(size_t)n);
+ o += (size_t)n;
+ } else {
+ if (out) memcpy(out+o,s+i,clen);
+ o += clen;
+ }
+ i += clen;
+ }
+ }
+ return o;
+}
+
+static char *sanitizeForDisplayAlloc(const char *s, size_t len, size_t *outlen) {
+ size_t slen = sanitizeForDisplay(s,len,NULL);
+ char *r = malloc(slen ? slen : 1);
+ if (r == NULL) return NULL;
+ sanitizeForDisplay(s,len,r);
+ *outlen = slen;
+ return r;
+}
+
/* Return the freshly allocated string content that is actually displayed in
* the user prompt. It can be the actual edited line, or a special version
* where pasted or multiline history ranges are replaced by their folded
@@ -1004,40 +1056,43 @@ static int linenoiseRenderBuffer(struct linenoiseState *l, char **out, size_t *o
if (!linenoiseGetRenderFolds(l,&fs)) {
/* Keep the refresh code simple: it always owns a temporary render
* buffer, even when the render is identical to the real edit buffer. */
- r = malloc(l->len+1);
+ len = sanitizeForDisplay(l->buf,l->len,NULL);
+ r = malloc(len+1);
if (r == NULL) return -1;
- memcpy(r,l->buf,l->len);
- r[l->len] = '\0';
+ sanitizeForDisplay(l->buf,l->len,r);
+ r[len] = '\0';
*out = r;
- *outlen = l->len;
- *outpos = l->pos;
+ *outlen = len;
+ pos = sanitizeForDisplay(l->buf,l->pos,NULL);
+ *outpos = pos > len ? len : pos;
return 0;
}
- /* Gaps are copied as-is, folded ranges are replaced by their markers.
- * The bytes inside each [start,end) range stay in l->buf but are not
- * emitted to the terminal. */
- len = l->len;
+ /* Gaps are sanitized and copied, folded ranges are replaced by their
+ * markers as-is (fixed text, not attacker bytes). The bytes inside each
+ * [start,end) range stay in l->buf but are not emitted to the terminal. */
+ len = 0;
+ src = 0;
for (j = 0; j < fs.count; j++) {
struct linenoiseFold *f = fs.fold+j;
- len -= f->end - f->start;
+ len += sanitizeForDisplay(l->buf+src,f->start-src,NULL);
len += f->displaylen;
+ src = f->end;
}
+ len += sanitizeForDisplay(l->buf+src,l->len-src,NULL);
r = malloc(len+1);
if (r == NULL) return -1;
src = dst = 0;
pos = 0;
for (j = 0; j < fs.count; j++) {
struct linenoiseFold *f = fs.fold+j;
- size_t gap = f->start - src;
if (!pos_set && l->pos <= f->start) {
- pos = dst + (l->pos - src);
+ pos = dst + sanitizeForDisplay(l->buf+src,l->pos-src,NULL);
pos_set = 1;
}
- memcpy(r+dst,l->buf+src,gap);
- dst += gap;
+ dst += sanitizeForDisplay(l->buf+src,f->start-src,r+dst);
if (!pos_set && l->pos < f->end) {
pos = dst + f->displaylen;
@@ -1051,13 +1106,13 @@ static int linenoiseRenderBuffer(struct linenoiseState *l, char **out, size_t *o
}
src = f->end;
}
- if (!pos_set) pos = dst + (l->pos - src);
- memcpy(r+dst,l->buf+src,l->len-src);
+ if (!pos_set) pos = dst + sanitizeForDisplay(l->buf+src,l->pos-src,NULL);
+ dst += sanitizeForDisplay(l->buf+src,l->len-src,r+dst);
r[len] = '\0';
*out = r;
*outlen = len;
- *outpos = pos;
+ *outpos = pos > len ? len : pos;
return 0;
}
@@ -1247,6 +1302,7 @@ static void refreshSingleLine(struct linenoiseState *l, int flags) {
* cursor position fits within the terminal width. */
while (pwidth + poscol >= l->cols) {
size_t clen = utf8NextCharLen(buf, 0, len);
+ if (clen == 0) break;
int cwidth = utf8SingleCharWidth(buf, clen);
buf += clen;
len -= clen;
@@ -1258,6 +1314,7 @@ static void refreshSingleLine(struct linenoiseState *l, int flags) {
/* Trim from the right if the line still doesn't fit. */
while (pwidth + lencol > l->cols) {
size_t clen = utf8PrevCharLen(buf, len);
+ if (clen == 0) break;
int cwidth = utf8SingleCharWidth(buf + len - clen, clen);
len -= clen;
lencol -= cwidth;
@@ -1291,7 +1348,10 @@ static void refreshSingleLine(struct linenoiseState *l, int flags) {
if (flags & REFRESH_WRITE) {
/* Move cursor to original position (using display column, not byte). */
- snprintf(seq,sizeof(seq),"\r\x1b[%dC", (int)(poscol+pwidth));
+ if (poscol+pwidth > 0)
+ snprintf(seq,sizeof(seq),"\r\x1b[%dC", (int)(poscol+pwidth));
+ else
+ snprintf(seq,sizeof(seq),"\r");
abAppend(&ab,seq,strlen(seq));
}
@@ -1516,16 +1576,25 @@ int linenoiseEditInsert(struct linenoiseState *l, const char *c, size_t clen) {
if (!needs_refresh && !mlmode && !hintsCallback &&
(maskmode || l->fold_count == 0))
{
- size_t bufwidth = utf8StrWidth(l->buf,l->len);
- if (utf8StrWidth(l->prompt,l->plen)+bufwidth < l->cols) {
- /* Avoid a full update of the line in the trivial case:
- * single-width char, no hints, fits in one line. */
- if (maskmode == 1) {
- if (write(l->ofd,"*",1) == -1) return -1;
- } else {
- if (write(l->ofd,c,clen) == -1) return -1;
+ size_t sbuflen;
+ char *sbuf = sanitizeForDisplayAlloc(l->buf,l->len,&sbuflen);
+ if (sbuf != NULL) {
+ size_t bufwidth = utf8StrWidth(sbuf,sbuflen);
+ int fits = utf8StrWidth(l->prompt,l->plen)+bufwidth < l->cols;
+ free(sbuf);
+ if (fits) {
+ if (maskmode == 1) {
+ if (write(l->ofd,"*",1) == -1) return -1;
+ } else {
+ size_t sclen;
+ char *sc = sanitizeForDisplayAlloc(c,clen,&sclen);
+ if (sc == NULL) { refreshLine(l); return 0; }
+ int wr = write(l->ofd,sc,sclen);
+ free(sc);
+ if (wr == -1) return -1;
+ }
+ return 0;
}
- return 0;
}
}
refreshLine(l);
@@ -1683,43 +1752,55 @@ void linenoiseEditDeletePrevWord(struct linenoiseState *l) {
* STDIN_FILENO and STDOUT_FILENO.
*/
int linenoiseEditStart(struct linenoiseState *l, int stdin_fd, int stdout_fd, char *buf, size_t buflen, const char *prompt) {
+ int resuming = (l->buf != NULL && l->buf == buf);
+ int ifd = stdin_fd != -1 ? stdin_fd : STDIN_FILENO;
+ int ofd = stdout_fd != -1 ? stdout_fd : STDOUT_FILENO;
+ int no_tty = (!isatty(ifd) || !isatty(ofd)) && !getenv("LINENOISE_ASSUME_TTY");
+
+ /* No raw mode on a non-tty; enter it before touching 'l' otherwise. */
+ if (!no_tty) {
+ if (enableRawMode(ifd) == -1) return -1;
+ }
+
/* Populate the linenoise state that we pass to functions implementing
* specific editing functionalities. */
l->in_completion = 0;
- l->ifd = stdin_fd != -1 ? stdin_fd : STDIN_FILENO;
- l->ofd = stdout_fd != -1 ? stdout_fd : STDOUT_FILENO;
+ l->ifd = ifd;
+ l->ofd = ofd;
l->buf = buf;
l->buflen = buflen;
+ l->buflen--; /* Make sure there is always space for the nulterm */
l->buflen_max = 0;
l->prompt = prompt;
l->plen = strlen(prompt);
- l->oldpos = l->pos = 0;
- l->len = 0;
- linenoiseFoldClear(l);
-
- /* Enter raw mode. */
- rawmode_output = l->ofd;
- if (enableRawMode(l->ifd) == -1) return -1;
-
- l->cols = getColumns(stdin_fd, stdout_fd);
- l->oldrows = 0;
- l->oldrpos = 1; /* Cursor starts on row 1. */
- l->history_index = 0;
+ if (!resuming) {
+ l->oldpos = l->pos = 0;
+ l->len = 0;
+ l->history_index = 0;
+ linenoiseFoldClear(l);
+ }
- /* Buffer starts empty. */
- l->buf[0] = '\0';
- l->buflen--; /* Make sure there is always space for the nulterm */
+ if (!resuming) {
+ /* Buffer starts empty. */
+ l->buf[0] = '\0';
+ }
/* If stdin is not a tty, stop here with the initialization. We
* will actually just read a line from standard input in blocking
* mode later, in linenoiseEditFeed(). */
- if (!isatty(l->ifd) && !getenv("LINENOISE_ASSUME_TTY")) return 0;
+ if (no_tty) return 0;
- /* The latest history entry is always our current buffer, that
- * initially is just an empty string. */
- linenoiseHistoryAdd("");
+ l->cols = getColumns(stdin_fd, stdout_fd);
+ l->oldrows = 0;
+ l->oldrpos = 1; /* Cursor starts on row 1. */
+
+ if (!resuming) {
+ /* The latest history entry is always our current buffer, that
+ * initially is just an empty string. */
+ linenoiseHistoryAdd("");
+ }
- if (write(l->ofd,prompt,l->plen) == -1) return -1;
+ linenoiseShow(l);
return 0;
}
@@ -1771,85 +1852,128 @@ static int pasteBufferAppend(struct linenoiseState *l, char **buf, size_t *cap,
return 0;
}
+static int waitReadable(int fd) {
+ fd_set rfds;
+ struct timeval tv;
+ FD_ZERO(&rfds);
+ FD_SET(fd,&rfds);
+ tv.tv_sec = 0; tv.tv_usec = 50000;
+ return select(fd+1,&rfds,NULL,NULL,&tv);
+}
+
+#define LOOP_TIME_BUDGET_MS 50
+
+static long elapsedMs(const struct timespec *t0) {
+ struct timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ return (now.tv_sec - t0->tv_sec) * 1000L +
+ (now.tv_nsec - t0->tv_nsec) / 1000000L;
+}
+
+static int pasteInProgress = 0;
+static char *pasteBuf = NULL;
+static size_t pasteCap = 0, pasteLen = 0, pasteMatch = 0, pasteMaxlen = 0;
+static int pasteOverflowed = 0;
+
/* Read a bracketed paste until ESC[201~ and insert the real bytes. If folding
* is needed, remember the inserted range so only rendering is shortened. */
-static void linenoiseEditPaste(struct linenoiseState *l) {
+static char *linenoiseEditPasteFeed(struct linenoiseState *l) {
static const char END[] = "\x1b[201~";
const size_t ENDLEN = sizeof(END)-1;
- char *buf = NULL;
- size_t cap = 0, len = 0, match = 0;
- size_t maxlen = l->buflen_max ? l->buflen_max : l->buflen;
- int overflowed = 0;
+ struct timespec t0;
+
+ if (!pasteInProgress) {
+ pasteBuf = NULL;
+ pasteCap = pasteLen = pasteMatch = 0;
+ pasteOverflowed = 0;
+ pasteMaxlen = l->buflen_max ? l->buflen_max : l->buflen;
+ pasteMaxlen = pasteMaxlen > l->len ? pasteMaxlen - l->len : 0;
+ if (pasteMaxlen > PASTE_MAX_BYTES) pasteMaxlen = PASTE_MAX_BYTES;
+ /* Once all fold slots are used, consume later pastes without storing them. */
+ if (l->fold_count == LINENOISE_MAX_FOLDS) pasteMaxlen = 0;
+ pasteInProgress = 1;
+ }
- maxlen = maxlen > l->len ? maxlen - l->len : 0;
- if (maxlen > PASTE_MAX_BYTES) maxlen = PASTE_MAX_BYTES;
- /* Once all fold slots are used, consume later pastes without storing them. */
- if (l->fold_count == LINENOISE_MAX_FOLDS) maxlen = 0;
+ clock_gettime(CLOCK_MONOTONIC, &t0);
while (1) {
+ if (elapsedMs(&t0) >= LOOP_TIME_BUDGET_MS) return linenoiseEditMore;
+
char c;
+ if (waitReadable(l->ifd) <= 0) return linenoiseEditMore;
if (read(l->ifd, &c, 1) != 1) break;
/* Track a possible ESC[201~ terminator without copying it into the
* paste. If it turns out to be ordinary input, flush the partial
* match below. */
- if (c == END[match]) {
- match++;
- if (match == ENDLEN) break;
+ if (c == END[pasteMatch]) {
+ pasteMatch++;
+ if (pasteMatch == ENDLEN) break;
continue;
}
- if (match > 0) {
- if (!overflowed &&
- pasteBufferAppend(l,&buf,&cap,&len,END,match,maxlen) == -1)
- overflowed = 1;
- match = 0;
+ if (pasteMatch > 0) {
+ if (!pasteOverflowed &&
+ pasteBufferAppend(l,&pasteBuf,&pasteCap,&pasteLen,END,pasteMatch,pasteMaxlen) == -1)
+ pasteOverflowed = 1;
+ pasteMatch = 0;
if (c == END[0]) {
- match = 1;
+ pasteMatch = 1;
continue;
}
}
- if (!overflowed &&
- pasteBufferAppend(l,&buf,&cap,&len,&c,1,maxlen) == -1)
- overflowed = 1;
- }
-
- if (overflowed) {
- free(buf);
- linenoiseBeep();
- return;
+ if (!pasteOverflowed &&
+ pasteBufferAppend(l,&pasteBuf,&pasteCap,&pasteLen,&c,1,pasteMaxlen) == -1)
+ pasteOverflowed = 1;
}
- if (buf == NULL) return;
+ pasteInProgress = 0;
{
+ char *buf = pasteBuf;
+ size_t len = pasteLen;
+ int overflowed = pasteOverflowed;
+ pasteBuf = NULL;
+ pasteCap = pasteLen = pasteMatch = 0;
+ pasteOverflowed = 0;
+
+ if (overflowed) {
+ free(buf);
+ linenoiseBeep();
+ return linenoiseEditMore;
+ }
+ if (buf == NULL) return linenoiseEditMore;
+
/* Normalize pasted CR and CRLF to LF, so the edit buffer uses one
* internal newline representation. */
size_t r = 0, w = 0;
while (r < len) {
- if (buf[r] == '\r') {
+ if (buf[r] == '\0') {
+ r += 1;
+ } else if (buf[r] == '\r') {
buf[w++] = '\n';
r += (r+1 < len && buf[r+1] == '\n') ? 2 : 1;
} else {
buf[w++] = buf[r++];
}
}
len = w;
- }
- if (!maskmode && shouldFoldText(buf,len)) {
- size_t start = l->pos;
- if (linenoiseEditInsertNoRefresh(l,buf,len) == -1) {
- free(buf);
- linenoiseBeep();
- return;
+ if (!maskmode && shouldFoldText(buf,len)) {
+ size_t start = l->pos;
+ if (linenoiseEditInsertNoRefresh(l,buf,len) == -1) {
+ free(buf);
+ linenoiseBeep();
+ return linenoiseEditMore;
+ }
+ linenoiseFoldAdd(l,start,start+len);
+ refreshLine(l);
+ } else {
+ linenoiseEditInsert(l,buf,len);
}
- linenoiseFoldAdd(l,start,start+len);
- refreshLine(l);
- } else {
- linenoiseEditInsert(l,buf,len);
+ free(buf);
}
- free(buf);
+ return linenoiseEditMore;
}
char *linenoiseEditMore = "If you see this, you are misusing the API: when linenoiseEditFeed() is called, if it returns linenoiseEditMore the user is yet editing the line. See the README file for more information.";
@@ -1873,9 +1997,11 @@ char *linenoiseEditMore = "If you see this, you are misusing the API: when linen
* Some other errno: I/O error.
*/
char *linenoiseEditFeed(struct linenoiseState *l) {
+ if (pasteInProgress) return linenoiseEditPasteFeed(l);
+
/* Not a TTY, pass control to line reading without character
* count limits. */
- if (!isatty(l->ifd) && !getenv("LINENOISE_ASSUME_TTY")) return linenoiseNoTTY();
+ if ((!isatty(l->ifd) || !isatty(l->ofd)) && !getenv("LINENOISE_ASSUME_TTY")) return linenoiseNoTTYFeed();
char c;
int nread;
@@ -1899,7 +2025,10 @@ char *linenoiseEditFeed(struct linenoiseState *l) {
}
switch(c) {
+ case KEY_NULL:
+ break;
case ENTER: /* enter */
+ case 10: /* ctrl-j / line feed: also accepted as enter */
history_len--;
free(history[history_len]);
if (mlmode) linenoiseEditMoveEnd(l);
@@ -1963,35 +2092,32 @@ char *linenoiseEditFeed(struct linenoiseState *l) {
linenoiseEditHistoryNext(l, LINENOISE_HISTORY_NEXT);
break;
case ESC: /* escape sequence */
- /* Read the next two bytes representing the escape sequence.
- * Use two calls to handle slow terminals returning the two
- * chars at different times. */
+ /* A real escape sequence arrives as one burst from the terminal, but
+ * a lone Escape keypress sends just this byte. Give it a short
+ * window to distinguish the two instead of blocking indefinitely on
+ * the first follow-up byte (this holds sync_mutex the whole time). */
+ if (waitReadable(l->ifd) <= 0) break;
if (read(l->ifd,seq,1) == -1) break;
+ if (waitReadable(l->ifd) <= 0) break;
if (read(l->ifd,seq+1,1) == -1) break;
/* ESC [ sequences. */
if (seq[0] == '[') {
if (seq[1] >= '0' && seq[1] <= '9') {
char param[8];
- size_t plen = 1;
- char final = 0;
-
- param[0] = seq[1];
- while (plen < sizeof(param)) {
- char p;
- if (read(l->ifd,&p,1) != 1) break;
- if (p >= '0' && p <= '9') {
- param[plen++] = p;
- } else {
- final = p;
- break;
- }
+ size_t plen = 0;
+ char final = seq[1];
+ int budget = 32;
+
+ while ((unsigned char)final >= 0x20 && (unsigned char)final <= 0x3f) {
+ if (plen < sizeof(param)) param[plen++] = final;
+ if (--budget <= 0) { final = 0; break; }
+ if (waitReadable(l->ifd) <= 0) { final = 0; break; }
+ if (read(l->ifd,&final,1) != 1) { final = 0; break; }
}
if (final == '~') {
if (plen == 1 && param[0] == '3') {
linenoiseEditDelete(l);
- } else if (plen == 3 && memcmp(param,"200",3) == 0) {
- linenoiseEditPaste(l);
}
}
} else {
@@ -2037,15 +2163,20 @@ char *linenoiseEditFeed(struct linenoiseState *l) {
{
char utf8[4];
int utf8len = utf8ByteLen(c);
+ int nread = 1;
utf8[0] = c;
if (utf8len > 1) {
- /* Read remaining bytes of the UTF-8 sequence. */
- int i;
- for (i = 1; i < utf8len; i++) {
- if (read(l->ifd, utf8+i, 1) != 1) break;
+ /* Read remaining bytes of the UTF-8 sequence, stopping on
+ * the first non-continuation byte (this also rejects NUL). */
+ for (nread = 1; nread < utf8len; nread++) {
+ char cont;
+ if (waitReadable(l->ifd) <= 0) break;
+ if (read(l->ifd, &cont, 1) != 1) break;
+ if (!utf8IsCont((unsigned char)cont)) break;
+ utf8[nread] = cont;
}
}
- if (linenoiseEditInsert(l, utf8, utf8len)) return NULL;
+ if (linenoiseEditInsert(l, utf8, nread)) return NULL;
}
break;
case CTRL_U: /* Ctrl+u, delete the whole line. */
@@ -2082,9 +2213,34 @@ char *linenoiseEditFeed(struct linenoiseState *l) {
* returns something different than NULL. At this point the user input
* is in the buffer, and we can restore the terminal in normal mode. */
void linenoiseEditStop(struct linenoiseState *l) {
- if (!isatty(l->ifd) && !getenv("LINENOISE_ASSUME_TTY")) return;
+ if (pasteInProgress) {
+ /* Drain the rest of the paste up to its terminator so it isn't
+ * replayed as keystrokes (e.g. submitted via an embedded newline)
+ * on the next edit session. */
+ static const char END[] = "\x1b[201~";
+ const size_t ENDLEN = sizeof(END)-1;
+ struct timespec t0;
+ clock_gettime(CLOCK_MONOTONIC, &t0);
+ while (elapsedMs(&t0) < LOOP_TIME_BUDGET_MS) {
+ char c;
+ if (waitReadable(l->ifd) <= 0) break;
+ if (read(l->ifd, &c, 1) != 1) break;
+ if (c == END[pasteMatch]) {
+ if (++pasteMatch == ENDLEN) break;
+ } else {
+ pasteMatch = (c == END[0]) ? 1 : 0;
+ }
+ }
+
+ free(pasteBuf);
+ pasteBuf = NULL;
+ pasteCap = pasteLen = pasteMatch = 0;
+ pasteOverflowed = 0;
+ pasteInProgress = 0;
+ }
+
+ if ((!isatty(l->ifd) || !isatty(l->ofd)) && !getenv("LINENOISE_ASSUME_TTY")) return;
disableRawMode(l->ifd);
- printf("\n");
}
/* This just implements a blocking loop for the multiplexed API.
@@ -2124,7 +2280,6 @@ void linenoisePrintKeyCodes(void) {
printf("Linenoise key codes debugging mode.\n"
"Press keys to see scan codes. Type 'quit' at any time to exit.\n");
- rawmode_output = STDOUT_FILENO;
if (enableRawMode(STDIN_FILENO) == -1) return;
memset(quit,' ',4);
while(1) {
@@ -2157,12 +2312,6 @@ static char *linenoiseReadLine(FILE *fp, int *err) {
if (len+1 >= cap) {
size_t newcap = cap ? cap*2 : 16;
char *oldval = line;
- if (newcap <= cap) {
- free(line);
- if (err) *err = 1;
- errno = ENOMEM;
- return NULL;
- }
line = realloc(line,newcap);
if (line == NULL) {
if (oldval) free(oldval);
@@ -2187,15 +2336,66 @@ static char *linenoiseReadLine(FILE *fp, int *err) {
}
}
-/* This function is called when linenoise() is called with the standard
- * input file descriptor not attached to a TTY. So for example when the
- * program using linenoise is called in pipe or with a file redirected
- * to its standard input. In this case, we want to be able to return the
- * line regardless of its length. */
static char *linenoiseNoTTY(void) {
return linenoiseReadLine(stdin,NULL);
}
+static char *linenoiseNoTTYFeed(void) {
+ static char *line = NULL;
+ static size_t len = 0, cap = 0;
+ int fd = fileno(stdin);
+ struct timespec t0;
+
+ clock_gettime(CLOCK_MONOTONIC, &t0);
+
+ while (1) {
+ if (elapsedMs(&t0) >= LOOP_TIME_BUDGET_MS) return linenoiseEditMore;
+
+ if (len+1 >= cap) {
+ size_t newcap = cap ? cap*2 : 16;
+ char *oldval = line;
+ line = realloc(line,newcap);
+ if (line == NULL) {
+ if (oldval) free(oldval);
+ return NULL;
+ }
+ cap = newcap;
+ }
+
+ int sr = waitReadable(fd);
+ if (sr == 0) return linenoiseEditMore;
+ if (sr < 0) {
+ free(line);
+ line = NULL; len = cap = 0;
+ return NULL;
+ }
+
+ char c;
+ ssize_t n = read(fd, &c, 1);
+
+ if (n < 0) {
+ free(line);
+ line = NULL; len = cap = 0;
+ return NULL;
+ }
+
+ if (n == 0 || c == '\n') {
+ if (n == 0 && len == 0) {
+ free(line);
+ line = NULL; len = cap = 0;
+ return NULL;
+ }
+ line[len] = '\0';
+ char *result = line;
+ line = NULL; len = cap = 0;
+ return result;
+ }
+
+ line[len] = c;
+ len++;
+ }
+}
+
/* The high level function that is the main API of the linenoise library.
* This function checks if the terminal has basic capabilities, just checking
* for a blacklist of stupid terminals, and later either calls the line
### src/common/util.cpp
@@ -62,7 +62,6 @@ using namespace epee;
#include "stack_trace.h"
#include "memwipe.h"
#include "net/http_client.h" // epee::net_utils::...
-#include "readline_buffer.h"
#ifdef WIN32
#include <windows.h>
### src/daemon/CMakeLists.txt
@@ -65,7 +65,6 @@ target_link_libraries(daemon
${Boost_SYSTEM_LIBRARY}
${CMAKE_THREAD_LIBS_INIT}
PkgConfig::libzmq
- ${GNU_READLINE_LIBRARY}
${EXTRA_LIBRARIES}
$<TARGET_NAME_IF_EXISTS:blocks>)
set_property(TARGET daemon
### src/gen_multisig/CMakeLists.txt
@@ -43,7 +43,6 @@ target_link_libraries(gen_multisig
${Boost_FILESYSTEM_LIBRARY}
${Boost_THREAD_LIBRARY}
${CMAKE_THREAD_LIBS_INIT}
- ${GNU_READLINE_LIBRARY}
${EXTRA_LIBRARIES})
add_dependencies(gen_multisig
version)
### src/simplewallet/CMakeLists.txt
@@ -57,7 +57,6 @@ target_link_libraries(simplewallet
${ICU_LIBRARIES}
${Boost_THREAD_LIBRARY}
${CMAKE_THREAD_LIBS_INIT}
- ${GNU_READLINE_LIBRARY}
${EXTRA_LIBRARIES})
set_property(TARGET simplewallet
PROPERTYWhy this scored 35/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.