diff --git a/.github/actions/setup-libcurl-cache/action.yaml b/.github/actions/setup-libcurl-cache/action.yaml index 6b559079..cbd46c0e 100644 --- a/.github/actions/setup-libcurl-cache/action.yaml +++ b/.github/actions/setup-libcurl-cache/action.yaml @@ -53,7 +53,7 @@ runs: id: cache-key shell: sh run: | - echo "cache-key=${{ inputs.cache-key-prefix }}${{ runner.os }}${{ runner.arch == 'ARM64' && '-arm64' || '' }}-${{ steps.detect-libc.outputs.variant }}-libcurl-${{ inputs.libcurl-release }}-deps-cache-${{ inputs.electron-version && 'electron' || 'node' }}-${{ inputs.electron-version || inputs.node-version }}" >> $GITHUB_OUTPUT + echo "cache-key=${{ inputs.cache-key-prefix }}${{ runner.os }}${{ runner.arch == 'ARM64' && '-arm64' || '' }}-${{ steps.detect-libc.outputs.variant }}-libcurl-${{ inputs.libcurl-release }}-deps-cache-${{ inputs.electron-version && 'electron' || 'node' }}-${{ inputs.electron-version || inputs.node-version }}-${{ hashFiles('scripts/ci/build.sh', 'scripts/ci/build-brotli.sh', 'scripts/ci/build-libcurl.sh') }}" >> $GITHUB_OUTPUT # Restore-only mode (for workflows that save separately) - name: Restore libcurl deps cache if: inputs.mode == 'restore-only' diff --git a/.github/workflows/build-lint-test.yaml b/.github/workflows/build-lint-test.yaml index 15e21f71..ede68b9b 100644 --- a/.github/workflows/build-lint-test.yaml +++ b/.github/workflows/build-lint-test.yaml @@ -204,6 +204,8 @@ jobs: - name: 'Run tests (Alpine arm64)' if: matrix.os == 'alpine-arm64' && matrix.electron-version == '' + # http2PushHeaders.spec compiles a native fixture with node-gyp, which + # needs a toolchain that the bare node:alpine image does not ship. run: | PNPM_VERSION=$(node -e "const {packageManager}=require('./package.json');console.log(packageManager.split('@')[1])") docker run --rm \ @@ -212,7 +214,11 @@ jobs: -v "${GITHUB_WORKSPACE}:${GITHUB_WORKSPACE}" \ -w "${GITHUB_WORKSPACE}" \ "node:${{ matrix.node }}-alpine3.22" \ - sh -c 'npm install -g pnpm@${PNPM_VERSION} && pnpm test:coverage' + sh -c ' + apk add --no-cache python3 make g++ && + npm install -g pnpm@${PNPM_VERSION} && + pnpm test:coverage + ' - name: Upload coverage to Codecov if: matrix.record-coverage && matrix.electron-version != '' diff --git a/.github/workflows/windows-consumer-install.yaml b/.github/workflows/windows-consumer-install.yaml index 45b8e1d7..a570f1b3 100644 --- a/.github/workflows/windows-consumer-install.yaml +++ b/.github/workflows/windows-consumer-install.yaml @@ -166,6 +166,10 @@ jobs: $curlVersion $curlVersionText = $curlVersion -join "`n" + if ($curlVersionText -notmatch '\bbrotli/1\.2\.1\b') { + throw 'Windows curl build did not link the patched Brotli 1.2.1 decoder' + } + if ($curlVersionText -notmatch 'Features:.*\bIDN\b') { throw 'Windows curl build did not retain IDN support' } diff --git a/CHANGELOG.md b/CHANGELOG.md index f4560694..291970be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,37 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ### Changed +## [5.2.0] - 2026-11-25 + +### Fixed +- Release the Multi wrapper after `Multi#close()` so it can be collected. ([#457](https://github.com/JCMais/node-libcurl/pull/457), fixes [#453](https://github.com/JCMais/node-libcurl/issues/453)) +- HTTP/2 push header accessors throw after the push callback returns. ([#460](https://github.com/JCMais/node-libcurl/pull/460), fixes [#452](https://github.com/JCMais/node-libcurl/issues/452)) +- `Multi#perform()` now rejects if its transfer is removed or its Multi is closed. Multi keeps attached Easy handles alive, detaches them during shutdown, and releases their socket watchers. Transfers added without `onMessage` can complete safely, and Multi stops polling sockets when libcurl requests no events. ([#464](https://github.com/JCMais/node-libcurl/pull/464)) +- `Curl#close()` now cancels active transfers on their owning Multi, including transfers using `setMulti()`. Closing from a transfer callback defers cleanup until libcurl returns. ([#464](https://github.com/JCMais/node-libcurl/pull/464)) +- Restored HTTP/2 server push callbacks on libcurl 8.4 and later. Accepted pushes are tracked by the Multi, and denied pushes close the offered Easy handle. ([#464](https://github.com/JCMais/node-libcurl/pull/464)) +- `READFUNCTION` receives a zero-filled buffer and validates the returned byte count. Upload seeks preserve offsets beyond 4 GiB, and file uploads advance by the number of bytes actually read. ([#463](https://github.com/JCMais/node-libcurl/pull/463)) +- Callback errors are retained until delivery, and reused Easy handles start with fresh transfer-local progress and HSTS state. `HSTSREADFUNCTION` preserves hostnames at the maximum supported length. ([#463](https://github.com/JCMais/node-libcurl/pull/463)) +- Easy handles keep their Share alive while attached. `Share#close()` reports `CURLSHE_IN_USE` while the Share is attached, and automatic Easy cleanup skips callbacks whose JavaScript receiver has been collected. ([#463](https://github.com/JCMais/node-libcurl/pull/463)) +- Replacing list or POST data options releases the previous data once outstanding duplicates stop using it. Failed list setup frees temporary data, and repeated MIME attachment on the same handle is tracked once. ([#463](https://github.com/JCMais/node-libcurl/pull/463)) +- Fixed socket monitoring setup and teardown errors. `Easy#getInfo()` preserves libcurl's error code directly. ([#463](https://github.com/JCMais/node-libcurl/pull/463)) +- `Curl#reset()` clears request state and restores the default user agent. `curly()` returns reused handles to the pool and rejects its promise when request setup fails. ([#462](https://github.com/JCMais/node-libcurl/pull/462)) +- Response parsing accepts compact and empty headers and decodes each payload independently. `curly()` honors custom parsers and matches content types regardless of case or whitespace before parameters. ([#462](https://github.com/JCMais/node-libcurl/pull/462)) +- Fixed response stream backpressure and resume behavior, detached listeners from replaced upload streams, restored the prior `NOPROGRESS` setting after streaming, and routed response setup errors through a single error event. ([#462](https://github.com/JCMais/node-libcurl/pull/462)) +- Fixed `Curl.getCount()` and fixed `Curl#dupHandle()` to preserve the user agent and copy `stream` listeners. ([#462](https://github.com/JCMais/node-libcurl/pull/462)) +- Fixed the numeric `TELNETOPTIONS` mapping and enabled native dispatch for existing bindings including `ABSTRACT_UNIX_SOCKET`, `ALTSVC`, `ALTSVC_CTRL`, `FTPSSLAUTH`, `FTP_SSL_CCC`, `MIME_OPTIONS`, `PROXY_ISSUERCERT_BLOB`, `SSH_HOSTKEYFUNCTION`, `SSH_HOST_PUBLIC_KEY_SHA256`, `TFTP_NO_OPTIONS`, `WS_OPTIONS`, and `INTERLEAVEFUNCTION`. ([#461](https://github.com/JCMais/node-libcurl/pull/461)) +- Corrected `CurlSshKeyType` numeric values to match libcurl. `CurlMultiNetworkChanged.ClearConns` and `.ClearDns` clear their respective caches on libcurl 8.20 and later, while both retain the combined behavior on libcurl 8.16–8.19. ([#461](https://github.com/JCMais/node-libcurl/pull/461)) +- Updated bundled Brotli to 1.2.1 on all platforms to fix [CVE-2026-111497](https://www.cve.org/CVERecord?id=CVE-2026-111497), an out-of-bounds write in the decoder. ([#456](https://github.com/JCMais/node-libcurl/issues/456)) +- Fixed `end` (and the promise returned by `Multi#perform`) not being delivered on Node.js 26 until some other JavaScript callback ran, which made requests awaited one at a time take ~1s each (libcurl's multi timer period) or never complete in an otherwise idle process. `Multi::OnSocket` and `Multi::OnTimeout` called into JavaScript from libuv without a callback scope, so the microtask queue was not drained afterwards. Before Node.js 26.4.0 an unrelated drain in `CheckImmediate` hid this ([nodejs/node#62969](https://github.com/nodejs/node/pull/62969)). Both now open a `Napi::CallbackScope`. As a side effect, `process.nextTick` callbacks and microtasks queued from inside data, header, progress, and other easy callbacks now run once the libuv callback that dispatched them returns, instead of after each individual callback. This matches how Node.js core runs callbacks. ([#455](https://github.com/JCMais/node-libcurl/pull/455), fixes [#454](https://github.com/JCMais/node-libcurl/issues/454)) +- Fixed the process aborting with `Assertion failed: (code == CURLM_OK), function Dispose` when `Multi#close` is called from inside `onMessage` on libcurl >= 8.17 (where the notifications API is the default, as in `examples/04-multi.js`), or from inside an easy callback such as `WRITEFUNCTION` with any libcurl version. libcurl rejects `curl_multi_cleanup` with `CURLM_RECURSIVE_API_CALL` while it is running its own callbacks, so the cleanup is now deferred until `curl_multi_socket_action` returns. +- Fixed building from source on Windows with Visual Studio 2026 (MSBuild 18) when node-libcurl is installed in a deeply nested folder, such as a pnpm store inside a monorepo. The build failed with `PathTooLongException` in `WriteLinesToFile` because gyp generated a project for node-addon-api's header-only `node_addon_api_except` target next to node-addon-api's own folder, and MSBuild wrote its intermediate files there. On Windows its settings are now set directly in `binding.gyp`. + +### Added +- Added `Curl.info.SIZE_DELIVERED` and the `QUICK_EXIT` and `RESOLVE_THREADS_MAX` Multi options on libcurl 8.20 and later. ([#461](https://github.com/JCMais/node-libcurl/pull/461)) +- Added `CurlAltSvc` and the enum members `CurlFileType.Unknown`, `CurlMultiNetworkChanged.ClearAll`, `CurlSshKeyType.Rsa1`, `CurlSshKeyMatch.Missing`, `CurlVersion.Hsts`, and `CurlVersion.ThreadSafe`. ([#461](https://github.com/JCMais/node-libcurl/pull/461)) + +### Changed +- The security policy supports v5 and describes when a fix may be offered for the previous major version. ([#459](https://github.com/JCMais/node-libcurl/pull/459)) + ## [5.1.2] - 2026-06-08 ### Fixed @@ -548,7 +579,8 @@ Special Thanks to [@koskokos2](https://github.com/koskokos2) for their contribut - Improved code style, started using prettier ## [1.2.0] - 2017-08-28 -[Unreleased]: https://github.com/JCMais/node-libcurl/compare/v5.1.2...HEAD +[Unreleased]: https://github.com/JCMais/node-libcurl/compare/v5.2.0...HEAD +[5.2.0]: https://github.com/JCMais/node-libcurl/compare/v5.1.2...v5.2.0 [5.1.2]: https://github.com/JCMais/node-libcurl/compare/v5.1.1...v5.1.2 [5.1.1]: https://github.com/JCMais/node-libcurl/compare/v5.1.0...v5.1.1 [5.1.0]: https://github.com/JCMais/node-libcurl/compare/v5.0.2...v5.1.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6d49780a..8ece7ff7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,5 +1,6 @@ # Contributing +- [AI usage policy](#ai-usage-policy) - [Contributing with Issues](#contributing-with-issues) - [Contributing with Code](#contributing-with-code) - [C/C++](#cc) @@ -19,6 +20,14 @@ - [Prereleases](#prereleases) - [Build Matrix](#build-matrix) +## AI usage policy + +AI tools are welcome in node-libcurl. Disclosure is optional. You should assume AI was involved in all recent contributions, including work by maintainers. + +You’re responsible for everything you submit. For a pull request, understand the changes, run the relevant checks, and be ready to explain your decisions during review. For a bug report, verify the finding yourself and describe what you observed. Keep submissions focused so maintainers can review them efficiently. + +We close low-effort submissions that shift basic verification to maintainers. This includes unverified claims, changes the contributor can’t explain, and generated reports that bury the issue. The same standards apply to everyone, including maintainers. + ## Contributing with Issues Before opening an issue try to search the existing ones for the same problem. diff --git a/README.md b/README.md index 36d4a646..e4c7a061 100644 --- a/README.md +++ b/README.md @@ -268,7 +268,7 @@ Installing with `yarn add node-libcurl` or `npm install node-libcurl` should dow The prebuilt binary is statically built with the following library versions, features and protocols (library versions may change between Node.js versions): ``` -Version: libcurl/8.17.0 OpenSSL/3.5.2 zlib/1.3.1 brotli/1.1.0 zstd/1.5.7 libidn2/2.1.1 libssh2/1.10.0 nghttp2/1.66.0 ngtcp2/1.17.0 nghttp3/1.12.0 OpenLDAP/2.6.9 +Version: libcurl/8.17.0 OpenSSL/3.5.2 zlib/1.3.1 brotli/1.2.1 zstd/1.5.7 libidn2/2.1.1 libssh2/1.10.0 nghttp2/1.66.0 ngtcp2/1.17.0 nghttp3/1.12.0 OpenLDAP/2.6.9 Protocols: dict, file, ftp, ftps, gopher, gophers, http, https, imap, imaps, ldap, ldaps, mqtt, pop3, pop3s, rtsp, scp, sftp, smb, smbs, smtp, smtps, telnet, tftp, ws, wss Features: AsynchDNS, IDN, IPv6, Largefile, NTLM, SSL, libz, brotli, TLS-SRP, HTTP2, UnixSockets, HTTPS-proxy, alt-svc ``` @@ -293,7 +293,7 @@ npm_config_build_from_source=true yarn add node-libcurl The prebuilt binaries are statically linked with `brotli`, `libidn2`, `libssh2`, `openLDAP`, `OpenSSL` `nghttp2`, `zstd` and `zlib`. -The `brotli`, `nghttp2`, `OpenSSL` and `zlib` versions **must** match the version Node.js uses, this is necessary to avoid any possible issues by mixing library symbols of different versions, since Node.js also exports some of the symbols of their deps. +The `nghttp2`, `OpenSSL` and `zlib` versions **must** match the version Node.js uses to avoid mixing library symbols from different versions. The build pins Brotli separately to a patched release. Keep Node.js or Electron up to date to patch the runtime's own decoder. In case you are building the addon yourself with the libraries mentioned above, you must make sure their version is ABI compatible with the one Node.js uses, otherwise you are probably going to hit a Segmentation Fault. diff --git a/SECURITY.md b/SECURITY.md index 9a58d9ff..b65c9f4c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,12 +2,16 @@ ## Supported Versions -The following versions are going to receive security updates. The updates will take form as minor version increments. +Only v5 is supported. Security updates for supported versions are released as minor version increments. | Version | Supported | | ------- | ------------------ | -| 2.1.0 | :white_check_mark: | -| < 2.0.0 | :x: | +| 5.x | :white_check_mark: | +| < 5.0.0 | :x: | + +We may backport a fix to the immediately previous major version for a serious +security vulnerability when affected users have no practical workaround. +Building from source with a patched dependency may be a workaround when feasible. ## Reporting a Vulnerability diff --git a/binding.gyp b/binding.gyp index a3e12f0f..9ec53e51 100644 --- a/binding.gyp +++ b/binding.gyp @@ -50,11 +50,11 @@ { 'target_name': '<(module_name)', 'type': 'loadable_module', - 'dependencies': [ - # https://github.com/nodejs/node-addon-api/blob/main/doc/setup.md - # using exceptions (instead of maybe, like we used to have on nan) - " { if (this.streamReadFunctionPaused) { @@ -533,8 +560,8 @@ class Curl extends EventEmitter { // a connection that has already finished // this can happen if some error has been throw // in the meantime - if (this.isRunning) { - this.pause(CurlPause.Cont) + if (this.isRunning && this.readFunctionStream === stream) { + this.pause(this.handle.pauseFlags & ~CurlPause.Send) } }) } @@ -743,23 +770,29 @@ class Curl extends EventEmitter { this.features & CurlFeature.StreamResponse || this.readFunctionStream if (isStreamEnabled) { this.setProgressCallback(this.streamModeProgressFunction.bind(this)) - this.setOpt('NOPROGRESS', false) + this.handle.setOpt(Curl.option.NOPROGRESS, false) } // Use custom Multi instance if set, otherwise use the default global one const multi = this.multiInstance || multiHandle // On libcurl 8.17+ the multi handle uses the new CURLMOPT_NOTIFYFUNCTION API, - // and our NotifyCallback resolves the perform() promise while still inside - // curl_multi_socket_action. Microtask draining can then run the .then() - // synchronously and try to call curl_multi_remove_handle from there, which - // libcurl rejects with CURLM_RECURSIVE_API_CALL ("API function called from - // within callback"). Defer removeHandle to the next tick so libcurl has - // unwound its own call stack first. + // and our NotifyCallback settles the perform() promise while still inside + // curl_multi_socket_action. Calling curl_multi_remove_handle from there is + // rejected by libcurl with CURLM_RECURSIVE_API_CALL ("API function called + // from within callback"). + // + // Since #455 the native side enters JS through a callback scope that only + // drains microtasks once curl_multi_socket_action has returned, so the + // .then() below no longer runs while libcurl is on the stack. The + // setImmediate is kept as a second guard for #439, at the cost of one extra + // event loop phase before `end` / `error` are emitted. // // See: https://github.com/JCMais/node-libcurl/issues/439 const finalize = (cb: () => void) => { setImmediate(() => { + if (this.isClosing || !this.handle.isOpen) return + try { if (this.handle.isOpen && this.handle.isInsideMultiHandle) { multi.removeHandle(this.handle) @@ -769,18 +802,22 @@ class Curl extends EventEmitter { // pattern does this), or the handle was already removed for any // other reason, swallow — we still want to settle the request. } + this.multiInUse = undefined cb() }) } - multi - .perform(this.handle) - .then(() => { - finalize(() => this.onEnd()) - }) - .catch((error) => { - finalize(() => this.onError(error, error.code)) - }) + try { + const transfer = multi.perform(this.handle) + this.multiInUse = multi + transfer.then( + () => finalize(() => this.onEnd()), + (error) => finalize(() => this.onError(error, error.code)), + ) + } catch (error) { + this.isRunning = false + throw error + } return this } @@ -832,7 +869,15 @@ class Curl extends EventEmitter { reset() { this.removeAllListeners() this.handle.reset() - + this.resetInternalState(false) + this.noProgress = true + + // features are tied to the request lifecycle of this instance, not to the + // native handle, so they must be cleared here - otherwise things like the + // StreamResponse flag would leak into the next request (which is fatal for + // pooled handles, see curly's object pool) + this.features = CurlFeature.Empty + this.streamWriteFunctionHighWaterMark = undefined // add callbacks back as reset will remove them this.handle.setOpt( Curl.option.WRITEFUNCTION, @@ -843,6 +888,8 @@ class Curl extends EventEmitter { this.defaultHeaderFunction.bind(this), ) + this.handle.setOpt(Curl.option.USERAGENT, Curl.defaultUserAgent) + return this } @@ -857,9 +904,10 @@ class Curl extends EventEmitter { */ dupHandle(shouldCopyEventListeners = true) { const duplicatedHandle = new Curl(this.handle.dupHandle()) - const eventsToCopy = ['end', 'error', 'data', 'header'] + const eventsToCopy = ['end', 'error', 'data', 'header', 'stream'] duplicatedHandle.features = this.features + duplicatedHandle.noProgress = this.noProgress if (shouldCopyEventListeners) { for (let i = 0; i < eventsToCopy.length; i += 1) { @@ -900,26 +948,55 @@ class Curl extends EventEmitter { * Official libcurl documentation: [`curl_easy_cleanup()`](http://curl.haxx.se/libcurl/c/curl_easy_cleanup.html) */ close() { - if (!this.handle.isOpen) { - return - } + if (this.isClosing || !this.handle.isOpen) return + this.isClosing = true - this.removeAllListeners() + const finish = () => { + if (this.handle.isInsideMultiHandle) { + const multi = this.multiInUse ?? multiHandle + multi.removeHandle(this.handle) + } - if (this.handle.isInsideMultiHandle) { - multiHandle.removeHandle(this.handle) + this.removeAllListeners() + this.cleanupReadFunctionStreamEvents() + this.handle.setOpt(Curl.option.WRITEFUNCTION, null) + this.handle.setOpt(Curl.option.HEADERFUNCTION, null) + this.handle.close() + this.isRunning = false + this.multiInUse = undefined } - this.handle.setOpt(Curl.option.WRITEFUNCTION, null) - this.handle.setOpt(Curl.option.HEADERFUNCTION, null) + try { + finish() + } catch (error) { + const code = (error as { code?: unknown })?.code + if ( + code === CurlMultiCode.CURLM_RECURSIVE_API_CALL || + code === CurlMultiCode.CURLM_BAD_HANDLE + ) { + // A callback can close the Curl or its Multi while libcurl is still on + // the stack. Retry after the socket action and any pending cleanup. + setImmediate(() => { + try { + finish() + } finally { + this.isClosing = false + } + }) + return + } + + this.isClosing = false + throw error + } - this.handle.close() + this.isClosing = false } /** * This is used to reset a few properties to their pre-request state. */ - protected resetInternalState() { + protected resetInternalState(resetHandleOptions = true) { this.isRunning = false this.chunks = [] @@ -929,12 +1006,16 @@ class Curl extends EventEmitter { const wasStreamEnabled = this.writeFunctionStream || this.readFunctionStream - if (wasStreamEnabled) { + if (wasStreamEnabled && resetHandleOptions && this.handle.isOpen) { this.setProgressCallback(null) + // perform() sets NOPROGRESS to false when streams are used - restore it, + // otherwise libcurl would enable its built-in progress meter (which + // writes to stderr) for the next requests made with this same instance + this.handle.setOpt(Curl.option.NOPROGRESS, this.noProgress) } // reset back the READFUNCTION if there was a stream we were reading from - if (this.readFunctionStream) { + if (this.readFunctionStream && resetHandleOptions && this.handle.isOpen) { this.setOpt('READFUNCTION', null) } @@ -948,6 +1029,8 @@ class Curl extends EventEmitter { this.streamReadFunctionPaused = false // common this.streamPauseNext = false + this.streamPendingReadSize = 0 + this.nextPauseFlags = null this.streamContinueNext = false this.streamError = false this.streamUserSuppliedProgressFunction = null @@ -982,7 +1065,7 @@ class Curl extends EventEmitter { : Buffer.alloc(0) return isHeaderParsingEnabled - ? parseHeaders(decoder.write(headersRaw)) + ? parseHeaders(headersRaw.toString('utf8')) : headersRaw } @@ -1057,6 +1140,11 @@ class Curl extends EventEmitter { autoDestroy: true, highWaterMark: this.streamWriteFunctionHighWaterMark, destroy(error, cb) { + if (handle.writeFunctionStream !== writeFunctionStream) { + cb(error) + return + } + handle.streamError = error || new Error('Curl response stream was unexpectedly destroyed') @@ -1081,10 +1169,35 @@ class Curl extends EventEmitter { cb(null) }, read(size) { + if (handle.writeFunctionStream !== writeFunctionStream) return + handle.streamPendingReadSize += size if (handle.handle.isPausedRecv && handle.isRunning) { handle.nextPauseFlags = handle.handle.pauseFlags & ~CurlPause.Recv + + // unpause on the next event loop iteration - this read() call can + // be running from inside the WRITEFUNCTION itself (via push), in + // which case libcurl is still inside its own stack. Waiting for + // the progress callback to consume nextPauseFlags is not enough: + // a paused transfer generates no events, so the unpause could be + // delayed by up to a second (libcurl's internal progress timer) + setImmediate(() => { + if ( + handle.writeFunctionStream === writeFunctionStream && + handle.isRunning && + handle.handle.isPausedRecv && + handle.streamPendingReadSize > 0 + ) { + handle.nextPauseFlags = null + try { + handle.pause(handle.handle.pauseFlags & ~CurlPause.Recv) + } catch { + // the transfer finished or errored in the meantime - the + // error itself is handled by the usual error paths + } + } + }) } }, }) @@ -1110,8 +1223,12 @@ class Curl extends EventEmitter { ) if (code !== CurlCode.CURLE_OK) { - const error = new Error('Could not get status code of request') - this.emit('error', error, code, this) + // do not emit 'error' directly from here: returning -1 below fails + // the transfer, which already emits 'error' through the regular + // error path - a direct emit would produce two 'error' events for + // the same request (and crash the process when the first handler + // removed all listeners, like the curly object pool does) + this.streamError = new Error('Could not get status code of request') return -1 } @@ -1126,11 +1243,20 @@ class Curl extends EventEmitter { } // write to the stream - if (!this.streamPendingReadSize) { + // libcurl chunk sizes rarely align with the read sizes requested by the + // stream, so the counter must pause on <= 0, not only on exactly 0 - + // otherwise once it crosses below zero backpressure would never be + // applied again + if (this.streamPendingReadSize <= 0) { return CurlWriteFunc.Pause } this.streamPendingReadSize -= chunk.length + if (this.streamPendingReadSize < 0) { + // the surplus delivered above what was requested is already inside the + // stream buffer and accounted for by the stream itself + this.streamPendingReadSize = 0 + } this.writeFunctionStream!.push(chunk) return size * nmemb diff --git a/lib/Multi.ts b/lib/Multi.ts index 69fe3294..ef1c6cf9 100644 --- a/lib/Multi.ts +++ b/lib/Multi.ts @@ -98,13 +98,11 @@ declare class Multi { * Sets the [`PUSHFUNCTION`](https://curl.haxx.se/libcurl/c/CURLMOPT_PUSHFUNCTION.html) option. * * @remarks - * You **must** not use the {@link Http2PushFrameHeaders | `Http2PushFrameHeaders`} object outside - * of this callback, doing so will try to use memory that libcurl has already - * freed and, in the best case scenario, will cause a segmentation fault. + * The {@link Http2PushFrameHeaders | `Http2PushFrameHeaders`} object is only valid during + * this callback. Its `getByName()` and `getByIndex()` methods throw after the callback returns. * - * In case you have denied the push, you **must** also not use the `duplicatedHandle` - * outside of this callback, as libcurl would already have closed it and you would - * try to access memory that has been freed. + * The `duplicatedHandle` is closed by libcurl if you deny the push. + * HTTP/2 push dispatch requires libcurl 8.4.0 or newer. * * Errors thrown inside this callback will have the same effect than returning `CurlPush.Deny`. * diff --git a/lib/curly.ts b/lib/curly.ts index 02ec3cf9..7d0cf349 100644 --- a/lib/curly.ts +++ b/lib/curly.ts @@ -384,72 +384,81 @@ const create = (defaultOptions: CurlyOptions = {}): CurlyFunction => { ): Promise> { const curlHandle = getFromPool() - curlHandle.enable(CurlFeature.NoDataParsing) - - curlHandle.setOpt('URL', `${options.curlyBaseUrl || ''}${url}`) - const finalOptions = { ...defaultOptions, ...options, } - for (const key of Object.keys(finalOptions)) { - const keyTyped = key as keyof CurlyOptions - - const optionName: CurlOptionName = - keyTyped in CurlOptionCamelCaseMap - ? CurlOptionCamelCaseMap[ - keyTyped as keyof typeof CurlOptionCamelCaseMap - ] - : (keyTyped as CurlOptionName) - - // if it begins with curly we do not set it on the curlHandle - // as it's an specific option for curly - if (optionName.startsWith('curly')) continue - - // @ts-ignore @TODO Try to type this - curlHandle.setOpt(optionName, finalOptions[key]) - } - - // streams! const { curlyStreamResponse, curlyStreamResponseHighWaterMark, curlyStreamUpload, curlyMimePost, } = finalOptions - const isUsingStream = !!(curlyStreamResponse || curlyStreamUpload) - if (finalOptions.curlyProgressCallback) { - if (typeof finalOptions.curlyProgressCallback !== 'function') { - throw new TypeError( - 'curlyProgressCallback must be a function with signature (number, number, number, number) => number', - ) + // any error thrown while setting up the handle must reject the returned + // promise (not propagate synchronously) and release the acquired handle + // back to the pool, otherwise it would leak + try { + curlHandle.enable(CurlFeature.NoDataParsing) + + curlHandle.setOpt('URL', `${options.curlyBaseUrl || ''}${url}`) + + for (const key of Object.keys(finalOptions)) { + const keyTyped = key as keyof CurlyOptions + + const optionName: CurlOptionName = + keyTyped in CurlOptionCamelCaseMap + ? CurlOptionCamelCaseMap[ + keyTyped as keyof typeof CurlOptionCamelCaseMap + ] + : (keyTyped as CurlOptionName) + + // if it begins with curly we do not set it on the curlHandle + // as it's an specific option for curly + if (optionName.startsWith('curly')) continue + + // @ts-ignore @TODO Try to type this + curlHandle.setOpt(optionName, finalOptions[key]) } - const fnToCall = isUsingStream - ? 'setStreamProgressCallback' - : 'setProgressCallback' + // streams! + const isUsingStream = !!(curlyStreamResponse || curlyStreamUpload) - curlHandle[fnToCall](finalOptions.curlyProgressCallback) - } + if (finalOptions.curlyProgressCallback) { + if (typeof finalOptions.curlyProgressCallback !== 'function') { + throw new TypeError( + 'curlyProgressCallback must be a function with signature (number, number, number, number) => number', + ) + } - if (curlyStreamResponse) { - curlHandle.enable(CurlFeature.StreamResponse) + const fnToCall = isUsingStream + ? 'setStreamProgressCallback' + : 'setProgressCallback' - if (curlyStreamResponseHighWaterMark) { - curlHandle.setStreamResponseHighWaterMark( - curlyStreamResponseHighWaterMark, - ) + curlHandle[fnToCall](finalOptions.curlyProgressCallback) } - } - if (curlyStreamUpload) { - curlHandle.setUploadStream(curlyStreamUpload) - } + if (curlyStreamResponse) { + curlHandle.enable(CurlFeature.StreamResponse) + + if (curlyStreamResponseHighWaterMark) { + curlHandle.setStreamResponseHighWaterMark( + curlyStreamResponseHighWaterMark, + ) + } + } - if (curlyMimePost && curlyMimePost.length > 0) { - curlHandle.setMimePost(curlyMimePost) + if (curlyStreamUpload) { + curlHandle.setUploadStream(curlyStreamUpload) + } + + if (curlyMimePost && curlyMimePost.length > 0) { + curlHandle.setMimePost(curlyMimePost) + } + } catch (error) { + returnToPool(curlHandle) + return Promise.reject(error) } const lowerCaseHeadersIfNecessary = (headers: HeaderInfo[]) => { @@ -512,19 +521,30 @@ const create = (defaultOptions: CurlyOptions = {}): CurlyFunction => { // remove the metadata of the content-type, like charset // See https://tools.ietf.org/html/rfc7231#section-3.1.1.5 - contentType = contentType.split(';')[0] - - const responseBodyParsers = { - ...curly.defaultResponseBodyParsers, - ...finalOptions.curlyResponseBodyParsers, - } + // media types are case-insensitive (RFC 7231 section 3.1.1.1) + contentType = contentType.split(';')[0].trim().toLowerCase() + + // user supplied parsers must be checked before the default ones, + // otherwise they would never match anything not already covered by the + // defaults, as the default '*' parser matches everything + const userResponseBodyParsers = + finalOptions.curlyResponseBodyParsers || {} + const responseBodyParsers: Array<[string, CurlyResponseBodyParser]> = + [ + ...Object.entries(userResponseBodyParsers), + ...Object.entries(curly.defaultResponseBodyParsers).filter( + ([contentTypeFormat]) => + !(contentTypeFormat in userResponseBodyParsers), + ), + ] let foundParser = finalOptions.curlyResponseBodyParser + let wildcardParser: CurlyResponseBodyParser | undefined = undefined if (typeof foundParser === 'undefined') { - for (const [contentTypeFormat, parser] of Object.entries( - responseBodyParsers, - )) { + for (const [contentTypeFormatRaw, parser] of responseBodyParsers) { + const contentTypeFormat = contentTypeFormatRaw.toLowerCase() + if (typeof parser !== 'function') { return reject( new TypeError( @@ -536,8 +556,10 @@ const create = (defaultOptions: CurlyOptions = {}): CurlyFunction => { foundParser = parser break } else if (contentTypeFormat === '*') { - foundParser = parser - break + // '*' matches everything - only use it if nothing more specific matches + if (!wildcardParser) { + wildcardParser = parser + } } else { const partsFormat = contentTypeFormat.split('/') const partsContentType = contentType.split('/') @@ -554,6 +576,10 @@ const create = (defaultOptions: CurlyOptions = {}): CurlyFunction => { } } } + + if (typeof foundParser === 'undefined') { + foundParser = wildcardParser + } } if (foundParser && typeof foundParser !== 'function') { @@ -590,6 +616,13 @@ const create = (defaultOptions: CurlyOptions = {}): CurlyFunction => { // has been resolved with it // so instead of rejecting the original promise // we are emitting the error event on the stream + // + // note: emit (not stream.destroy(error)) is intentional - the + // response stream has a custom _destroy that swallows the passed + // error (it is resurfaced through this very code path), so + // destroy(error) here would silently drop it. Per Node.js stream + // conventions, consumers must attach an 'error' listener (async + // iterators and pipeline() do this automatically). if (stream) { stream.emit('error', errorToUse) } else { diff --git a/lib/enum/CurlAltSvc.ts b/lib/enum/CurlAltSvc.ts new file mode 100644 index 00000000..2e2fc749 --- /dev/null +++ b/lib/enum/CurlAltSvc.ts @@ -0,0 +1,32 @@ +/** + * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/** + * Object with bit flags to be used with the {@link "Curl".Curl.setOpt | `Curl#setOpt`} option `ALTSVC_CTRL`. + * + * `CURLALTSVC_H1` becomes `CurlAltSvc.H1` + * + * @public + */ +export enum CurlAltSvc { + /** + * Do not write the alt-svc cache back to the file specified with the + * `ALTSVC` option even if it gets updated. + */ + ReadonlyFile = 1 << 2, + /** + * Accept alternative services offered over HTTP/1.1. + */ + H1 = 1 << 3, + /** + * Accept alternative services offered over HTTP/2. + */ + H2 = 1 << 4, + /** + * Accept alternative services offered over HTTP/3. + */ + H3 = 1 << 5, +} diff --git a/lib/enum/CurlFileType.ts b/lib/enum/CurlFileType.ts index b392b253..8aefc3a8 100644 --- a/lib/enum/CurlFileType.ts +++ b/lib/enum/CurlFileType.ts @@ -22,4 +22,8 @@ export enum CurlFileType { NamedPipe, Socket, Door, + /** + * Is possible only on Sun Solaris now + */ + Unknown, } diff --git a/lib/enum/CurlMultiNetworkChanged.ts b/lib/enum/CurlMultiNetworkChanged.ts index f7b6f8b0..0de966a5 100644 --- a/lib/enum/CurlMultiNetworkChanged.ts +++ b/lib/enum/CurlMultiNetworkChanged.ts @@ -4,23 +4,31 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ -// https://github.com/curl/curl/blob/00cb679c04ef9e0f30bd99c9dcc58c1e1928c01a/include/curl/multi.h#L410 +import { Curl } from '../Curl' + +const hasSeparateFlags = Curl.isVersionGreaterOrEqualThan(8, 20, 0) /** - * To be used with the `NETRC` option + * To be used with the `NETWORK_CHANGED` Multi option (libcurl 8.16+). + * Before libcurl 8.20, all three flags clear both caches. * - * `CURLMNC_CLEAR_CONNS` becomes `CurlMultiNetworkChanged.ClearConns` + * `CURLMNWC_CLEAR_CONNS` becomes `CurlMultiNetworkChanged.ClearConns` * * @public */ export enum CurlMultiNetworkChanged { + /** + * Tells libcurl to clear "everything" that could be related to the + * previous network setup. + */ + ClearAll = 1 << 0, /** * Tells libcurl to prevent further reuse of existing connections. * Connections that are idle will be closed. Ongoing transfers * will continue with the connection they have. */ - ClearConns = 1 << 0, + ClearConns = hasSeparateFlags ? 1 << 1 : 1 << 0, /** * Tells libcurl to clear the DNS cache. */ - ClearDns = 1 << 0, + ClearDns = hasSeparateFlags ? 1 << 2 : 1 << 0, } diff --git a/lib/enum/CurlSshKey.ts b/lib/enum/CurlSshKey.ts index 8aad8a47..93766bd1 100644 --- a/lib/enum/CurlSshKey.ts +++ b/lib/enum/CurlSshKey.ts @@ -19,22 +19,26 @@ export enum CurlSshKeyType { * Unknown key type */ Unknown = 0, + /** + * RSA1 key (obsolete SSH protocol version 1) + */ + Rsa1 = 1, /** * RSA key */ - Rsa = 1, + Rsa = 2, /** * DSS key */ - Dss = 2, + Dss = 3, /** * ECDSA key */ - Ecdsa = 3, + Ecdsa = 4, /** * ED25519 key */ - Ed25519 = 4, + Ed25519 = 5, } /** @@ -55,4 +59,8 @@ export enum CurlSshKeyMatch { * The host key is rejected, the connection is canceled. */ Mismatch = 1, + /** + * No matching host/key was found (reported by CURLOPT_SSH_KEYFUNCTION). + */ + Missing = 2, } diff --git a/lib/enum/CurlVersion.ts b/lib/enum/CurlVersion.ts index 5718c93f..4321fc74 100644 --- a/lib/enum/CurlVersion.ts +++ b/lib/enum/CurlVersion.ts @@ -128,11 +128,16 @@ export enum CurlVersion { * Unicode support on Windows */ Unicode = 1 << 27, - - // TODO(jonathan): when we add HSTS support - add it in here as 1 << 28 - + /** + * HSTS is supported + */ + Hsts = 1 << 28, /** * libgsasl is supported */ Gsasl = 1 << 29, + /** + * The libcurl API is thread-safe + */ + ThreadSafe = 1 << 30, } diff --git a/lib/generated/CurlInfo.ts b/lib/generated/CurlInfo.ts index 328b94b6..e1c94ac5 100644 --- a/lib/generated/CurlInfo.ts +++ b/lib/generated/CurlInfo.ts @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ -// This file was generated by scripts/build-constants.js on 2025-11-13T02:10:36.516Z +// This file was generated by scripts/build-constants.js on 2026-06-11T11:59:16.651Z // Do not edit manually /** @@ -257,14 +257,14 @@ export interface CurlInfo { readonly POSTTRANSFER_TIME_T: 'POSTTRANSFER_TIME_T' /** - * The time it took from the start until the file transfer is just about to begin. This includes all pre-transfer commands and negotiations that are specific to the particular protocol(s) involved. + * The time it took from the start until the file transfer is about to begin. This includes all pre-transfer commands and negotiations that are specific to the particular protocol(s) involved. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLINFO_PRETRANSFER_TIME.html](https://curl.haxx.se/libcurl/c/CURLINFO_PRETRANSFER_TIME.html) */ readonly PRETRANSFER_TIME: 'PRETRANSFER_TIME' /** - * The time it took from the start until the file transfer is just about to begin. This includes all pre-transfer commands and negotiations that are specific to the particular protocol(s) involved. In microseconds. + * The time it took from the start until the file transfer is about to begin. This includes all pre-transfer commands and negotiations that are specific to the particular protocol(s) involved. In microseconds. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLINFO_PRETRANSFER_TIME_T.html](https://curl.haxx.se/libcurl/c/CURLINFO_PRETRANSFER_TIME_T.html) */ @@ -341,14 +341,14 @@ export interface CurlInfo { readonly REDIRECT_COUNT: 'REDIRECT_COUNT' /** - * The time it took for all redirection steps include name lookup, connect, pretransfer and transfer before final transaction was started. So, this is zero if no redirection took place. As a double. + * The time it took for all redirection steps include name lookup, connect, pretransfer and transfer before final transaction was started. This is zero if no redirection took place. As a double. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLINFO_REDIRECT_TIME.html](https://curl.haxx.se/libcurl/c/CURLINFO_REDIRECT_TIME.html) */ readonly REDIRECT_TIME: 'REDIRECT_TIME' /** - * The time it took for all redirection steps include name lookup, connect, pretransfer and transfer before final transaction was started. So, this is zero if no redirection took place. In number of microseconds. + * The time it took for all redirection steps include name lookup, connect, pretransfer and transfer before final transaction was started. This is zero if no redirection took place. In number of microseconds. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLINFO_REDIRECT_TIME_T.html](https://curl.haxx.se/libcurl/c/CURLINFO_REDIRECT_TIME_T.html) */ @@ -424,6 +424,13 @@ export interface CurlInfo { */ readonly SCHEME: 'SCHEME' + /** + * Number of bytes passed to the write callback. See CURLINFO_SIZE_DELIVERED(3) + * + * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLINFO_SIZE_DELIVERED.html](https://curl.haxx.se/libcurl/c/CURLINFO_SIZE_DELIVERED.html) + */ + readonly SIZE_DELIVERED: 'SIZE_DELIVERED' + /** * (Deprecated) Number of bytes downloaded. * @@ -614,6 +621,7 @@ export type CurlInfoName = | 'RTSP_SERVER_CSEQ' | 'RTSP_SESSION_ID' | 'SCHEME' + | 'SIZE_DELIVERED' | 'SIZE_DOWNLOAD' | 'SIZE_DOWNLOAD_T' | 'SIZE_UPLOAD' diff --git a/lib/generated/CurlOption.ts b/lib/generated/CurlOption.ts index a58adc29..4803b013 100644 --- a/lib/generated/CurlOption.ts +++ b/lib/generated/CurlOption.ts @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ -// This file was generated by scripts/build-constants.js on 2025-11-13T02:10:36.480Z +// This file was generated by scripts/build-constants.js on 2026-06-11T11:59:16.392Z // Do not edit manually import { CurlChunk } from '../enum/CurlChunk' @@ -993,7 +993,7 @@ export interface CurlOption { readonly PRE_PROXY: 'PRE_PROXY' /** - * Commands to run just before transfer. + * Commands to run immediately before transfer. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLOPT_PREQUOTE.html](https://curl.haxx.se/libcurl/c/CURLOPT_PREQUOTE.html) */ @@ -1665,14 +1665,14 @@ export interface CurlOption { readonly SSLVERSION: 'SSLVERSION' /** - * This HTTP/2 stream depends on another. + * Deprecated option This HTTP/2 stream depends on another. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS.html](https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS.html) */ readonly STREAM_DEPENDS: 'STREAM_DEPENDS' /** - * This HTTP/2 stream depends on another exclusively. + * Deprecated option This HTTP/2 stream depends on another exclusively. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS_E.html](https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS_E.html) */ @@ -2910,7 +2910,7 @@ export const CurlOptionCamelCaseMap = { preProxy: 'PRE_PROXY', /** - * Commands to run just before transfer. + * Commands to run immediately before transfer. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLOPT_PREQUOTE.html](https://curl.haxx.se/libcurl/c/CURLOPT_PREQUOTE.html) */ @@ -3582,14 +3582,14 @@ export const CurlOptionCamelCaseMap = { sslversion: 'SSLVERSION', /** - * This HTTP/2 stream depends on another. + * Deprecated option This HTTP/2 stream depends on another. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS.html](https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS.html) */ streamDepends: 'STREAM_DEPENDS', /** - * This HTTP/2 stream depends on another exclusively. + * Deprecated option This HTTP/2 stream depends on another exclusively. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS_E.html](https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS_E.html) */ @@ -6162,14 +6162,14 @@ export type CurlOptionValueType = { preProxy?: string | number | boolean | null /** - * Commands to run just before transfer. + * Commands to run immediately before transfer. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLOPT_PREQUOTE.html](https://curl.haxx.se/libcurl/c/CURLOPT_PREQUOTE.html) */ PREQUOTE?: string[] | null /** - * Commands to run just before transfer. + * Commands to run immediately before transfer. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLOPT_PREQUOTE.html](https://curl.haxx.se/libcurl/c/CURLOPT_PREQUOTE.html) */ @@ -7546,28 +7546,28 @@ export type CurlOptionValueType = { sslversion?: CurlSslVersion | null /** - * This HTTP/2 stream depends on another. + * Deprecated option This HTTP/2 stream depends on another. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS.html](https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS.html) */ STREAM_DEPENDS?: Easy | null /** - * This HTTP/2 stream depends on another. + * Deprecated option This HTTP/2 stream depends on another. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS.html](https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS.html) */ streamDepends?: Easy | null /** - * This HTTP/2 stream depends on another exclusively. + * Deprecated option This HTTP/2 stream depends on another exclusively. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS_E.html](https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS_E.html) */ STREAM_DEPENDS_E?: Easy | null /** - * This HTTP/2 stream depends on another exclusively. + * Deprecated option This HTTP/2 stream depends on another exclusively. * * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS_E.html](https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_DEPENDS_E.html) */ diff --git a/lib/generated/MultiOption.ts b/lib/generated/MultiOption.ts index 213c48fc..080e1ad7 100644 --- a/lib/generated/MultiOption.ts +++ b/lib/generated/MultiOption.ts @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ -// This file was generated by scripts/build-constants.js on 2025-11-13T02:10:36.547Z +// This file was generated by scripts/build-constants.js on 2026-06-11T11:59:16.877Z // Do not edit manually /** @@ -73,6 +73,20 @@ export interface MultiOption { * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLMOPT_PUSHFUNCTION.html](https://curl.haxx.se/libcurl/c/CURLMOPT_PUSHFUNCTION.html) */ readonly PUSHFUNCTION: 'PUSHFUNCTION' + + /** + * Enable a quicker cleanup of the multi handle. See CURLMOPT_QUICK_EXIT(3) + * + * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLMOPT_QUICK_EXIT.html](https://curl.haxx.se/libcurl/c/CURLMOPT_QUICK_EXIT.html) + */ + readonly QUICK_EXIT: 'QUICK_EXIT' + + /** + * Max threads used for threaded DNS resolver. See CURLMOPT_RESOLVE_THREADS_MAX(3) + * + * Official libcurl documentation: [https://curl.haxx.se/libcurl/c/CURLMOPT_RESOLVE_THREADS_MAX.html](https://curl.haxx.se/libcurl/c/CURLMOPT_RESOLVE_THREADS_MAX.html) + */ + readonly RESOLVE_THREADS_MAX: 'RESOLVE_THREADS_MAX' } /** @@ -88,3 +102,5 @@ export type MultiOptionName = | 'MAXCONNECTS' | 'NETWORK_CHANGED' | 'PUSHFUNCTION' + | 'QUICK_EXIT' + | 'RESOLVE_THREADS_MAX' diff --git a/lib/index.ts b/lib/index.ts index df29ba9c..4abbfaff 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -39,6 +39,7 @@ export * from './CurlMultiError' export * from './CurlSharedError' // enums +export * from './enum/CurlAltSvc' export * from './enum/CurlAuth' export * from './enum/CurlChunk' export * from './enum/CurlCode' diff --git a/lib/parseHeaders.ts b/lib/parseHeaders.ts index 63e8d78d..159a6fad 100644 --- a/lib/parseHeaders.ts +++ b/lib/parseHeaders.ts @@ -59,15 +59,21 @@ export function parseHeaders(headersString: string): HeaderInfo[] { continue } - const header = headers[i].split(/:\s(.+)/) - if (header[0].toUpperCase() === 'SET-COOKIE') { + // the whitespace after the colon is optional (RFC 7230, header-field = field-name ":" OWS field-value OWS) + const colonIndex = headers[i].indexOf(':') + const headerName = + colonIndex === -1 ? headers[i] : headers[i].slice(0, colonIndex) + const headerValue = + colonIndex === -1 ? '' : headers[i].slice(colonIndex + 1).trim() + + if (headerName.toUpperCase() === 'SET-COOKIE') { if (!currHeaders['Set-Cookie']) { currHeaders['Set-Cookie'] = [] } - currHeaders['Set-Cookie'].push(header[1]) + currHeaders['Set-Cookie'].push(headerValue) } else { - currHeaders[header[0]] = header[1] + currHeaders[headerName] = headerValue } } diff --git a/package.json b/package.json index 8d018d23..1b5bf68e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@brightsec/node-libcurl", - "version": "5.1.7-1", + "version": "5.2.0-0", "description": "The fastest http(s) client (and much more) for Node.js - Node.js bindings for libcurl", "keywords": [ "node-curl", diff --git a/scripts/ci/build.sh b/scripts/ci/build.sh index 39fea881..da7493c2 100755 --- a/scripts/ci/build.sh +++ b/scripts/ci/build.sh @@ -300,11 +300,8 @@ fi ################### # Build brotli ################### -# Brotli version must match Node.js one -# But brotli only started being shipped with Node 12 -BROTLI_NODEJS=$(node -e "console.log(process.versions.brotli || '')") -BROTLI_DEFAULT_RELEASE=${BROTLI_NODEJS:-1.0.7} -BROTLI_RELEASE=${BROTLI_RELEASE:-$BROTLI_DEFAULT_RELEASE} +# Pin a patched upstream release even when the build runtime bundles an older decoder. +BROTLI_RELEASE=${BROTLI_RELEASE:-1.2.1} BROTLI_DEST_FOLDER=$PREFIX_DIR/deps/brotli echo "Building brotli v$BROTLI_RELEASE" ./scripts/ci/build-brotli.sh $BROTLI_RELEASE $BROTLI_DEST_FOLDER >$LOGS_FOLDER/build-brotli.log 2>&1 @@ -380,17 +377,29 @@ if [[ $LIBCURL_RELEASE == "LATEST" ]]; then LIBCURL_RELEASE=$LATEST_LIBCURL_RELEASE fi LIBCURL_DEST_FOLDER=$PREFIX_DIR/deps/libcurl +export LIBCURL_BUILD_FOLDER=$LIBCURL_DEST_FOLDER/build/$LIBCURL_RELEASE +if [[ -f "$LIBCURL_BUILD_FOLDER/lib/libcurl.a" ]]; then + cached_curl_version=$("$LIBCURL_BUILD_FOLDER/bin/curl" --version 2>/dev/null) || cached_curl_version= + if [[ " ${cached_curl_version%%$'\n'*} " != *" brotli/$BROTLI_RELEASE "* ]]; then + echo "Cached libcurl does not use Brotli $BROTLI_RELEASE; rebuilding libcurl" + export FORCE_REBUILD_LIBCURL=true + fi +fi echo "Building libcurl v$LIBCURL_RELEASE - Latest is v$LATEST_LIBCURL_RELEASE" ./scripts/ci/build-libcurl.sh $LIBCURL_RELEASE $LIBCURL_DEST_FOLDER || (echo "libcurl failed build log:" && cat_slower $LIBCURL_DEST_FOLDER/source/$LIBCURL_RELEASE/config.log && exit 1) echo "libcurl successful build log:" cat_slower $LIBCURL_DEST_FOLDER/source/$LIBCURL_RELEASE/config.log -export LIBCURL_BUILD_FOLDER=$LIBCURL_DEST_FOLDER/build/$LIBCURL_RELEASE ls -al $LIBCURL_BUILD_FOLDER/lib export PATH=$LIBCURL_DEST_FOLDER/build/$LIBCURL_RELEASE/bin:$PATH export LIBCURL_RELEASE=$LIBCURL_RELEASE -curl --version +curl_version=$("$LIBCURL_BUILD_FOLDER/bin/curl" --version) +echo "$curl_version" +if [[ " ${curl_version%%$'\n'*} " != *" brotli/$BROTLI_RELEASE "* ]]; then + echo "ERROR: expected libcurl to use Brotli $BROTLI_RELEASE" >&2 + exit 1 +fi curl-config --version curl-config --libs curl-config --static-libs diff --git a/src/Curl.cc b/src/Curl.cc index d14f86fb..08727d94 100644 --- a/src/Curl.cc +++ b/src/Curl.cc @@ -51,6 +51,7 @@ const std::vector curlOptionBlob = { {"PROXY_CAINFO_BLOB", CURLOPT_PROXY_CAINFO_BLOB}, #endif + {"PROXY_ISSUERCERT_BLOB", CURLOPT_PROXY_ISSUERCERT_BLOB}, {"PROXY_SSLCERT_BLOB", CURLOPT_PROXY_SSLCERT_BLOB}, {"PROXY_SSLKEY_BLOB", CURLOPT_PROXY_SSLKEY_BLOB}, {"SSLCERT_BLOB", CURLOPT_SSLCERT_BLOB}, @@ -64,6 +65,7 @@ const std::vector curlOptionFunction = { {"FNMATCH_FUNCTION", CURLOPT_FNMATCH_FUNCTION}, {"DEBUGFUNCTION", CURLOPT_DEBUGFUNCTION}, {"HEADERFUNCTION", CURLOPT_HEADERFUNCTION}, + {"INTERLEAVEFUNCTION", CURLOPT_INTERLEAVEFUNCTION}, #if NODE_LIBCURL_VER_GE(7, 74, 0) {"HSTSREADFUNCTION", CURLOPT_HSTSREADFUNCTION}, @@ -78,6 +80,10 @@ const std::vector curlOptionFunction = { {"READFUNCTION", CURLOPT_READFUNCTION}, {"SEEKFUNCTION", CURLOPT_SEEKFUNCTION}, +#if NODE_LIBCURL_VER_GE(7, 84, 0) + {"SSH_HOSTKEYFUNCTION", CURLOPT_SSH_HOSTKEYFUNCTION}, +#endif + #if NODE_LIBCURL_VER_GE(7, 64, 0) {"TRAILERFUNCTION", CURLOPT_TRAILERFUNCTION}, #endif @@ -106,6 +112,10 @@ const std::vector curlOptionInteger = { {"CA_CACHE_TIMEOUT", CURLOPT_CA_CACHE_TIMEOUT}, #endif +#if NODE_LIBCURL_VER_GE(7, 64, 1) + {"ALTSVC_CTRL", CURLOPT_ALTSVC_CTRL}, +#endif + {"CERTINFO", CURLOPT_CERTINFO}, {"CONNECTTIMEOUT", CURLOPT_CONNECTTIMEOUT}, {"CONNECTTIMEOUT_MS", CURLOPT_CONNECTTIMEOUT_MS}, @@ -113,6 +123,20 @@ const std::vector curlOptionInteger = { {"COOKIESESSION", CURLOPT_COOKIESESSION}, {"CRLF", CURLOPT_CRLF}, {"DIRLISTONLY", CURLOPT_DIRLISTONLY}, + {"FTPSSLAUTH", CURLOPT_FTPSSLAUTH}, + {"FTP_SSL_CCC", CURLOPT_FTP_SSL_CCC}, + +#if NODE_LIBCURL_VER_GE(7, 81, 0) + {"MIME_OPTIONS", CURLOPT_MIME_OPTIONS}, +#endif + +#if NODE_LIBCURL_VER_GE(7, 48, 0) + {"TFTP_NO_OPTIONS", CURLOPT_TFTP_NO_OPTIONS}, +#endif + +#if NODE_LIBCURL_VER_GE(7, 86, 0) + {"WS_OPTIONS", CURLOPT_WS_OPTIONS}, +#endif #if NODE_LIBCURL_VER_GE(7, 60, 0) {"DISALLOW_USERNAME_IN_URL", CURLOPT_DISALLOW_USERNAME_IN_URL}, @@ -364,8 +388,21 @@ const std::vector curlOptionLinkedList = { // This should be kept in sync with the options on scripts/utils/curlOptionsBlacklist.js const std::vector curlOptionNotImplemented = { +// Options that are used internally (their *FUNCTION counterparts are +// implemented and manage the data pointers themselves). +#if NODE_LIBCURL_VER_GE(7, 74, 0) + {"HSTSREADDATA", CURLOPT_HSTSREADDATA}, + {"HSTSWRITEDATA", CURLOPT_HSTSWRITEDATA}, +#endif +#if NODE_LIBCURL_VER_GE(7, 80, 0) + {"PREREQDATA", CURLOPT_PREREQDATA}, +#endif +#if NODE_LIBCURL_VER_GE(7, 84, 0) + {"SSH_HOSTKEYDATA", CURLOPT_SSH_HOSTKEYDATA}, +#endif + // Options that are complex to add support for. - {"SSL_CTX_FUNCTION", CURLOPT_TELNETOPTIONS}, + {"SSL_CTX_FUNCTION", CURLOPT_SSL_CTX_FUNCTION}, {"OPENSOCKETFUNCTION", CURLOPT_OPENSOCKETFUNCTION}, {"CLOSESOCKETFUNCTION", CURLOPT_CLOSESOCKETFUNCTION}, {"SOCKOPTFUNCTION", CURLOPT_SOCKOPTFUNCTION}, @@ -418,7 +455,6 @@ const std::vector curlOptionNotImplemented = { #endif // Maybe? - {"INTERLEAVEFUNCTION", CURLOPT_INTERLEAVEFUNCTION}, {"SSH_KEYFUNCTION", CURLOPT_SSH_KEYFUNCTION}, {"STDERR", CURLOPT_STDERR}, @@ -444,11 +480,23 @@ const std::vector curlOptionString = { {"CAPATH", CURLOPT_CAPATH}, {"COOKIE", CURLOPT_COOKIE}, {"COOKIEFILE", CURLOPT_COOKIEFILE}, +#if NODE_LIBCURL_VER_GE(7, 53, 0) + {"ABSTRACT_UNIX_SOCKET", CURLOPT_ABSTRACT_UNIX_SOCKET}, +#endif + +#if NODE_LIBCURL_VER_GE(7, 64, 1) + {"ALTSVC", CURLOPT_ALTSVC}, +#endif + {"COOKIEJAR", CURLOPT_COOKIEJAR}, {"COOKIELIST", CURLOPT_COOKIELIST}, {"CRLFILE", CURLOPT_CRLFILE}, {"CUSTOMREQUEST", CURLOPT_CUSTOMREQUEST}, +#if NODE_LIBCURL_VER_GE(7, 80, 0) + {"SSH_HOST_PUBLIC_KEY_SHA256", CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256}, +#endif + #if NODE_LIBCURL_VER_GE(7, 45, 0) {"DEFAULT_PROTOCOL", CURLOPT_DEFAULT_PROTOCOL}, #endif @@ -640,6 +688,11 @@ const std::vector curlMultiOptionInteger = { // Also see: https://github.com/curl/curl/pull/3651 {"MAX_PIPELINE_LENGTH", CURLMOPT_MAX_PIPELINE_LENGTH}, {"PIPELINING", CURLMOPT_PIPELINING}, + +#if NODE_LIBCURL_VER_GE(8, 20, 0) + {"QUICK_EXIT", CURLMOPT_QUICK_EXIT}, + {"RESOLVE_THREADS_MAX", CURLMOPT_RESOLVE_THREADS_MAX}, +#endif }; // This should be kept in sync with the options on scripts/utils/multiOptionsBlacklist.js @@ -776,6 +829,9 @@ const std::vector curlInfoOffT = { {"CONN_ID", CURLINFO_CONN_ID}, {"XFER_ID", CURLINFO_XFER_ID}, #endif +#if NODE_LIBCURL_VER_GE(8, 20, 0) + {"SIZE_DELIVERED", CURLINFO_SIZE_DELIVERED}, +#endif #if NODE_LIBCURL_VER_GE(8, 6, 0) {"QUEUE_TIME_T", CURLINFO_QUEUE_TIME_T}, #endif diff --git a/src/CurlMime.cc b/src/CurlMime.cc index be2b4e12..e017bec5 100644 --- a/src/CurlMime.cc +++ b/src/CurlMime.cc @@ -608,7 +608,7 @@ size_t CurlMimePart::StaticReadCallback(char* buffer, size_t size, size_t nitems // Invalid return type return CURL_READFUNC_ABORT; } catch (const Napi::Error& error) { - part->easy->callbackError.Reset(error.Value()); + part->easy->callbackError.Reset(error.Value(), 1); return CURL_READFUNC_ABORT; } } @@ -635,7 +635,7 @@ int CurlMimePart::StaticSeekCallback(void* userdata, curl_off_t offset, int orig return CURL_SEEKFUNC_FAIL; } catch (const Napi::Error& error) { - part->easy->callbackError.Reset(error.Value()); + part->easy->callbackError.Reset(error.Value(), 1); return CURL_SEEKFUNC_FAIL; } } diff --git a/src/Easy.cc b/src/Easy.cc index 06a84fcf..07b025cb 100644 --- a/src/Easy.cc +++ b/src/Easy.cc @@ -24,6 +24,7 @@ #include "macros.h" #include +#include #include #include @@ -44,19 +45,20 @@ const napi_type_tag EASY_TYPE_TAG = { // ToFree class for memory management class Easy::ToFree { public: - std::vector> str; - std::vector slist; - std::vector mime; - std::vector> post; - - ~ToFree() { - for (auto& list : slist) { - if (list) curl_slist_free_all(list); - } - for (auto& m : mime) { - if (m) curl_mime_free(m); + std::map> lists; + std::shared_ptr> postFields; + std::shared_ptr httpPost; + + // MIME attachments retain the existing shared lifetime across duplicates. + struct MimeList { + std::vector handles; + + ~MimeList() { + for (auto* handle : handles) curl_mime_free(handle); } - } + }; + + std::shared_ptr mime = std::make_shared(); }; // Constructor @@ -138,6 +140,21 @@ Easy::~Easy() { } } +// node-addon-api schedules Finalize outside GC. curl_easy_cleanup and MIME +// cleanup can invoke callbacks, while releasing an AsyncContext uses Node-API. +void Easy::Finalize(Napi::Env env) { + if (!this->isOpen) return; + + // The wrapper object is gone, so callbacks no longer have a JS receiver. + // Preserve callbacks during explicit close, where the receiver is live. + this->callbacks.clear(); +#if NODE_LIBCURL_VER_GE(7, 74, 0) + curl_easy_setopt(this->ch, CURLOPT_HSTSWRITEFUNCTION, nullptr); +#endif + curl_easy_setopt(this->ch, CURLOPT_VERBOSE, 0L); + this->Dispose(); +} + // Dispose persistent objects and references stored during the life of this obj. void Easy::Dispose() { NODE_LIBCURL_DEBUG_LOG(this, "Easy::Dispose", ""); @@ -149,6 +166,11 @@ void Easy::Dispose() { this->ch = nullptr; this->isOpen = false; + // the libcurl handle no longer exists, so it no longer uses the share. + // Note that this must not be done on reset: curl_easy_reset keeps the + // share association + this->usedShareRef.Reset(); + const auto curl = this->Env().GetInstanceData(); curl->AdjustHandleMemory(CURL_HANDLE_TYPE_EASY, -1); @@ -163,6 +185,7 @@ void Easy::Dispose() { void Easy::DisposeInternalData() { this->callbacks.clear(); this->hstsReadCache.clear(); + this->wasHstsReadCacheSet = false; this->cbOnSocketEvent.Reset(); this->callbackError.Reset(); @@ -242,8 +265,8 @@ void Easy::CopyOtherData(Easy* orig) { this->cbOnSocketEventAsyncContext = orig->cbOnSocketEventAsyncContext; } - // Copy shared ToFree data - this->toFree = orig->toFree; + // Copy each option reference so replacing it on either handle is independent. + *this->toFree = *orig->toFree; } void Easy::CallSocketEvent(int status, int events) { @@ -277,6 +300,12 @@ void Easy::MonitorSockets() { curl_socket_t socket; retCurl = curl_easy_getinfo(this->ch, CURLINFO_ACTIVESOCKET, &socket); + // check the return code before the socket value - on failure the socket + // variable was never written to + if (retCurl != CURLE_OK) { + throw CurlError::New(this->Env(), "Failed to receive socket", retCurl, true); + } + if (socket == CURL_SOCKET_BAD) { throw CurlError::New(this->Env(), "Received invalid socket from the current connection!", CURLE_BAD_FUNCTION_ARGUMENT); @@ -284,11 +313,11 @@ void Easy::MonitorSockets() { #else long socket; // NOLINT(runtime/int) retCurl = curl_easy_getinfo(this->ch, CURLINFO_LASTSOCKET, &socket); -#endif if (retCurl != CURLE_OK) { throw CurlError::New(this->Env(), "Failed to receive socket", retCurl, true); } +#endif this->socketPollHandle = new uv_poll_t; @@ -301,6 +330,11 @@ void Easy::MonitorSockets() { retUv = uv_poll_init_socket(loop, this->socketPollHandle, socket); if (retUv < 0) { + // release the handle, otherwise it would leak and any later + // monitorSocketEvents() call would wrongly report "Already monitoring" + delete this->socketPollHandle; + this->socketPollHandle = nullptr; + std::string errorMsg = std::string("Failed to poll on connection socket. Reason: ") + UV_ERROR_STRING(retUv); @@ -315,10 +349,27 @@ void Easy::MonitorSockets() { assert(obj); obj->CallSocketEvent(status, events); }); + + if (retUv < 0) { + // initialized handles must go through uv_close, a plain delete is not safe + uv_close(reinterpret_cast(this->socketPollHandle), + [](uv_handle_t* handle) { delete handle; }); + this->socketPollHandle = nullptr; + + std::string errorMsg = + std::string("Failed to start polling on socket. Reason: ") + UV_ERROR_STRING(retUv); + + throw CurlError::New(this->Env(), errorMsg.c_str(), CURLE_INTERFACE_FAILED); + } + this->isMonitoringSockets = true; } void Easy::UnmonitorSockets() { + if (!this->socketPollHandle) { + throw CurlError::New(this->Env(), "Not monitoring sockets!", CURLE_BAD_FUNCTION_ARGUMENT); + } + int retUv; retUv = uv_poll_stop(this->socketPollHandle); @@ -331,6 +382,10 @@ void Easy::UnmonitorSockets() { uv_close(reinterpret_cast(this->socketPollHandle), [](uv_handle_t* handle) { delete handle; }); + // the poll handle is deleted by the close callback above - drop our pointer + // so the handle can be monitored again and a double unmonitor cannot + // touch freed memory + this->socketPollHandle = nullptr; this->isMonitoringSockets = false; } @@ -338,7 +393,9 @@ void inline Easy::throwErrorMultiInterfaceAware(const Napi::Error& error) noexce Napi::HandleScope scope(this->Env()); if (this->isInsideMultiHandle) { - this->callbackError.Reset(error.Value()); + // refcount 1: the default (0) creates a weak reference, and the error + // object could be collected before the Multi consumes it + this->callbackError.Reset(error.Value(), 1); } else { error.ThrowAsJavaScriptException(); } @@ -457,6 +514,10 @@ Napi::Value Easy::SetOpt(const Napi::CallbackInfo& info) { case CURLOPT_SHARE: if (value.IsNull()) { setOptRetCode = curl_easy_setopt(this->ch, CURLOPT_SHARE, NULL); + + if (setOptRetCode == CURLE_OK) { + this->usedShareRef.Reset(); + } } else { if (!value.IsObject() || !value.As().InstanceOf(curl->ShareConstructor.Value())) { @@ -473,13 +534,29 @@ Napi::Value Easy::SetOpt(const Napi::CallbackInfo& info) { } setOptRetCode = curl_easy_setopt(this->ch, CURLOPT_SHARE, share->sh); + + if (setOptRetCode == CURLE_OK) { + this->usedShareRef.Reset(); + + // libcurl keeps a pointer to the share until it is unset or this + // easy handle is disposed. + this->usedShareRef = Napi::Persistent(value.As()); + } } break; } // linked list options } else if ((optionId = IsInsideCurlConstantStruct(curlOptionLinkedList, opt))) { if (value.IsNull()) { - setOptRetCode = curl_easy_setopt(this->ch, static_cast(optionId), NULL); + const auto option = static_cast(optionId); + setOptRetCode = curl_easy_setopt(this->ch, option, nullptr); + if (setOptRetCode == CURLE_OK) { + if (option == CURLOPT_HTTPPOST) { + this->toFree->httpPost.reset(); + } else { + this->toFree->lists.erase(option); + } + } // HTTPPOST is a special case, since it's an array of objects. } else if (optionId == CURLOPT_HTTPPOST) { std::string invalidArrayMsg = "HTTPPOST option value should be an Array of Objects."; @@ -489,7 +566,7 @@ Napi::Value Easy::SetOpt(const Napi::CallbackInfo& info) { } Napi::Array rows = value.As(); - auto httpPost = std::make_unique(); + auto httpPost = std::make_shared(); // [{ key : val }] for (uint32_t i = 0, len = rows.Length(); i < len; ++i) { @@ -599,7 +676,7 @@ Napi::Value Easy::SetOpt(const Napi::CallbackInfo& info) { setOptRetCode = curl_easy_setopt(this->ch, CURLOPT_HTTPPOST, httpPost->first); if (setOptRetCode == CURLE_OK) { - this->toFree->post.push_back(std::move(httpPost)); + this->toFree->httpPost = std::move(httpPost); } #if NODE_LIBCURL_VER_GE(7, 56, 0) @@ -633,10 +710,13 @@ Napi::Value Easy::SetOpt(const Napi::CallbackInfo& info) { } #endif - setOptRetCode = curl_easy_setopt(this->ch, CURLOPT_MIMEPOST, curlMime->mime); + auto& handles = this->toFree->mime->handles; + const bool isNew = std::find(handles.begin(), handles.end(), curlMime->mime) == handles.end(); + if (isNew) handles.reserve(handles.size() + 1); - if (setOptRetCode == CURLE_OK) { - this->toFree->mime.push_back(curlMime->mime); + setOptRetCode = curl_easy_setopt(this->ch, CURLOPT_MIMEPOST, curlMime->mime); + if (setOptRetCode == CURLE_OK && isNew) { + handles.push_back(curlMime->mime); } #endif @@ -645,49 +725,60 @@ Napi::Value Easy::SetOpt(const Napi::CallbackInfo& info) { throw Napi::TypeError::New(env, "Option value must be an Array."); } - // convert value to curl linked list (curl_slist) - curl_slist* slist = NULL; + std::unique_ptr list(nullptr, curl_slist_free_all); Napi::Array array = value.As(); for (uint32_t i = 0, len = array.Length(); i < len; ++i) { - std::string item = array.Get(i).As().Utf8Value(); - slist = curl_slist_append(slist, item.c_str()); - } + Napi::Value element = array.Get(i); + if (!element.IsString()) { + throw Napi::TypeError::New(env, "Option value must be an Array of Strings."); + } - setOptRetCode = curl_easy_setopt(this->ch, static_cast(optionId), slist); + std::string item = element.As().Utf8Value(); + curl_slist* appended = curl_slist_append(list.get(), item.c_str()); + if (!appended) { + throw Napi::Error::New(env, "Could not append value to the list."); + } + // On success, the returned list owns the previous nodes. + list.release(); + list.reset(appended); + } + auto option = static_cast(optionId); + std::shared_ptr replacement(std::move(list)); + auto& previous = this->toFree->lists[option]; + setOptRetCode = curl_easy_setopt(this->ch, option, replacement.get()); if (setOptRetCode == CURLE_OK) { - this->toFree->slist.push_back(slist); + previous = std::move(replacement); } } // check if option is string, and the value is correct } else if ((optionId = IsInsideCurlConstantStruct(curlOptionString, opt))) { + auto option = static_cast(optionId); if (value.IsNull()) { - setOptRetCode = curl_easy_setopt(this->ch, static_cast(optionId), NULL); + setOptRetCode = curl_easy_setopt(this->ch, option, nullptr); + if (setOptRetCode == CURLE_OK && option == CURLOPT_POSTFIELDS) { + this->toFree->postFields.reset(); + } } else { if (!value.IsString()) { throw Napi::TypeError::New(env, "Option value must be a string."); } std::string valueStr = value.As().Utf8Value(); - - // libcurl makes a copy of the strings after version 7.17, CURLOPT_POSTFIELD - // is the only exception - if (static_cast(optionId) == CURLOPT_POSTFIELDS) { - std::vector valueChar(valueStr.begin(), valueStr.end()); - valueChar.push_back(0); - - setOptRetCode = - curl_easy_setopt(this->ch, static_cast(optionId), &valueChar[0]); - + if (option == CURLOPT_POSTFIELDS) { + auto bytes = std::make_shared>(valueStr.begin(), valueStr.end()); + bytes->push_back(0); + setOptRetCode = curl_easy_setopt(this->ch, option, bytes->data()); if (setOptRetCode == CURLE_OK) { - this->toFree->str.push_back(std::move(valueChar)); + this->toFree->postFields = std::move(bytes); } - } else { - setOptRetCode = - curl_easy_setopt(this->ch, static_cast(optionId), valueStr.c_str()); + setOptRetCode = curl_easy_setopt(this->ch, option, valueStr.c_str()); + if (setOptRetCode == CURLE_OK && option == CURLOPT_COPYPOSTFIELDS) { + this->toFree->postFields.reset(); + } } } @@ -1097,14 +1188,16 @@ Napi::Value Easy::GetInfo(const Napi::CallbackInfo& info) { } } } - } catch (const std::exception& e) { - // Inside Easy::GetInfoImpl we throw an exception with the error code - // so we can get it here and set the code to the correct value - std::string errMsg = e.what(); - std::string errCode; - std::copy_if(errMsg.begin(), errMsg.end(), std::back_inserter(errCode), ::isdigit); - code = static_cast(errCode.length() > 0 ? std::stoi(errCode) - : CURLE_BAD_FUNCTION_ARGUMENT); + } catch (Napi::Error& e) { + // GetInfoTmpl throws a CurlError carrying the failing CURLcode in the + // "code" property - read it directly instead of scraping digits out of + // the message (which also picked up digits belonging to the message + // itself, and could throw out of std::stoi) + Napi::Value codeValue = e.Value().Get("code"); + code = codeValue.IsNumber() ? static_cast(codeValue.As().Int32Value()) + : CURLE_BAD_FUNCTION_ARGUMENT; + } catch (const std::exception&) { + code = CURLE_BAD_FUNCTION_ARGUMENT; } Napi::Object ret = Napi::Object::New(env); @@ -1113,6 +1206,18 @@ Napi::Value Easy::GetInfo(const Napi::CallbackInfo& info) { return ret; } +void Easy::ResetPerTransferState() { + this->isCbProgressAlreadyAborted = false; + + for (auto& entry : this->hstsReadCache) { + entry.Reset(); + } + this->hstsReadCache.clear(); + this->wasHstsReadCacheSet = false; + + this->callbackError.Reset(); +} + Napi::Value Easy::Perform(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); OpenSslErrorQueueGuard openSslErrorQueueGuard; @@ -1123,6 +1228,8 @@ Napi::Value Easy::Perform(const Napi::CallbackInfo& info) { NODE_LIBCURL_DEBUG_LOG(this, "Easy::Perform", "performing request"); + this->ResetPerTransferState(); + LocaleGuard localeGuard; CURLcode code = curl_easy_perform(this->ch); @@ -1610,7 +1717,7 @@ size_t Easy::OnHeader(char* data, size_t size, size_t nmemb) { size_t Easy::ReadFunction(char* ptr, size_t size, size_t nmemb, void* userdata) { Easy* obj = static_cast(userdata); - int32_t returnValue = CURL_READFUNC_ABORT; + int64_t returnValue = CURL_READFUNC_ABORT; int32_t fd = obj->readDataFileDescriptor; size_t n = size * nmemb; @@ -1624,7 +1731,12 @@ size_t Easy::ReadFunction(char* ptr, size_t size, size_t nmemb, void* userdata) try { Napi::Function cb = it->second.Value(); - Napi::Buffer buffer = Napi::Buffer::New(env, static_cast(n)); + Napi::Buffer buffer = Napi::Buffer::New(env, n); + // napi buffers are not zero-initialized (think Buffer.allocUnsafe) - + // without this the callback could read stale heap contents + if (buffer.Data()) { + std::memset(buffer.Data(), 0, n); + } // TODO(jonathan, migration): capture this when perform is called (either on Easy or Multi) Napi::AsyncContext asyncContext(env, "Easy::ReadFunction"); @@ -1649,14 +1761,25 @@ size_t Easy::ReadFunction(char* ptr, size_t size, size_t nmemb, void* userdata) return returnValue; } - returnValue = result.As().Int32Value(); + double count = result.As().DoubleValue(); + if (count == CURL_READFUNC_ABORT) return CURL_READFUNC_ABORT; + if (count == CURL_READFUNC_PAUSE) { + obj->pauseState |= CURLPAUSE_SEND; + return CURL_READFUNC_PAUSE; + } - char* data = buffer.Data(); - bool hasData = !!data && returnValue > 0 && returnValue < CURL_READFUNC_ABORT; + if (!std::isfinite(count) || count < 0 || count > n || std::trunc(count) != count) { + Napi::TypeError typeError = Napi::TypeError::New( + env, "READFUNCTION must return an integer byte count within the buffer size."); + obj->throwErrorMultiInterfaceAware(typeError); + return CURL_READFUNC_ABORT; + } - if (hasData) { - std::memcpy(ptr, data, returnValue); + size_t bytesRead = static_cast(count); + if (bytesRead) { + std::memcpy(ptr, buffer.Data(), bytesRead); } + return bytesRead; } catch (const Napi::Error& e) { obj->throwErrorMultiInterfaceAware(e); @@ -1671,9 +1794,6 @@ size_t Easy::ReadFunction(char* ptr, size_t size, size_t nmemb, void* userdata) // get the offset curl_off_t offset = obj->readDataOffset; - if (offset >= 0) { - obj->readDataOffset += n; - } uv_fs_t readReq; @@ -1692,6 +1812,12 @@ size_t Easy::ReadFunction(char* ptr, size_t size, size_t nmemb, void* userdata) returnValue = uv_fs_read(loop, &readReq, fd, &uvbuf, 1, offset, NULL); #endif uv_fs_req_cleanup(&readReq); + + // advance by the amount actually read - advancing by the requested size + // would skip data after a short read + if (offset >= 0 && returnValue > 0) { + obj->readDataOffset += returnValue; + } } if (returnValue < 0) { @@ -1705,7 +1831,7 @@ size_t Easy::ReadFunction(char* ptr, size_t size, size_t nmemb, void* userdata) return static_cast(returnValue); } -size_t Easy::SeekFunction(void* userdata, curl_off_t offset, int origin) { +int Easy::SeekFunction(void* userdata, curl_off_t offset, int origin) { Easy* obj = static_cast(userdata); int32_t returnValue = CURL_SEEKFUNC_FAIL; @@ -1726,11 +1852,13 @@ size_t Easy::SeekFunction(void* userdata, curl_off_t offset, int origin) { // TODO(jonathan, migration): capture this when perform is called (either on Easy or Multi) Napi::AsyncContext asyncContext(env, "Easy::SeekFunction"); - Napi::Value result = - cb.MakeCallback(obj->Value(), - {Napi::Number::New(env, static_cast(offset)), - Napi::Number::New(env, static_cast(origin))}, - asyncContext); + Napi::Value result = cb.MakeCallback( + obj->Value(), + {// JS numbers hold integers up to 2^53 exactly, more than + // enough for file offsets - a uint32 cast would wrap for + // offsets >= 4GiB and corrupt resumed transfers + Napi::Number::New(env, static_cast(offset)), Napi::Number::New(env, origin)}, + asyncContext); // This is in theory not needed, as we have exceptions enabled if (env.IsExceptionPending()) { @@ -2227,9 +2355,11 @@ int Easy::CbHstsRead(CURL* handle, struct curl_hstsentry* sts, void* userdata) { return returnValue; } - // Set host name - strncpy(sts->name, hostStrValue.c_str(), sts->namelen); - sts->name[sts->namelen - 1] = '\0'; // Ensure null termination + // Set host name - the buffer behind sts->name holds namelen + 1 bytes + // (see hsts_pull in libcurl's hsts.c), so terminating at the actual + // length is in-bounds and does not truncate max-length hostnames + std::memcpy(sts->name, hostStrValue.c_str(), hostStrValue.length()); + sts->name[hostStrValue.length()] = '\0'; // Set includeSubDomains if (!includeSubDomainsProperty.IsUndefined() && !includeSubDomainsProperty.IsNull()) { @@ -2573,12 +2703,22 @@ int Easy::CbSshHostKey(void* clientp, int keytype, const char* key, size_t keyle #endif } +// A refused or failed push is cleaned up by libcurl. +void Easy::DisownHandle() { + this->ch = nullptr; + this->isOpen = false; + this->isInsideMultiHandle = false; + this->Env().GetInstanceData()->AdjustHandleMemory(CURL_HANDLE_TYPE_EASY, -1); + this->DisposeInternalData(); +} + Napi::Object Easy::FromCURLHandle(Napi::Env env, CURL* handle) { // this is a static method possibly called from outside a Node.js callstack // thus we need to properly handle the scopes. Napi::EscapableHandleScope scope(env); Napi::External curlEasyHandle = Napi::External::New(env, handle); + curlEasyHandle.TypeTag(&EASY_TYPE_TAG); auto curl = env.GetInstanceData(); auto newInstance = curl->EasyConstructor.New({curlEasyHandle}); diff --git a/src/Easy.h b/src/Easy.h index 2b6d2bee..ff550404 100644 --- a/src/Easy.h +++ b/src/Easy.h @@ -29,6 +29,7 @@ class Easy : public Napi::ObjectWrap { public: Easy(const Napi::CallbackInfo& info); ~Easy(); + void Finalize(Napi::Env env) override; static Napi::Function Init(Napi::Env env, Napi::Object exports); @@ -75,9 +76,16 @@ class Easy : public Napi::ObjectWrap { // Callback error for Multi interface Napi::ObjectReference callbackError; + void DisownHandle(); + // Helper to create Easy from CURL handle static Napi::Object FromCURLHandle(Napi::Env env, CURL* handle); + // Resets state that is only valid for the duration of a single transfer. + // Must be called whenever a new transfer is started with this handle + // (Easy::Perform, Multi::AddHandle and Multi::Perform). + void ResetPerTransferState(); + private: // Internal class for cleanup management class ToFree; @@ -115,6 +123,9 @@ class Easy : public Napi::ObjectWrap { // Memory management std::shared_ptr toFree = nullptr; + // Keep the Share wrapper alive while libcurl uses it. + Napi::ObjectReference usedShareRef; + // HSTS cache std::vector> hstsReadCache; bool wasHstsReadCacheSet = false; @@ -124,7 +135,8 @@ class Easy : public Napi::ObjectWrap { // Static cURL callbacks static size_t ReadFunction(char* ptr, size_t size, size_t nmemb, void* userdata); - static size_t SeekFunction(void* userdata, curl_off_t offset, int origin); + // must match curl_seek_callback: int (*)(void *, curl_off_t, int) + static int SeekFunction(void* userdata, curl_off_t offset, int origin); static size_t HeaderFunction(char* ptr, size_t size, size_t nmemb, void* userdata); static size_t WriteFunction(char* ptr, size_t size, size_t nmemb, void* userdata); static long CbChunkBgn(curl_fileinfo* transferInfo, void* ptr, int remains); diff --git a/src/Http2PushFrameHeaders.cc b/src/Http2PushFrameHeaders.cc index 9436c064..5bc82148 100644 --- a/src/Http2PushFrameHeaders.cc +++ b/src/Http2PushFrameHeaders.cc @@ -59,8 +59,16 @@ Napi::Function Http2PushFrameHeaders::Init(Napi::Env env, Napi::Object exports) return func; } +void Http2PushFrameHeaders::RequireValidHeaders(Napi::Env env) const { + if (!this->headers) { + throw Napi::Error::New( + env, "This Http2PushFrameHeaders instance is only valid during the PUSHFUNCTION callback"); + } +} + Napi::Value Http2PushFrameHeaders::GetByIndex(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); + this->RequireValidHeaders(env); if (info.Length() < 1) { throw Napi::TypeError::New(env, "Wrong number of arguments"); @@ -84,6 +92,7 @@ Napi::Value Http2PushFrameHeaders::GetByIndex(const Napi::CallbackInfo& info) { Napi::Value Http2PushFrameHeaders::GetByName(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); + this->RequireValidHeaders(env); if (info.Length() < 1) { throw Napi::TypeError::New(env, "Wrong number of arguments"); diff --git a/src/Http2PushFrameHeaders.h b/src/Http2PushFrameHeaders.h index d6016206..277171bd 100644 --- a/src/Http2PushFrameHeaders.h +++ b/src/Http2PushFrameHeaders.h @@ -22,7 +22,12 @@ class Http2PushFrameHeaders : public Napi::ObjectWrap { // Constructor - must be public for ObjectWrap Http2PushFrameHeaders(const Napi::CallbackInfo& info); + // libcurl owns the headers and keeps them alive only during the push callback. + void Invalidate() { this->headers = nullptr; } + private: + void RequireValidHeaders(Napi::Env env) const; + // Copy constructors cannot be used Http2PushFrameHeaders(const Http2PushFrameHeaders& that) = delete; Http2PushFrameHeaders& operator=(const Http2PushFrameHeaders& that) = delete; diff --git a/src/Multi.cc b/src/Multi.cc index 13367ff2..9a3e8fb8 100644 --- a/src/Multi.cc +++ b/src/Multi.cc @@ -81,7 +81,7 @@ Multi::Multi(const Napi::CallbackInfo& info) : Napi::ObjectWrap(info), id // Used by OnSocket / OnTimeout to open a callback scope when entering JS from // libuv. Created once here rather than per event. - this->asyncContext = std::make_unique(env, "node-libcurl:Multi"); + this->asyncContext = std::make_shared(env, "node-libcurl:Multi"); // Enable notification API if requested and supported if (shouldUseNotificationsApi) { @@ -150,12 +150,22 @@ Multi::~Multi() { } } -void Multi::Dispose() { +// Declaring this makes node-addon-api defer the finalizer through +// node_api_post_finalizer instead of deleting the instance from inside the GC. +// Dispose calls napi_async_destroy (via asyncContext.reset()), which Node.js +// rejects from a GC finalizer with a fatal error. +void Multi::Finalize(Napi::Env env) { + NODE_LIBCURL_DEBUG_LOG(this, "Multi::Finalize", "isOpen: " + std::to_string(this->isOpen)); + this->Dispose(); +} + +void Multi::Dispose(bool rejectPending) { if (!this->isOpen) return; NODE_LIBCURL_DEBUG_LOG(this, "Multi::Dispose", ""); this->isOpen = false; + this->rejectPendingOnClose = rejectPending; // no point on running the timer anymore uv_timer_stop(&this->timeout); @@ -168,20 +178,64 @@ void Multi::Dispose() { // Clean up multi handle if (this->mh) { - CURLMcode code = curl_multi_cleanup(this->mh); - assert(code == CURLM_OK); - this->mh = nullptr; + if (this->isInsideSocketAction) { + NODE_LIBCURL_DEBUG_LOG(this, "Multi::Dispose", + "inside curl_multi_socket_action, deferring curl_multi_cleanup"); + this->cleanupPending = true; + } else { + this->CleanupMultiHandle(); + } } // Must happen while the environment is still valid: napi_async_destroy. + // A callback scope that is still open holds its own reference (see SocketAction). this->asyncContext.reset(); + // Release the self reference taken in the constructor once libuv has + // finished closing the timer embedded in this instance. + this->CloseTimerAsync(); + curl->AdjustHandleMemory(CURL_HANDLE_TYPE_MULTI, -1); } -// Debug logging methods removed - now using NODE_LIBCURL_DEBUG_LOG macros +void Multi::CleanupMultiHandle() { + for (const auto& [handle, easy] : this->attachedHandles) { + curl_multi_remove_handle(this->mh, handle); + easy->isInsideMultiHandle = false; + easy->Unref(); + } + this->attachedHandles.clear(); + this->amountOfHandles = 0; + + CURLMcode code = curl_multi_cleanup(this->mh); + assert(code == CURLM_OK && "curl_multi_cleanup failed"); + (void)code; + this->mh = nullptr; + this->cleanupPending = false; + + while (!this->socketContextMap.empty()) { + auto* ctx = this->socketContextMap.begin()->second; + uv_poll_stop(&ctx->pollHandle); + Multi::DestroyCurlSocketContext(ctx); + } + + if (this->rejectPendingOnClose && !this->handlePromiseMap.empty()) { + Napi::Env env = this->Env(); + Napi::HandleScope scope(env); + auto error = CurlError::New(env, "Multi handle closed during transfer", CURLM_BAD_HANDLE); + for (const auto& entry : this->handlePromiseMap) { + entry.second->Reject(error.Value()); + } + } + this->handlePromiseMap.clear(); +} -void Multi::StopTimer() { uv_timer_stop(&this->timeout); } +void Multi::TrackHandle(Easy* easy) { + this->attachedHandles.emplace(easy->ch, easy); + easy->Ref(); + easy->isInsideMultiHandle = true; + ++this->amountOfHandles; +} // Initialize the class for export Napi::Function Multi::Init(Napi::Env env, Napi::Object exports) { @@ -333,8 +387,8 @@ Napi::Value Multi::AddHandle(const Napi::CallbackInfo& info) { NODE_LIBCURL_DEBUG_LOG(this, "Multi::AddHandle", "adding handle " + std::to_string(easy->id)); - // reset callback error in case it is set - easy->callbackError.Reset(); + // reset state that is only valid for a single transfer + easy->ResetPerTransferState(); // Check comment on node_libcurl.cc LocaleGuard localeGuard; @@ -344,8 +398,7 @@ Napi::Value Multi::AddHandle(const Napi::CallbackInfo& info) { throw CurlError::New(env, "Could not add easy handle to the multi handle.", code, true); } - ++this->amountOfHandles; - easy->isInsideMultiHandle = true; + this->TrackHandle(easy); return Napi::Number::New(env, static_cast(code)); } @@ -378,6 +431,13 @@ Napi::Value Multi::RemoveHandle(const Napi::CallbackInfo& info) { NODE_LIBCURL_DEBUG_LOG(this, "Multi::RemoveHandle", "removing handle " + std::to_string(easy->id)); + auto attached = this->attachedHandles.find(easy->ch); + if (attached == this->attachedHandles.end()) { + if (!easy->isInsideMultiHandle) return Napi::Number::New(env, CURLM_OK); + throw CurlError::New(env, "Easy handle belongs to another Multi or is still being pushed", + CURLM_BAD_EASY_HANDLE); + } + CURLMcode code = curl_multi_remove_handle(this->mh, easy->ch); if (code != CURLM_OK) { @@ -386,6 +446,16 @@ Napi::Value Multi::RemoveHandle(const Napi::CallbackInfo& info) { --this->amountOfHandles; easy->isInsideMultiHandle = false; + this->attachedHandles.erase(attached); + + auto pending = this->handlePromiseMap.find(easy->ch); + if (pending != this->handlePromiseMap.end()) { + auto error = + CurlError::New(env, "Easy handle removed during transfer", CURLM_BAD_EASY_HANDLE); + pending->second->Reject(error.Value()); + this->handlePromiseMap.erase(pending); + } + easy->Unref(); return Napi::Number::New(env, static_cast(code)); } @@ -424,8 +494,8 @@ Napi::Value Multi::Perform(const Napi::CallbackInfo& info) { // Create deferred promise auto deferred = Napi::Promise::Deferred::New(env); - // reset callback error in case it is set - easy->callbackError.Reset(); + // reset state that is only valid for a single transfer + easy->ResetPerTransferState(); // Check comment on node_libcurl.cc LocaleGuard localeGuard; @@ -435,8 +505,7 @@ Napi::Value Multi::Perform(const Napi::CallbackInfo& info) { throw CurlError::New(env, "Could not add easy handle to the multi handle.", code, true); } - ++this->amountOfHandles; - easy->isInsideMultiHandle = true; + this->TrackHandle(easy); // Store the deferred promise for this handle this->handlePromiseMap[easy->ch] = std::make_shared(std::move(deferred)); @@ -494,7 +563,7 @@ Napi::Value Multi::Close(const Napi::CallbackInfo& info) { NODE_LIBCURL_DEBUG_LOG(this, "Multi::Close", ""); - this->Dispose(); + this->Dispose(true); return env.Undefined(); } @@ -591,6 +660,8 @@ void Multi::CallOnMessageCallback(CURL* easy, CURLcode handleCode) { return; } + if (this->cbOnMessage.IsEmpty()) return; + Napi::Function callback = this->cbOnMessage.Value(); // Create arguments: error (null or Error object), Easy instance @@ -679,8 +750,6 @@ void Multi::DestroyCurlSocketContext(CurlSocketContext* ctx) { if (!uv_is_closing(handle)) { uv_close(handle, [](uv_handle_t* handle) { auto ctx = static_cast(handle->data); - NODE_LIBCURL_DEBUG_LOG(ctx->multi, "Multi::DestroyCurlSocketContext", - "Closed socket context for socket: " + std::to_string(ctx->sockfd)); delete ctx; }); } @@ -707,8 +776,9 @@ int Multi::HandleSocket(CURL* easy, curl_socket_t s, int action, void* userp, vo // set event based on the current action int events = 0; - if (action != CURL_POLL_IN) events |= UV_WRITABLE; - if (action != CURL_POLL_OUT) events |= UV_READABLE; + if (action == CURL_POLL_OUT || action == CURL_POLL_INOUT) events |= UV_WRITABLE; + if (action == CURL_POLL_IN || action == CURL_POLL_INOUT) events |= UV_READABLE; + if (events == 0) return uv_poll_stop(&ctx->pollHandle); NODE_LIBCURL_DEBUG_LOG(obj, "Multi::HandleSocket", "Starting poll for socket: " + std::to_string(s) + @@ -745,7 +815,9 @@ int Multi::HandleTimeout(CURLM* multi, void* userp) { Multi* obj = static_cast(userp); - if (obj->timerClosed) { + // After close(), libcurl can still ask for a timer while a deferred cleanup is + // pending, or while curl_multi_cleanup itself runs. Nothing would act on it. + if (obj->timerClosed || !obj->isOpen) { return 0; } @@ -765,6 +837,10 @@ int Multi::HandleTimeout(CURLM* multi, int Multi::CbPushFunction(CURL* parent, CURL* child, size_t numberOfHeaders, struct curl_pushheaders* headers, void* userPtr) { +#if !NODE_LIBCURL_VER_GE(8, 4, 0) + // curl_multi_get_handles is required to confirm that libcurl adopted a push. + return CURL_PUSH_DENY; +#else // Note: // We cannot throw js errors inside this callback // as there is no way to signal libcurl to mark this request as failed @@ -775,13 +851,10 @@ int Multi::CbPushFunction(CURL* parent, CURL* child, size_t numberOfHeaders, int returnValue = CURL_PUSH_DENY; Multi* obj = static_cast(userPtr); - assert(obj); - assert(obj->isOpen); + if (!obj || !obj->isOpen) return CURL_PUSH_DENY; auto it = obj->callbacks.find(CURLMOPT_PUSHFUNCTION); - assert(it != obj->callbacks.end() && "PUSHFUNCTION callback not set."); - - if (it->second.IsEmpty()) { + if (it == obj->callbacks.end() || it->second.IsEmpty()) { return CURL_PUSH_DENY; } @@ -798,10 +871,15 @@ int Multi::CbPushFunction(CURL* parent, CURL* child, size_t numberOfHeaders, Napi::Env env = it->second.Env(); Napi::HandleScope scope(env); auto curl = env.GetInstanceData(); + Http2PushFrameHeaders* pushHeaders = nullptr; + Easy* childWrapper = nullptr; try { Napi::Object parentEasyJsObj = parentEasyObj->Value(); Napi::Object childEasyJsObj = Easy::FromCURLHandle(env, child); + childWrapper = Easy::Unwrap(childEasyJsObj); + // libcurl owns the child throughout PUSHFUNCTION, including while calling JS. + childWrapper->isInsideMultiHandle = true; auto headersExternal = Napi::External::New(env, headers); headersExternal.TypeTag(&HTTP2_PUSH_FRAME_HEADERS_TYPE_TAG); @@ -810,6 +888,7 @@ int Multi::CbPushFunction(CURL* parent, CURL* child, size_t numberOfHeaders, headersExternal, Napi::Number::New(env, numberOfHeaders), }); + pushHeaders = Http2PushFrameHeaders::Unwrap(http2PushFrameJsObj); Napi::Function callback = it->second.Value(); // TODO(jonathan, migration): capture this when perform is called or similar (either on Easy or @@ -825,15 +904,52 @@ int Multi::CbPushFunction(CURL* parent, CURL* child, size_t numberOfHeaders, asyncContext); if (!returnValueCallback.IsEmpty() && returnValueCallback.IsNumber()) { - returnValue = returnValueCallback.As().Int32Value(); + double decision = returnValueCallback.As().DoubleValue(); + if (decision == CURL_PUSH_OK && obj->isOpen) returnValue = CURL_PUSH_OK; + if (decision == CURL_PUSH_ERROROUT) returnValue = CURL_PUSH_ERROROUT; } } catch (const Napi::Error&) { // See the note at the top of this function, we must not rethrow this error. // Show some Debug message? - return returnValue; + } + + if (pushHeaders) { + pushHeaders->Invalidate(); + } + + if (childWrapper) { + // libcurl may still use the child while accepting or discarding the push. + // Keep the wrapper and its option data alive until the socket action ends. + obj->pendingPushes.emplace(child, childWrapper); + childWrapper->Ref(); + childWrapper->isOpen = false; } return returnValue; +#endif +} + +void Multi::ResolvePushOwnership() { +#if NODE_LIBCURL_VER_GE(8, 4, 0) + if (this->pendingPushes.empty()) return; + + CURL** handles = curl_multi_get_handles(this->mh); + if (!handles) return; + + for (const auto& [handle, easy] : this->pendingPushes) { + CURL** current = handles; + while (*current && *current != handle) ++current; + if (*current) { + easy->isOpen = true; + this->TrackHandle(easy); + } else { + easy->DisownHandle(); + } + easy->Unref(); + } + this->pendingPushes.clear(); + curl_free(handles); +#endif } #if NODE_LIBCURL_VER_GE(8, 17, 0) @@ -844,85 +960,109 @@ void Multi::NotifyCallback(CURLM* multi, unsigned int notification, CURL* easy, NODE_LIBCURL_DEBUG_LOG(obj, "Multi::NotifyCallback", "notification: " + std::to_string(notification)); - if (notification == CURLMNOTIFY_INFO_READ) { + if (notification == CURLMNOTIFY_INFO_READ && obj->pendingPushes.empty()) { obj->ProcessMessages(); } } #endif -// function called when the previous timeout set reaches 0 -UV_TIMER_CB(Multi::OnTimeout) { - Multi* obj = static_cast(timer->data); +// Single entry point from libuv (OnTimeout / OnSocket) into libcurl, and from +// there into JS. Callers must check isOpen first. +CURLMcode Multi::SocketAction(curl_socket_t sockfd, int flags) { + assert(this->isOpen && this->mh && !this->isInsideSocketAction); // This runs from libuv, that is, from outside any JS context. Node.js only // performs a microtask checkpoint when a callback scope is closed, so without - // one the promise CallOnMessageCallback settles below stays queued until - // something else happens to drain the microtask queue - which, for a caller - // awaiting one request at a time, is the next tick of this very timer. - if (!obj->asyncContext) return; - - Napi::Env env = obj->Env(); + // one the promise CallOnMessageCallback settles stays queued until something + // else happens to drain the microtask queue - which, for a caller awaiting + // one request at a time, is the next tick of the multi timer. + // + // The local copy must outlive callbackScope (it is declared first, so it is + // destroyed last): close() from inside a callback resets this->asyncContext + // while the scope is still open, and since Node.js 25 the async resource + // stack points into the context. + std::shared_ptr asyncContext = this->asyncContext; + + Napi::Env env = this->Env(); Napi::HandleScope handleScope(env); - Napi::CallbackScope callbackScope(env, *obj->asyncContext); + Napi::CallbackScope callbackScope(env, *asyncContext); + // Declared after callbackScope so the queue is cleared before the scope + // closes and runs the microtask checkpoint (JS that may do TLS I/O). OpenSslErrorQueueGuard openSslErrorQueueGuard; - NODE_LIBCURL_DEBUG_LOG(obj, "Multi::OnTimeout", ""); - // Check comment on node_libcurl.cc LocaleGuard localeGuard; - CURLMcode code = curl_multi_socket_action(obj->mh, CURL_SOCKET_TIMEOUT, 0, &obj->runningHandles); + + CURLMcode code; + + this->isInsideSocketAction = true; + // Before version 7.20.0: If you receive CURLM_CALL_MULTI_PERFORM, this + // basically means that you should call curl_multi_socket_action again + // before you wait for more actions on libcurl's sockets. + // You don't have to do it immediately, but the return code means that + // libcurl may have more data available to return or that there may be more data + // to send off before it is "satisfied". + do { + code = curl_multi_socket_action(this->mh, sockfd, flags, &this->runningHandles); + } while (code == CURLM_CALL_MULTI_PERFORM); + this->isInsideSocketAction = false; + + const bool hadPendingPushes = !this->pendingPushes.empty(); + this->ResolvePushOwnership(); + + // close() was called while libcurl was on the stack, finish it now. + if (this->cleanupPending) { + this->CleanupMultiHandle(); + } + + // When notifications are enabled, libcurl will call our NotifyCallback when needed. + // ProcessMessages is a no-op if the handle was closed above. + if (this->pendingPushes.empty() && (!this->useNotificationsApi || hadPendingPushes)) { + this->ProcessMessages(); + } + + return code; +} + +// function called when the previous timeout set reaches 0 +UV_TIMER_CB(Multi::OnTimeout) { + Multi* obj = static_cast(timer->data); + + if (!obj->isOpen) return; + + NODE_LIBCURL_DEBUG_LOG(obj, "Multi::OnTimeout", ""); + + CURLMcode code = obj->SocketAction(CURL_SOCKET_TIMEOUT, 0); assert((CURLM_OK == code || true) && "Calling curl_multi_socket_action from within Multi::OnTimeout failed. This is possibly a " "bug on node-libcurl or libcurl itself. Please report this issue to node-libcurl."); - - // When notifications are enabled, libcurl will call our NotifyCallback when needed - if (!obj->useNotificationsApi) { - obj->ProcessMessages(); - } + (void)code; } void Multi::OnSocket(uv_poll_t* handle, int status, int events) { int flags = 0; - CURLMcode code; - if (status < 0) flags = CURL_CSELECT_ERR; if (events & UV_READABLE) flags |= CURL_CSELECT_IN; if (events & UV_WRITABLE) flags |= CURL_CSELECT_OUT; Multi::CurlSocketContext* ctx = static_cast(handle->data); - // See the comment in Multi::OnTimeout - a callback scope is required here for - // the microtask checkpoint to run. - if (!ctx->multi->asyncContext) return; - - Napi::Env env = ctx->multi->Env(); - Napi::HandleScope handleScope(env); - Napi::CallbackScope callbackScope(env, *ctx->multi->asyncContext); - OpenSslErrorQueueGuard openSslErrorQueueGuard; + // libcurl removes its sockets during curl_multi_cleanup, so this should not + // happen. If it does, stop polling: a level-triggered socket that nobody + // reads would otherwise wake this callback on every loop iteration. + if (!ctx->multi->isOpen) { + uv_poll_stop(handle); + return; + } NODE_LIBCURL_DEBUG_LOG(ctx->multi, "Multi::OnSocket", "events: " + std::to_string(events)); - // Check comment on node_libcurl.cc - LocaleGuard localeGuard; - // Before version 7.20.0: If you receive CURLM_CALL_MULTI_PERFORM, this - // basically means that you should call curl_multi_socket_action again - // before you wait for more actions on libcurl's sockets. - // You don't have to do it immediately, but the return code means that - // libcurl may have more data available to return or that there may be more data - // to send off before it is "satisfied". - do { - code = - curl_multi_socket_action(ctx->multi->mh, ctx->sockfd, flags, &ctx->multi->runningHandles); - } while (code == CURLM_CALL_MULTI_PERFORM); + CURLMcode code = ctx->multi->SocketAction(ctx->sockfd, flags); assert(code == CURLM_OK && "curl_multi_socket_action failed"); - - // When notifications are enabled, libcurl will call our NotifyCallback when needed - if (!ctx->multi->useNotificationsApi) { - ctx->multi->ProcessMessages(); - } + (void)code; } } // namespace NodeLibcurl diff --git a/src/Multi.h b/src/Multi.h index 5d0139df..02bd8979 100644 --- a/src/Multi.h +++ b/src/Multi.h @@ -27,6 +27,10 @@ class Multi : public Napi::ObjectWrap { Multi(const Napi::CallbackInfo& info); ~Multi(); + // Runs from node_api_post_finalizer, outside the GC, so Dispose can call + // Node-API functions that are not allowed inside a GC finalizer. + void Finalize(Napi::Env env) override; + // Static methods for JS class initialization static Napi::Function Init(Napi::Env env, Napi::Object exports); @@ -61,9 +65,12 @@ class Multi : public Napi::ObjectWrap { }; // Private methods - void StopTimer(); void CloseTimerAsync(); - void Dispose(); + void Dispose(bool rejectPending = false); + void CleanupMultiHandle(); + void TrackHandle(Easy* easy); + void ResolvePushOwnership(); + CURLMcode SocketAction(curl_socket_t sockfd, int flags); void ProcessMessages(); void CallOnMessageCallback(CURL* easy, CURLcode statusCode); @@ -79,6 +86,11 @@ class Multi : public Napi::ObjectWrap { // Promise-based perform tracking std::map> handlePromiseMap; + // Keep Easy wrappers alive until their handles are removed. + std::map attachedHandles; + std::map pendingPushes; + bool rejectPendingOnClose = false; + // Timer for timeout handling uv_timer_t timeout; bool timerClosed = false; @@ -88,7 +100,16 @@ class Multi : public Napi::ObjectWrap { // Both libuv callbacks below (OnSocket / OnTimeout) call into JS from outside // any JS context, so they need a callback scope. One long-lived async context // per Multi is enough, and avoids a napi_async_init per socket event. - std::unique_ptr asyncContext; + // Shared so an open scope can keep it alive across close() (see SocketAction). + std::shared_ptr asyncContext; + + // libcurl rejects curl_multi_cleanup with CURLM_RECURSIVE_API_CALL while + // curl_multi_socket_action is on the stack (for example, close() called from + // onMessage with the notifications API, or from an Easy callback). Dispose + // then sets cleanupPending, and SocketAction runs the cleanup once libcurl + // has returned. + bool isInsideSocketAction = false; + bool cleanupPending = false; std::map socketContextMap; diff --git a/src/Share.cc b/src/Share.cc index 53874d80..67ea5219 100644 --- a/src/Share.cc +++ b/src/Share.cc @@ -61,7 +61,7 @@ void Share::Dispose() { this->isOpen = false; CURLSHcode code = curl_share_cleanup(this->sh); - assert(code == CURLSHE_OK); + assert((code == CURLSHE_OK || code == CURLSHE_IN_USE) && "Failed to cleanup share handle."); auto curl = this->Env().GetInstanceData(); curl->AdjustHandleMemory(CURL_HANDLE_TYPE_SHARE, -1); @@ -132,7 +132,14 @@ Napi::Value Share::Close(const Napi::CallbackInfo& info) { throw CurlError::New(env, "Share handle already closed.", CURLSHE_INVALID); } - this->Dispose(); + CURLSHcode code = curl_share_cleanup(this->sh); + if (code != CURLSHE_OK) { + throw CurlError::New(env, "Could not close share handle", code, true); + } + + this->isOpen = false; + this->sh = nullptr; + env.GetInstanceData()->AdjustHandleMemory(CURL_HANDLE_TYPE_SHARE, -1); return env.Undefined(); } diff --git a/test/curl/close.spec.ts b/test/curl/close.spec.ts new file mode 100644 index 00000000..b86b8490 --- /dev/null +++ b/test/curl/close.spec.ts @@ -0,0 +1,87 @@ +/** + * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import { describe, beforeAll, afterAll, it, expect } from 'vitest' + +import { createServer } from '../helper/server' +import { Curl, Multi } from '../../lib' +import { withCommonTestOptions } from '../helper/commonOptions' + +let serverInstance: ReturnType + +describe('close()', () => { + beforeAll(async () => { + serverInstance = createServer() + serverInstance.app.get('/', (_req, res) => { + res.send('Hello World!') + }) + await serverInstance.listen() + }) + + afterAll(async () => { + await serverInstance.close() + }) + + it('should safely abort an in-flight request', async () => { + const curl = new Curl() + withCommonTestOptions(curl) + curl.setOpt('URL', serverInstance.url) + + await new Promise((resolve, reject) => { + curl.on('data', () => { + try { + curl.close() + } catch (error) { + reject(error) + return + } + + // the rejection of the internal multi.perform() promise is processed + // asynchronously - give it time to settle so an uncaught 'error' emit + // (which would crash the process) has a chance to happen + setTimeout(resolve, 100) + }) + + curl.perform() + }) + + expect(curl.isOpen).toBe(false) + }) + + it('should remove the handle from the custom Multi instance set with setMulti()', async () => { + const multi = new Multi() + const curl = new Curl() + withCommonTestOptions(curl) + curl.setMulti(multi) + curl.setOpt('URL', serverInstance.url) + + try { + await new Promise((resolve, reject) => { + curl.on('data', () => { + try { + // with the bug, this tries to remove the handle from the global + // multi instead of the custom one and throws + curl.close() + } catch (error) { + reject(error) + return + } + + setTimeout(resolve, 100) + }) + + curl.perform() + }) + + expect(curl.isOpen).toBe(false) + } finally { + if (curl.isOpen) { + curl.close() + } + multi.close() + } + }) +}) diff --git a/test/curl/curly.spec.ts b/test/curl/curly.spec.ts index 3ee5707b..f885a025 100644 --- a/test/curl/curly.spec.ts +++ b/test/curl/curly.spec.ts @@ -18,6 +18,10 @@ describe('curly', () => { beforeAll(async () => { serverInstance = createServer() allMethodsWithMultipleReqResTypes(serverInstance.app) + serverInstance.app.get('/content-type-casing', (_req, res) => { + res.writeHead(200, { 'Content-Type': 'Application/JSON; charset=utf-8' }) + res.end('{"test": true}') + }) await serverInstance.listen() }) @@ -25,6 +29,7 @@ describe('curly', () => { await serverInstance.close() // beautiful is not it? serverInstance.app._router.stack.pop() + serverInstance.app._router.stack.pop() }) describe('common usage', () => { @@ -125,6 +130,16 @@ describe('curly', () => { expect(data).toHaveProperty('test', true) }) + it('matches content-types case-insensitively', async () => { + // media types are case-insensitive per RFC 7231 section 3.1.1.1 + const { statusCode, data } = await curly.get>( + `${serverInstance.url}/content-type-casing`, + ) + + expect(statusCode).toBe(200) + expect(data).toEqual({ test: true }) + }) + it('default content-type parsers work - *', async () => { const { statusCode, data } = await curly.get( `${serverInstance.url}/all?type=something`, @@ -165,6 +180,42 @@ describe('curly', () => { expect(req2.data).toBeInstanceOf(Buffer) }) + it('adds a parser for a content-type not covered by the defaults with the curlyResponseBodyParsers option', async () => { + const options = { + curlyResponseBodyParsers: { + 'application/something': (data: Buffer, header: any[]) => { + expect(data).toBeInstanceOf(Buffer) + expect(Array.isArray(header)).toBe(true) + + return 'something-parsed' + }, + }, + } + + const { statusCode, data } = await curly.get( + `${serverInstance.url}/all?type=something`, + options, + ) + expect(statusCode).toBe(200) + expect(data).toBe('something-parsed') + }) + + it('user supplied parsers have precedence over default wildcard parsers', async () => { + const options = { + curlyResponseBodyParsers: { + // the default text/* parser would also match this content-type + 'text/html': (_data: Buffer, _header: any[]) => 'html-parsed', + }, + } + + const { statusCode, data } = await curly.get( + `${serverInstance.url}/all`, + options, + ) + expect(statusCode).toBe(200) + expect(data).toBe('html-parsed') + }) + it('overrides all content-type parsers with the curlyResponseBodyParser option - json', async () => { const options = { curlyResponseBodyParser: (data: Buffer, header: any[]) => { @@ -248,16 +299,44 @@ describe('curly', () => { }) describe('error handling', () => { - it('throw error on invalid curlyProgressCallback', () => { + it('rejects with an error on invalid curlyProgressCallback', async () => { const options = { curlyProgressCallback: 'I should have been a function :)', } - expect(() => + await expect( curly // @ts-expect-error not assignable! .get(`${serverInstance.url}/all?type=json`, options), - ).toThrow(/^curlyProgressCallback must be a function/) + ).rejects.toThrow(/^curlyProgressCallback must be a function/) + }) + + it('rejects the promise (instead of throwing synchronously) when an invalid option is given', async () => { + let promise: Promise | null = null + + expect(() => { + promise = curly.get(`${serverInstance.url}/all`, { + // @ts-expect-error invalid option on purpose + thisOptionDoesNotExist: 'abc', + }) + }).not.toThrow() + + await expect(promise).rejects.toThrow(/Unknown option/) + }) + + it('rejects the promise (instead of throwing synchronously) when curlyProgressCallback is not a function', async () => { + let promise: Promise | null = null + + expect(() => { + promise = curly.get(`${serverInstance.url}/all`, { + // @ts-expect-error invalid value on purpose + curlyProgressCallback: 'not-a-function', + }) + }).not.toThrow() + + await expect(promise).rejects.toThrow( + /curlyProgressCallback must be a function/, + ) }) it('throw error on invalid response body parser in option curlyResponseBodyParsers', async () => { diff --git a/test/curl/dataParsing.spec.ts b/test/curl/dataParsing.spec.ts new file mode 100644 index 00000000..faf87f91 --- /dev/null +++ b/test/curl/dataParsing.spec.ts @@ -0,0 +1,87 @@ +/** + * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import { describe, beforeAll, afterAll, it, expect } from 'vitest' + +import { createServer } from '../helper/server' +import { Curl, HeaderInfo } from '../../lib' +import { withCommonTestOptions } from '../helper/commonOptions' + +let serverInstance: ReturnType + +// a body that ends in the middle of a multibyte UTF-8 character (truncated 🚀) +const truncatedUtf8Body = Buffer.concat([ + Buffer.from('hello '), + Buffer.from([0xf0, 0x9f]), +]) + +const performRequest = (handle: Curl) => + new Promise<{ + status: number + data: string | Buffer + headers: Buffer | HeaderInfo[] + }>((resolve, reject) => { + handle.once('end', (status, data, headers) => + resolve({ status, data, headers }), + ) + handle.once('error', (error) => reject(error)) + handle.perform() + }) + +describe('data parsing', () => { + beforeAll(async () => { + serverInstance = createServer() + serverInstance.app.get('/truncated-utf8', (_req, res) => { + res.set('Content-Type', 'application/octet-stream') + res.send(truncatedUtf8Body) + }) + await serverInstance.listen() + }) + + afterAll(async () => { + await serverInstance.close() + }) + + it('should not corrupt header parsing when the body ends mid UTF-8 character', async () => { + const curl = new Curl() + withCommonTestOptions(curl) + curl.setOpt('URL', serverInstance.path('/truncated-utf8')) + + try { + const { headers } = await performRequest(curl) + + expect(Array.isArray(headers)).toBe(true) + const headerGroups = headers as HeaderInfo[] + expect(headerGroups[0].result?.version).toBe('HTTP/1.1') + expect(headerGroups[0].result?.code).toBe(200) + } finally { + curl.close() + } + }) + + it('should not leak decoder state into other requests', async () => { + const firstCurl = new Curl() + withCommonTestOptions(firstCurl) + firstCurl.setOpt('URL', serverInstance.path('/truncated-utf8')) + + const secondCurl = new Curl() + withCommonTestOptions(secondCurl) + secondCurl.setOpt('URL', serverInstance.path('/truncated-utf8')) + + try { + const firstResponse = await performRequest(firstCurl) + const secondResponse = await performRequest(secondCurl) + + // each request must decode its own body independently: + // the truncated trailing bytes become a single replacement char + expect(firstResponse.data).toBe('hello �') + expect(secondResponse.data).toBe('hello �') + } finally { + firstCurl.close() + secondCurl.close() + } + }) +}) diff --git a/test/curl/dupHandle.spec.ts b/test/curl/dupHandle.spec.ts index 3963109b..ab59cd54 100644 --- a/test/curl/dupHandle.spec.ts +++ b/test/curl/dupHandle.spec.ts @@ -101,6 +101,10 @@ describe('dupHandle()', () => { }) }) + serverInstance.app.get('/ua', (req, res) => { + res.send(String(req.headers['user-agent'])) + }) + await serverInstance.listen() await fs.writeFile(imageFilename, buffer) }) @@ -110,6 +114,7 @@ describe('dupHandle()', () => { await serverInstance.close() serverInstance.app._router.stack.pop() serverInstance.app._router.stack.pop() + serverInstance.app._router.stack.pop() }) it('should correctly send HTTPPOST data when duplicated', async () => { @@ -145,6 +150,39 @@ describe('dupHandle()', () => { expect(parsedData.type).toBe(httpPostData[0].type) }) + it('should keep a custom USERAGENT set on the original handle', async () => { + const customUserAgent = 'my-custom-user-agent/1.0' + + curl.setOpt('URL', `${serverInstance.url}/ua`) + curl.setOpt('USERAGENT', customUserAgent) + + duplicatedCurl = curl.dupHandle() + + const result = await new Promise<{ status: number; data: string }>( + (resolve, reject) => { + duplicatedCurl.on('end', (status, data) => { + resolve({ status, data: data as string }) + }) + + duplicatedCurl.on('error', reject) + + duplicatedCurl.perform() + }, + ) + + expect(result.status).toBe(200) + expect(result.data).toBe(customUserAgent) + }) + + it('should copy the stream event listeners', () => { + curl.setOpt('URL', `${serverInstance.url}/ua`) + curl.on('stream', () => {}) + + duplicatedCurl = curl.dupHandle() + + expect(duplicatedCurl.listeners('stream')).toHaveLength(1) + }) + it('should correctly send POSTFIELDS data when duplicated', async () => { curl.setOpt('URL', `${serverInstance.url}/urlencoded`) curl.setOpt('POSTFIELDS', querystring.stringify(postFieldsData)) diff --git a/test/curl/easySafety.spec.ts b/test/curl/easySafety.spec.ts new file mode 100644 index 00000000..9913a0d3 --- /dev/null +++ b/test/curl/easySafety.spec.ts @@ -0,0 +1,250 @@ +/** + * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import { describe, beforeAll, afterAll, it, expect, inject, vi } from 'vitest' + +import { createServer } from '../helper/server' +import { + Curl, + CurlCode, + CurlHsts, + CurlHstsCallback, + CurlShareLock, + CurlShareOption, + Easy, + Share, +} from '../../lib' +import { withCommonTestOptions } from '../helper/commonOptions' + +let serverInstance: ReturnType + +describe('native layer regressions', () => { + beforeAll(async () => { + serverInstance = createServer() + serverInstance.app.get('/', (_req, res) => { + res.send('Hello World!') + }) + serverInstance.app.put('/upload', (_req, res) => { + res.send('ok') + }) + serverInstance.app.get('/echo-header', (req, res) => { + res.send(String(req.headers['x-test-header'])) + }) + serverInstance.app.post('/echo-body', (req, res) => { + // the urlencoded middleware already parsed the body - reconstruct it + res.send( + Object.entries(req.body as Record) + .map(([key, value]) => `${key}=${value}`) + .join('&'), + ) + }) + await serverInstance.listen() + }) + + afterAll(async () => { + await serverInstance.close() + }) + + describe('READFUNCTION buffer initialization', () => { + it('passes a zero-filled buffer to the callback', async () => { + const curl = new Curl() + withCommonTestOptions(curl) + curl.setOpt('URL', `${serverInstance.url}/upload`) + curl.setOpt('UPLOAD', true) + curl.setOpt('HTTPHEADER', ['Transfer-Encoding: chunked']) + + let bufferWasChecked = false + let bufferHadStaleData = false + curl.setOpt('READFUNCTION', (buffer) => { + if (!bufferWasChecked) { + bufferWasChecked = true + // the buffer must not leak previous heap contents into JS land + bufferHadStaleData = buffer.some((byte) => byte !== 0) + } + return 0 // empty upload + }) + + try { + await new Promise((resolve, reject) => { + curl.on('end', () => resolve()) + curl.on('error', reject) + curl.perform() + }) + + expect(bufferWasChecked).toBe(true) + expect(bufferHadStaleData).toBe(false) + } finally { + curl.close() + } + }) + }) + + describe('per-transfer state on reused handles', () => { + it('aborting via the progress callback does not poison the next transfer', () => { + const easy = new Easy() + withCommonTestOptions(easy) + // easy.perform() is synchronous and blocks the event loop, so the + // server handling the request must live in another process - the global + // setup server runs in the vitest main process, use that one + easy.setOpt('URL', inject('httpServerUrl')) + easy.setOpt('WRITEFUNCTION', (_buffer, size, nmemb) => size * nmemb) + easy.setOpt('NOPROGRESS', false) + + try { + easy.setOpt('XFERINFOFUNCTION', () => 1) // non-zero aborts the transfer + expect(easy.perform()).toBe(CurlCode.CURLE_ABORTED_BY_CALLBACK) + + // reusing the same handle (without reset()) is the standard libcurl + // pattern - the new progress callback must be invoked again + let secondTransferProgressCalls = 0 + easy.setOpt('XFERINFOFUNCTION', () => { + secondTransferProgressCalls += 1 + return 0 + }) + + expect(easy.perform()).toBe(CurlCode.CURLE_OK) + expect(secondTransferProgressCalls).toBeGreaterThan(0) + } finally { + easy.close() + } + }) + }) + + describe('share handle lifetime', () => { + it('closing a share that is still used by an easy handle throws instead of leaking', () => { + const share = new Share() + share.setOpt(CurlShareOption.SHARE, CurlShareLock.DataCookie) + + const easy = new Easy() + withCommonTestOptions(easy) + easy.setOpt('SHARE', share) + + try { + expect(() => share.close()).toThrow(/in use/i) + + // after unsetting the share it can be closed normally + easy.setOpt('SHARE', null) + expect(() => share.close()).not.toThrow() + } finally { + easy.close() + } + }) + + it('closing the easy handle releases the share', () => { + const share = new Share() + share.setOpt(CurlShareOption.SHARE, CurlShareLock.DataCookie) + + const easy = new Easy() + withCommonTestOptions(easy) + easy.setOpt('SHARE', share) + easy.close() + + expect(() => share.close()).not.toThrow() + }) + }) + + it('collects an Easy with an HSTS write callback', async () => { + let writes = 0 + let collected = false + const registry = new FinalizationRegistry(() => { + collected = true + }) + const performAndDrop = () => { + const easy = new Easy() + easy.setOpt('URL', inject('httpServerUrl')) + easy.setOpt('WRITEFUNCTION', (data) => data.length) + easy.setOpt('HSTS_CTRL', CurlHsts.Enable) + easy.setOpt('HSTSREADFUNCTION', () => [ + { host: 'example.test', includeSubDomains: false }, + ]) + easy.setOpt('HSTSWRITEFUNCTION', () => { + writes++ + return CurlHstsCallback.Ok + }) + expect(easy.perform()).toBe(CurlCode.CURLE_OK) + registry.register(easy, undefined) + } + + performAndDrop() + + await vi.waitFor(() => { + global.gc?.() + expect(collected).toBe(true) + }) + await new Promise((resolve) => setImmediate(resolve)) + expect(writes).toBe(0) + }) + + describe('option data replacement on reused handles', () => { + const performRequest = (curl: Curl) => + new Promise((resolve, reject) => { + curl.once('end', (_status, data) => resolve(data as string)) + curl.once('error', reject) + curl.perform() + }) + + it('uses the latest HTTPHEADER value after many replacements', async () => { + const curl = new Curl() + withCommonTestOptions(curl) + curl.setOpt('URL', `${serverInstance.url}/echo-header`) + + try { + // the previous lists are freed as they are replaced - if that freeing + // were premature, libcurl would read freed memory here + for (let i = 0; i <= 500; i += 1) { + curl.setOpt('HTTPHEADER', [`x-test-header: value-${i}`]) + } + + const data = await performRequest(curl) + expect(data).toBe('value-500') + } finally { + curl.close() + } + }) + + it('uses the latest POSTFIELDS value after many replacements', async () => { + const curl = new Curl() + withCommonTestOptions(curl) + curl.setOpt('URL', `${serverInstance.url}/echo-body`) + + try { + for (let i = 0; i <= 500; i += 1) { + curl.setOpt('POSTFIELDS', `field=value-${i}`) + } + + const data = await performRequest(curl) + expect(data).toBe('field=value-500') + } finally { + curl.close() + } + }) + + it('does not free data still used by a duplicated handle', async () => { + const curl = new Curl() + withCommonTestOptions(curl) + curl.setOpt('URL', `${serverInstance.url}/echo-body`) + curl.setOpt('POSTFIELDS', 'origin=first') + + const duplicated = curl.dupHandle(false) + + try { + // the storage is shared with the duplicated handle now - replacing + // the option must NOT free the previous buffer, the duplicated + // handle still points to it + curl.setOpt('POSTFIELDS', 'origin=replaced') + + const dataFromDuplicate = await performRequest(duplicated) + expect(dataFromDuplicate).toBe('origin=first') + + const dataFromOriginal = await performRequest(curl) + expect(dataFromOriginal).toBe('origin=replaced') + } finally { + duplicated.close() + curl.close() + } + }) + }) +}) diff --git a/test/curl/enumValues.spec.ts b/test/curl/enumValues.spec.ts new file mode 100644 index 00000000..43dbdd46 --- /dev/null +++ b/test/curl/enumValues.spec.ts @@ -0,0 +1,68 @@ +/** + * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import { describe, it, expect } from 'vitest' + +import { + Curl, + CurlAltSvc, + CurlFileType, + CurlFtpAuth, + CurlMultiNetworkChanged, + CurlSshKeyMatch, + CurlSshKeyType, + CurlVersion, +} from '../../lib' + +// these mirror the values in libcurl's curl.h / multi.h - they are part of +// the ABI contract, getting them wrong silently breaks user callbacks +describe('enum values match libcurl constants', () => { + it('CurlSshKeyType matches enum curl_khtype', () => { + expect(CurlSshKeyType.Unknown).toBe(0) + expect(CurlSshKeyType.Rsa1).toBe(1) + expect(CurlSshKeyType.Rsa).toBe(2) + expect(CurlSshKeyType.Dss).toBe(3) + expect(CurlSshKeyType.Ecdsa).toBe(4) + expect(CurlSshKeyType.Ed25519).toBe(5) + }) + + it('CurlSshKeyMatch matches enum curl_khmatch', () => { + expect(CurlSshKeyMatch.Ok).toBe(0) + expect(CurlSshKeyMatch.Mismatch).toBe(1) + expect(CurlSshKeyMatch.Missing).toBe(2) + }) + + it('CurlMultiNetworkChanged matches the CURLMNWC_* defines', () => { + expect(CurlMultiNetworkChanged.ClearAll).toBe(1 << 0) + const separateFlags = Curl.isVersionGreaterOrEqualThan(8, 20, 0) + expect(CurlMultiNetworkChanged.ClearConns).toBe(separateFlags ? 2 : 1) + expect(CurlMultiNetworkChanged.ClearDns).toBe(separateFlags ? 4 : 1) + }) + + it('CurlFileType matches enum curlfiletype', () => { + expect(CurlFileType.File).toBe(0) + expect(CurlFileType.Door).toBe(7) + expect(CurlFileType.Unknown).toBe(8) + }) + + it('CurlVersion contains the HSTS and THREADSAFE feature bits', () => { + expect(CurlVersion.Hsts).toBe(1 << 28) + expect(CurlVersion.ThreadSafe).toBe(1 << 30) + }) + + it('CurlAltSvc matches the CURLALTSVC_* defines', () => { + expect(CurlAltSvc.ReadonlyFile).toBe(1 << 2) + expect(CurlAltSvc.H1).toBe(1 << 3) + expect(CurlAltSvc.H2).toBe(1 << 4) + expect(CurlAltSvc.H3).toBe(1 << 5) + }) + + it('CurlFtpAuth matches the CURLFTPAUTH_* defines', () => { + expect(CurlFtpAuth.Default).toBe(0) + expect(CurlFtpAuth.Ssl).toBe(1) + expect(CurlFtpAuth.Tls).toBe(2) + }) +}) diff --git a/test/curl/getCount.spec.ts b/test/curl/getCount.spec.ts new file mode 100644 index 00000000..1d50fc57 --- /dev/null +++ b/test/curl/getCount.spec.ts @@ -0,0 +1,23 @@ +/** + * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import { describe, it, expect } from 'vitest' + +import { Curl } from '../../lib' + +describe('Curl.getCount()', () => { + it('should return the number of handles in the internal multi handle', () => { + expect(Curl.getCount()).toBe(0) + + const curl = new Curl() + try { + // not performing, so the handle is not inside the multi yet + expect(Curl.getCount()).toBe(0) + } finally { + curl.close() + } + }) +}) diff --git a/test/curl/hsts.spec.ts b/test/curl/hsts.spec.ts index 099e83b4..57a6937d 100644 --- a/test/curl/hsts.spec.ts +++ b/test/curl/hsts.spec.ts @@ -269,6 +269,36 @@ describe.runIf(Curl.isVersionGreaterOrEqualThan(7, 74, 0))('Callbacks', () => { }) }) + it('preserves hostnames with exactly maxHostLengthBytes characters', async () => { + curl.setOpt('HSTS_CTRL', CurlHsts.Enable) + // no network needed: the HSTS cache is loaded when the transfer starts + // (even if the connection fails) and saved when the handle is closed + curl.setOpt('URL', 'http://localhost:1/') + + let longHost = '' + curl.setOpt('HSTSREADFUNCTION', function (options) { + longHost = `${'a'.repeat(options.maxHostLengthBytes - 4)}.com` + return [{ host: longHost, includeSubDomains: false }] + }) + + const savedHosts: string[] = [] + curl.setOpt('HSTSWRITEFUNCTION', function (data) { + savedHosts.push(data.host) + return CurlHstsCallback.Ok + }) + + await new Promise((resolve) => { + curl.on('end', () => resolve()) + // the request itself fails (connection refused) - that is fine + curl.on('error', () => resolve()) + curl.perform() + }) + + curl.close() + + expect(savedHosts).toContain(longHost) + }) + it('returning invalid data from HSTSREADFUNCTION should throw an error', async () => { curl.setOpt('HSTS_CTRL', CurlHsts.Enable) diff --git a/test/curl/http2.spec.ts b/test/curl/http2.spec.ts index 8dbda34e..75fa7d4c 100644 --- a/test/curl/http2.spec.ts +++ b/test/curl/http2.spec.ts @@ -13,7 +13,7 @@ import { } from 'http2' import { createHttp2Server } from '../helper/server' -import { Curl, CurlHttpVersion } from '../../lib' +import { Curl, CurlHttpVersion, CurlPush, Easy, Multi } from '../../lib' import { withCommonTestOptions } from '../helper/commonOptions' type OnSessionFn = (session: ServerHttp2Session) => void @@ -23,14 +23,27 @@ type OnStreamFn = ( flags: number, ) => void -let session: ServerHttp2Session +const sessions = new Set() let serverInstance: ReturnType const onError = (error: Error) => console.error(error) const onSession: OnSessionFn = (_session) => { - session = _session + sessions.add(_session) + _session.once('close', () => sessions.delete(_session)) } -const onStream: OnStreamFn = (stream, _headers) => { +const onStream: OnStreamFn = (stream, headers) => { + if (headers[':path'] === '/push') { + stream.pushStream({ ':path': '/asset' }, (error, pushed) => { + if (!error) { + pushed.on('error', () => {}) + pushed.respond({ ':status': 200 }) + pushed.end('asset') + } + stream.respond({ ':status': 200 }) + stream.end('parent') + }) + return + } stream.respond({ 'content-type': 'text/html', ':status': 200, @@ -51,7 +64,7 @@ describe('HTTP2', () => { serverInstance.server.removeListener('error', onError) serverInstance.server.removeListener('session', onSession) serverInstance.server.removeListener('stream', onStream) - session?.destroy() + for (const session of sessions) session.destroy() await serverInstance.close() }) @@ -79,4 +92,66 @@ describe('HTTP2', () => { expect(result).toBe(200) }) + + it.runIf(Curl.isVersionGreaterOrEqualThan(8, 4, 0)).each([ + { accept: true, decision: 'accept' }, + { accept: false, decision: 'deny' }, + { accept: false, decision: 'throw while handling' }, + ])( + 'can $decision an HTTP/2 push', + async ({ accept, decision }) => { + const multi = new Multi() + const parent = new Easy() + withCommonTestOptions(parent) + parent.setOpt('URL', `${serverInstance.url}/push`) + parent.setOpt('HTTP_VERSION', CurlHttpVersion.V2_0) + parent.setOpt('SSL_VERIFYPEER', false) + let child: Easy | undefined + let path: string | null = null + let childBody = '' + + multi.setOpt('PUSHFUNCTION', (_parent, pushed, headers) => { + child = pushed + path = headers.getByName(':path') + if (decision === 'throw while handling') throw new Error('push refused') + if (!accept) return CurlPush.Deny + pushed.setOpt('WRITEFUNCTION', (data) => { + childBody += data.toString() + return data.length + }) + return CurlPush.Ok + }) + + try { + await new Promise((resolve, reject) => { + let completed = 0 + multi.onMessage((error, handle) => { + if (error) { + reject(error) + return + } + + try { + multi.removeHandle(handle) + completed++ + if (completed === (accept ? 2 : 1)) resolve() + } catch (removeError) { + reject(removeError) + } + }) + multi.addHandle(parent) + }) + + expect(path).toBe('/asset') + expect(child?.isOpen).toBe(accept) + expect(childBody).toBe(accept ? 'asset' : '') + expect(multi.getCount()).toBe(0) + } finally { + multi.close() + if (child?.isOpen) child.close() + parent.close() + } + }, + 5000, + ) }) diff --git a/test/curl/http2PushHeaders.spec.ts b/test/curl/http2PushHeaders.spec.ts new file mode 100644 index 00000000..f57bcad7 --- /dev/null +++ b/test/curl/http2PushHeaders.spec.ts @@ -0,0 +1,37 @@ +/** + * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import { execFileSync } from 'node:child_process' +import { join } from 'node:path' +import { expect, it } from 'vitest' + +import type { Http2PushFrameHeaders } from '../../lib/types/Http2PushFrameHeaders' + +it('rejects reads from an invalidated HTTP/2 push header wrapper', () => { + const fixture = join(__dirname, '../fixtures/push-headers') + execFileSync(process.execPath, [ + require.resolve('node-gyp/bin/node-gyp.js'), + 'rebuild', + '--directory', + fixture, + ]) + + const { + headers, + invalidate, + }: { + headers: Http2PushFrameHeaders + invalidate: (headers: Http2PushFrameHeaders) => void + } = require(join(fixture, 'build/Release/push_headers_fixture.node')) + + expect(headers.getByIndex(0)).toBe('x-test:example') + expect(headers.getByName('x-test')).toBe('example') + + invalidate(headers) + + expect(() => headers.getByIndex(0)).toThrow(/only valid during/i) + expect(() => headers.getByName('x-test')).toThrow(/only valid during/i) +}) diff --git a/test/curl/multi.spec.ts b/test/curl/multi.spec.ts new file mode 100644 index 00000000..e45e2a7d --- /dev/null +++ b/test/curl/multi.spec.ts @@ -0,0 +1,111 @@ +/** + * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import { executionAsyncResource } from 'async_hooks' +import { describe, beforeAll, afterAll, it, expect } from 'vitest' + +import { createServer } from '../helper/server' +import { Easy, Multi } from '../../lib' +import { withCommonTestOptions } from '../helper/commonOptions' + +let serverInstance: ReturnType + +const createEasy = () => { + const easy = new Easy() + withCommonTestOptions(easy) + easy.setOpt('URL', serverInstance.url) + easy.setOpt('WRITEFUNCTION', (_buf, size, nmemb) => size * nmemb) + return easy +} + +// Lets libuv run a few more iterations. If close() left sockets or timers in a +// bad state, the process crashes or this never resolves. +const pumpLoop = () => new Promise((resolve) => setTimeout(resolve, 50)) + +describe('Multi', () => { + beforeAll(async () => { + serverInstance = createServer() + serverInstance.app.get('/', (_req, res) => { + res.send('Hello World!') + }) + await serverInstance.listen() + }) + + afterAll(async () => { + await serverInstance.close() + serverInstance.app._router.stack.pop() + }) + + // With the notifications API (libcurl >= 8.17), onMessage runs inside + // libcurl's notify callback, that is, while curl_multi_socket_action is still + // on the stack. With polling it runs after curl_multi_socket_action returned. + // On libcurl < 8.17 both entries use polling. + describe.each([ + { name: 'notifications API', shouldUseNotificationsApi: true }, + { name: 'polling', shouldUseNotificationsApi: false }, + ])('close ($name)', ({ shouldUseNotificationsApi }) => { + // onMessage runs inside the callback scope opened when entering JS from + // libuv, and since Node.js 25 the async resource stack points into that + // scope's async context, so the context must outlive close(). Reading the + // stack used to return garbage or crash the process. + it('should keep the async resource valid when called from inside onMessage', async () => { + const { before, after } = await new Promise<{ + before: object + after: object + }>((resolve, reject) => { + const multi = new Multi({ shouldUseNotificationsApi }) + + multi.onMessage((error, handle) => { + const before = executionAsyncResource() + + multi.removeHandle(handle) + handle.close() + multi.close() + + if (error) { + reject(error) + return + } + + resolve({ before, after: executionAsyncResource() }) + }) + multi.addHandle(createEasy()) + }) + + expect(typeof before).toBe('object') + expect(after).toBe(before) + + await pumpLoop() + }) + + // libcurl rejects curl_multi_cleanup with CURLM_RECURSIVE_API_CALL while + // its own callbacks are running, which used to trip an assert in Dispose. + it('should not crash when called from inside an Easy callback', async () => { + const multi = new Multi({ shouldUseNotificationsApi }) + const easy = createEasy() + + let closed = false + + await new Promise((resolve) => { + easy.setOpt('WRITEFUNCTION', (_buf, size, nmemb) => { + if (!closed) { + closed = true + multi.close() + resolve() + } + return size * nmemb + }) + + multi.onMessage(() => {}) + multi.addHandle(easy) + }) + + await pumpLoop() + + expect(() => multi.close()).toThrow('Multi handle already closed.') + }) + }) +}) diff --git a/test/curl/multiLifecycle.spec.ts b/test/curl/multiLifecycle.spec.ts new file mode 100644 index 00000000..8caa912e --- /dev/null +++ b/test/curl/multiLifecycle.spec.ts @@ -0,0 +1,157 @@ +/** + * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import { describe, beforeAll, afterAll, it, expect } from 'vitest' + +import { createServer } from '../helper/server' +import { Easy, Multi } from '../../lib' +import { withCommonTestOptions } from '../helper/commonOptions' + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +let serverInstance: ReturnType + +const createEasy = (path = '/') => { + const easy = new Easy() + withCommonTestOptions(easy) + easy.setOpt('URL', `${serverInstance.url}${path}`) + easy.setOpt('WRITEFUNCTION', (_buffer, size, nmemb) => size * nmemb) + return easy +} + +describe('Multi lifecycle', () => { + beforeAll(async () => { + serverInstance = createServer() + serverInstance.app.get('/', (_req, res) => { + res.send('Hello World!') + }) + serverInstance.app.get('/delay', (_req, res) => { + setTimeout(() => res.send('finally!'), 1000) + }) + await serverInstance.listen() + }) + + afterAll(async () => { + await serverInstance.close() + }) + + it('rejects pending perform() promises when the multi is closed', async () => { + const multi = new Multi() + const easy = createEasy('/delay') + + const promise = multi.perform(easy) + // let the transfer actually start + await sleep(50) + + multi.close() + + await expect(promise).rejects.toThrow(/closed/i) + + // the easy must have been detached so it can be closed by the user + expect(easy.isInsideMultiHandle).toBe(false) + expect(() => easy.close()).not.toThrow() + + // give any stray socket events a chance to fire against the closed multi + await sleep(100) + }) + + it('settles the pending request when its easy handle is removed', async () => { + const multi = new Multi() + const easy = createEasy('/delay') + + try { + const request = multi.perform(easy) + const rejected = expect(request).rejects.toThrow(/removed/i) + multi.removeHandle(easy) + await rejected + + multi.removeHandle(easy) + expect(multi.getCount()).toBe(0) + expect(easy.isInsideMultiHandle).toBe(false) + } finally { + multi.close() + easy.close() + } + }) + + it('detaches handles added with addHandle() when the multi is closed', async () => { + const multi = new Multi() + const easy = createEasy('/delay') + + multi.onMessage(() => {}) + multi.addHandle(easy) + await sleep(50) + + multi.close() + + expect(easy.isInsideMultiHandle).toBe(false) + expect(() => easy.close()).not.toThrow() + + await sleep(100) + }) + + it('releases the multi instance after close() so it can be collected', async () => { + let multi: Multi | null = new Multi() + const weakRef = new WeakRef(multi) + + multi.close() + multi = null + + // The self reference is released from an async close callback, so give it + // a few event loop iterations before forcing garbage collection. + for (let i = 0; i < 5; i += 1) { + await sleep(10) + global.gc?.() + } + + expect(weakRef.deref()).toBeUndefined() + }) + + it('keeps a fire-and-forget easy alive until the transfer finishes', async () => { + const multi = new Multi() + + // no reference to the easy handle is kept by this scope + const promise = multi.perform(createEasy('/delay')) + + await sleep(50) + global.gc?.() + await sleep(50) + global.gc?.() + + const easy = await promise + expect(easy.isOpen).toBe(true) + + multi.removeHandle(easy) + easy.close() + multi.close() + }) + + it('supports removing and closing everything from inside the onMessage callback', async () => { + const multi = new Multi() + const easy = createEasy() + + await new Promise((resolve, reject) => { + multi.onMessage((error, handle) => { + try { + if (error) { + throw error + } + multi.removeHandle(handle) + handle.close() + multi.close() + resolve() + } catch (callbackError) { + reject(callbackError) + } + }) + + multi.addHandle(easy) + }) + + // give any stray socket events a chance to fire against the closed multi + await sleep(100) + }) +}) diff --git a/test/curl/newerOptions.spec.ts b/test/curl/newerOptions.spec.ts new file mode 100644 index 00000000..2d7ff43f --- /dev/null +++ b/test/curl/newerOptions.spec.ts @@ -0,0 +1,183 @@ +/** + * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import { describe, beforeAll, afterAll, it, expect } from 'vitest' + +import { createServer } from '../helper/server' +import { + Curl, + CurlAltSvc, + CurlCode, + CurlFtpAuth, + CurlFtpSsl, + CurlMimeOpt, + CurlWsOptions, + Easy, + Multi, +} from '../../lib' +import { withCommonTestOptions } from '../helper/commonOptions' + +let serverInstance: ReturnType + +describe('options from newer libcurl versions', () => { + beforeAll(async () => { + serverInstance = createServer() + serverInstance.app.get('/', (_req, res) => { + res.send('Hello World!') + }) + await serverInstance.listen() + }) + + afterAll(async () => { + await serverInstance.close() + }) + + describe.runIf(Curl.isVersionGreaterOrEqualThan(7, 86, 0))( + 'easy options', + () => { + it('accepts the string options', () => { + const easy = new Easy() + try { + expect(easy.setOpt('ABSTRACT_UNIX_SOCKET', '/tmp/test.sock')).toBe( + CurlCode.CURLE_OK, + ) + expect(easy.setOpt('ALTSVC', '/tmp/altsvc-cache.txt')).toBe( + CurlCode.CURLE_OK, + ) + expect( + easy.setOpt( + 'SSH_HOST_PUBLIC_KEY_SHA256', + 'NDVkMTQxMGQ4NTk3ZmY0YjVjMjI5OTc4NWMyY2RmMjE=', + ), + ).toBe(CurlCode.CURLE_OK) + } finally { + easy.close() + } + }) + + it('accepts the integer options', () => { + const easy = new Easy() + try { + expect( + easy.setOpt('ALTSVC_CTRL', CurlAltSvc.H1 | CurlAltSvc.H2), + ).toBe(CurlCode.CURLE_OK) + expect(easy.setOpt('FTPSSLAUTH', CurlFtpAuth.Tls)).toBe( + CurlCode.CURLE_OK, + ) + expect(easy.setOpt('FTP_SSL_CCC', CurlFtpSsl.CccPassive)).toBe( + CurlCode.CURLE_OK, + ) + expect(easy.setOpt('MIME_OPTIONS', CurlMimeOpt.FormEscape)).toBe( + CurlCode.CURLE_OK, + ) + expect(easy.setOpt('TFTP_NO_OPTIONS', true)).toBe(CurlCode.CURLE_OK) + expect(easy.setOpt('WS_OPTIONS', CurlWsOptions.RawMode)).toBe( + CurlCode.CURLE_OK, + ) + } finally { + easy.close() + } + }) + + it('accepts PROXY_ISSUERCERT_BLOB', () => { + const easy = new Easy() + try { + expect( + easy.setOpt('PROXY_ISSUERCERT_BLOB', Buffer.from('not-a-cert')), + ).toBe(CurlCode.CURLE_OK) + expect(easy.setOpt('PROXY_ISSUERCERT_BLOB', null)).toBe( + CurlCode.CURLE_OK, + ) + } finally { + easy.close() + } + }) + + it('accepts INTERLEAVEFUNCTION', () => { + const easy = new Easy() + try { + expect( + easy.setOpt('INTERLEAVEFUNCTION', (_data, size, nmemb) => { + return size * nmemb + }), + ).toBe(CurlCode.CURLE_OK) + expect(easy.setOpt('INTERLEAVEFUNCTION', null)).toBe( + CurlCode.CURLE_OK, + ) + } finally { + easy.close() + } + }) + + it('accepts SSH_HOSTKEYFUNCTION', () => { + const easy = new Easy() + try { + expect(easy.setOpt('SSH_HOSTKEYFUNCTION', () => 0)).toBe( + CurlCode.CURLE_OK, + ) + expect(easy.setOpt('SSH_HOSTKEYFUNCTION', null)).toBe( + CurlCode.CURLE_OK, + ) + } finally { + easy.close() + } + }) + + it('rejects the internally used _DATA options with a descriptive error', () => { + const easy = new Easy() + try { + for (const option of [ + 'HSTSREADDATA', + 'HSTSWRITEDATA', + 'PREREQDATA', + 'SSH_HOSTKEYDATA', + ]) { + expect(() => easy.setOpt(option as never, 1 as never)).toThrow( + /Unsupported option/, + ) + } + } finally { + easy.close() + } + }) + }, + ) + + describe.runIf(Curl.isVersionGreaterOrEqualThan(8, 20, 0))( + 'libcurl 8.20 additions', + () => { + it('exposes CURLINFO_SIZE_DELIVERED', async () => { + const curl = new Curl() + withCommonTestOptions(curl) + curl.setOpt('URL', serverInstance.url) + + try { + const sizeDelivered = await new Promise((resolve, reject) => { + curl.on('end', () => { + resolve(curl.getInfo('SIZE_DELIVERED') as number) + }) + curl.on('error', reject) + curl.perform() + }) + + expect(sizeDelivered).toBeGreaterThan(0) + } finally { + curl.close() + } + }) + + it('accepts the new multi options', () => { + const multi = new Multi() + try { + expect(multi.setOpt('QUICK_EXIT', 1)).toBe(0) + expect(multi.setOpt('RESOLVE_THREADS_MAX', 4)).toBe(0) + } finally { + multi.close() + } + }) + }, + ) +}) diff --git a/test/curl/parseHeaders.spec.ts b/test/curl/parseHeaders.spec.ts new file mode 100644 index 00000000..d1da2792 --- /dev/null +++ b/test/curl/parseHeaders.spec.ts @@ -0,0 +1,78 @@ +/** + * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import { describe, it, expect } from 'vitest' + +import { parseHeaders } from '../../lib/parseHeaders' + +const buildHeadersString = (lines: string[]) => + ['HTTP/1.1 200 OK', ...lines, '', ''].join('\r\n') + +describe('parseHeaders()', () => { + it('should parse the status line', () => { + const [headers] = parseHeaders(buildHeadersString(['Host: example.com'])) + + expect(headers.result).toEqual({ + version: 'HTTP/1.1', + code: 200, + reason: 'OK', + }) + }) + + it('should parse headers with a space after the colon', () => { + const [headers] = parseHeaders(buildHeadersString(['Host: example.com'])) + + expect(headers['Host']).toBe('example.com') + }) + + it('should parse headers without a space after the colon', () => { + const [headers] = parseHeaders(buildHeadersString(['Host:example.com'])) + + expect(headers['Host']).toBe('example.com') + }) + + it('should parse headers with an empty value', () => { + const [headers] = parseHeaders(buildHeadersString(['X-Empty:'])) + + expect(headers['X-Empty']).toBe('') + }) + + it('should keep colons inside the header value', () => { + const [headers] = parseHeaders( + buildHeadersString(['Location: http://example.com/path']), + ) + + expect(headers['Location']).toBe('http://example.com/path') + }) + + it('should parse Set-Cookie headers into an array', () => { + const [headers] = parseHeaders( + buildHeadersString(['Set-Cookie: a=b', 'Set-Cookie:c=d']), + ) + + expect(headers['Set-Cookie']).toEqual(['a=b', 'c=d']) + }) + + it('should parse multiple header groups (redirects)', () => { + const headersString = [ + 'HTTP/1.1 301 Moved Permanently', + 'Location: /new', + '', + 'HTTP/1.1 200 OK', + 'Content-Type: text/plain', + '', + '', + ].join('\r\n') + + const groups = parseHeaders(headersString) + + expect(groups).toHaveLength(2) + expect(groups[0].result?.code).toBe(301) + expect(groups[0]['Location']).toBe('/new') + expect(groups[1].result?.code).toBe(200) + expect(groups[1]['Content-Type']).toBe('text/plain') + }) +}) diff --git a/test/curl/reset.spec.ts b/test/curl/reset.spec.ts index fa91019e..e6c40a1e 100644 --- a/test/curl/reset.spec.ts +++ b/test/curl/reset.spec.ts @@ -4,10 +4,10 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ -import { describe, beforeAll, afterAll, it } from 'vitest' +import { describe, beforeAll, afterAll, it, expect } from 'vitest' import { createServer } from '../helper/server' -import { Curl, CurlCode } from '../../lib' +import { Curl, CurlCode, CurlFeature } from '../../lib' import { withCommonTestOptions } from '../helper/commonOptions' let firstRun = true @@ -70,3 +70,71 @@ describe('reset()', () => { await makeRequest() }) }) + +describe('reset() state restoration', () => { + let server: ReturnType + + const performRequest = (handle: Curl) => + new Promise<{ status: number; data: string | Buffer }>( + (resolve, reject) => { + handle.once('end', (status, data) => resolve({ status, data })) + handle.once('error', (error) => reject(error)) + handle.perform() + }, + ) + + beforeAll(async () => { + server = createServer() + server.app.get('/ua', (req, res) => { + res.send(String(req.headers['user-agent'])) + }) + await server.listen() + }) + + afterAll(async () => { + await server.close() + }) + + it('should clear enabled features', async () => { + const handle = new Curl() + withCommonTestOptions(handle) + handle.setOpt('URL', server.path('/ua')) + handle.enable(CurlFeature.Raw) + + try { + const firstResponse = await performRequest(handle) + expect(Buffer.isBuffer(firstResponse.data)).toBe(true) + + handle.reset() + withCommonTestOptions(handle) + handle.setOpt('URL', server.path('/ua')) + + // after reset the handle should be back to its initial state, + // which means data parsing is enabled again + const secondResponse = await performRequest(handle) + expect(typeof secondResponse.data).toBe('string') + } finally { + handle.close() + } + }) + + it('should restore the default USERAGENT', async () => { + const handle = new Curl() + withCommonTestOptions(handle) + handle.setOpt('URL', server.path('/ua')) + + try { + const firstResponse = await performRequest(handle) + expect(firstResponse.data).toContain('node-libcurl/') + + handle.reset() + withCommonTestOptions(handle) + handle.setOpt('URL', server.path('/ua')) + + const secondResponse = await performRequest(handle) + expect(secondResponse.data).toContain('node-libcurl/') + } finally { + handle.close() + } + }) +}) diff --git a/test/curl/streams.spec.ts b/test/curl/streams.spec.ts index fc87011c..0cdc6a02 100644 --- a/test/curl/streams.spec.ts +++ b/test/curl/streams.spec.ts @@ -4,12 +4,12 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ -import { describe, beforeAll, afterAll, it, expect } from 'vitest' +import { describe, beforeAll, afterAll, it, expect, vi } from 'vitest' import { Readable } from 'stream' import crypto from 'crypto' -import { Curl, CurlCode, CurlEasyError, curly } from '../../lib' +import { Curl, CurlCode, CurlEasyError, CurlFeature, curly } from '../../lib' import { createServer } from '../helper/server' import { allMethodsWithMultipleReqResTypes } from '../helper/commonRoutes' @@ -112,12 +112,18 @@ describe('streams', () => { putUploadBuffer: randomBuffer, }) + serverInstance.app.get('/big-payload', (_req, res) => { + res.set('Content-Type', 'application/octet-stream') + res.send(crypto.randomBytes(4 * 1024 * 1024)) + }) + await serverInstance.listen() }) afterAll(async () => { await serverInstance.close() serverInstance.app._router.stack.pop() + serverInstance.app._router.stack.pop() }) describe('curly', () => { @@ -490,6 +496,27 @@ describe('streams', () => { expect(streamUpload.listenerCount('end')).toBe(1) }) + it('removes the previous stream listeners when replacing the upload stream', () => { + const firstStream = getReadableStreamForBuffer(randomBuffer) + const secondStream = getReadableStreamForBuffer(randomBuffer) + + const curl = new Curl() + try { + curl.setUploadStream(firstStream) + expect(firstStream.listenerCount('end')).toBe(1) + + curl.setUploadStream(secondStream) + // the first stream must not influence the upload anymore - its + // end/error/close events would mutate the shared upload state + expect(firstStream.listenerCount('end')).toBe(0) + expect(firstStream.listenerCount('error')).toBe(0) + expect(firstStream.listenerCount('close')).toBe(0) + expect(secondStream.listenerCount('end')).toBe(1) + } finally { + curl.close() + } + }) + it('resets stream back to null after calling setUploadStream(null)', async () => { const streamUpload = getReadableStreamForBuffer(randomBuffer) @@ -501,5 +528,84 @@ describe('streams', () => { curl.setUploadStream(null) expect(streamUpload.listenerCount('end')).toBe(0) }) + + it('applies backpressure when the consumer is slower than the producer', async () => { + const highWaterMark = 16 * 1024 + + const curl = new Curl() + withCommonTestOptions(curl) + curl.setOpt('URL', `${serverInstance.url}/big-payload`) + curl.enable(CurlFeature.StreamResponse) + curl.setStreamResponseHighWaterMark(highWaterMark) + // force libcurl chunks to not align with the stream read sizes, which is + // what happens in the real world due to network fragmentation + curl.setOpt('BUFFERSIZE', 10000) + + let maxBuffered = 0 + let totalReceived = 0 + + try { + await new Promise((resolve, reject) => { + curl.on('stream', async (stream) => { + try { + for await (const chunk of stream) { + // reading from the stream drains everything buffered so far into + // a single chunk, so the chunk size shows how much data piled up + // inside the stream while the consumer was busy + maxBuffered = Math.max(maxBuffered, (chunk as Buffer).length) + totalReceived += (chunk as Buffer).length + // slow consumer + await sleep(1) + } + resolve() + } catch (error) { + reject(error) + } + }) + curl.on('error', reject) + curl.perform() + }) + + expect(totalReceived).toBe(4 * 1024 * 1024) + // if backpressure works, the amount buffered inside the response + // stream stays in the same order of magnitude as the highWaterMark. + // Without it the response body piles up in the stream buffer. + expect(maxBuffered).toBeLessThanOrEqual(highWaterMark * 8) + } finally { + curl.close() + } + }) + + it.each([true, false])( + 'restores NOPROGRESS=%s after a stream request', + async (noProgress) => { + const curl = new Curl() + withCommonTestOptions(curl) + curl.setOpt('URL', `${serverInstance.url}/all`) + curl.setOpt('NOPROGRESS', noProgress) + curl.enable(CurlFeature.StreamResponse) + const setOpt = vi.spyOn(curl.handle, 'setOpt') + + try { + await new Promise((resolve, reject) => { + curl.on('stream', (stream) => stream.resume()) + curl.on('end', () => resolve()) + curl.on('error', reject) + curl.perform() + }) + + const calls = setOpt.mock.calls.filter( + ([option]) => option === Curl.option.NOPROGRESS, + ) + expect(calls).toEqual([ + [Curl.option.NOPROGRESS, false], + [Curl.option.NOPROGRESS, noProgress], + ]) + } finally { + setOpt.mockRestore() + curl.close() + } + }, + ) }) }) diff --git a/test/fixtures/push-headers/binding.gyp b/test/fixtures/push-headers/binding.gyp new file mode 100644 index 00000000..973e7224 --- /dev/null +++ b/test/fixtures/push-headers/binding.gyp @@ -0,0 +1,16 @@ +{ + 'targets': [ + { + 'target_name': 'push_headers_fixture', + 'sources': ['fixture.cc', '../../../src/Http2PushFrameHeaders.cc'], + 'include_dirs': [ + ' + +struct curl_pushheaders { + char line[sizeof("x-test:example")] = "x-test:example"; +}; + +extern "C" char* curl_pushheader_bynum(curl_pushheaders* headers, size_t index) { + return headers && index == 0 ? headers->line : nullptr; +} + +extern "C" char* curl_pushheader_byname(curl_pushheaders* headers, const char* name) { + return headers && std::strcmp(name, "x-test") == 0 ? headers->line + sizeof("x-test") : nullptr; +} + +using NodeLibcurl::HTTP2_PUSH_FRAME_HEADERS_TYPE_TAG; +using NodeLibcurl::Http2PushFrameHeaders; + +Napi::Object Init(Napi::Env env, Napi::Object exports) { + auto constructor = Http2PushFrameHeaders::Init(env, exports); + // Keep the mock data alive for the whole test process, even after invalidation. + static curl_pushheaders headers; + auto external = Napi::External::New(env, &headers); + external.TypeTag(&HTTP2_PUSH_FRAME_HEADERS_TYPE_TAG); + exports.Set("headers", constructor.New({external, Napi::Number::New(env, 1)})); + exports.Set("invalidate", Napi::Function::New(env, [](const Napi::CallbackInfo& info) { + Http2PushFrameHeaders::Unwrap(info[0].As())->Invalidate(); + })); + return exports; +} + +NODE_API_MODULE(push_headers_fixture, Init) diff --git a/test/fixtures/push-headers/include/curl/curl.h b/test/fixtures/push-headers/include/curl/curl.h new file mode 100644 index 00000000..e43bf66b --- /dev/null +++ b/test/fixtures/push-headers/include/curl/curl.h @@ -0,0 +1,8 @@ +#pragma once + +#include + +// Only the two libcurl calls used by the production wrapper are stubbed. +struct curl_pushheaders; +extern "C" char* curl_pushheader_bynum(struct curl_pushheaders* headers, size_t index); +extern "C" char* curl_pushheader_byname(struct curl_pushheaders* headers, const char* name); diff --git a/vcpkg-configuration.json b/vcpkg-configuration.json index fc1c06a6..e89224b5 100644 --- a/vcpkg-configuration.json +++ b/vcpkg-configuration.json @@ -4,5 +4,13 @@ "repository": "https://github.com/microsoft/vcpkg", "baseline": "50c0cb48a0cf2f6fc5c7b2c0d2bafbe26d0a7ca2" }, + "registries": [ + { + "kind": "git", + "repository": "https://github.com/microsoft/vcpkg", + "baseline": "61d7eaeb094a6acbc23d9c2e54de9208175fda47", + "packages": ["brotli"] + } + ], "overlay-ports": ["./overlays"] }