Skip to content

curl_multi_socket_action() can wait indefinitely past CURLOPT_SERVER_RESPONSE_TIMEOUT #23025

Closed

Description

@qwaz

I did this

CURLOPT_SERVER_RESPONSE_TIMEOUT(_MS) is documented to wait no longer than the configured time for a response to a sent command, then fail the transfer. When an FTP, IMAP, POP3, or SMTP transfer is driven by curl_multi_socket_action(), it can instead wait indefinitely if the server keeps the connection open without replying.

The state machine in lib/pingpong.c calculates the remaining server response time, but checks it only when Curl_pp_statemach() runs. After a command is sent, no Curl_expire() call registers that wait with libcurl's timeout handling, so the remaining response time is not reflected in the timeout_ms value passed to the CURLMOPT_TIMERFUNCTION callback.

CURLOPT_TIMEOUT(_MS) still works because multistate_setup() schedules that timeout with Curl_expire_set().

The curl_easy_perform() path is unaffected for a different reason. Its easy_transfer() loop repeatedly calls curl_multi_poll(..., 1000) followed by curl_multi_perform(). This re-enters Curl_pp_statemach() about once per second even without file descriptor activity, so the elapsed server response timeout is detected on a later iteration.

The relevant control flow in lib/pingpong.c is:

  1. Curl_pp_vsendf() records the response start time in pp->response.
  2. Curl_pp_state_timeleft_ms() calculates the remaining response time.
  3. Each call to Curl_pp_statemach() checks whether that time has already elapsed. In nonblocking mode it checks the socket immediately and returns CURLE_OK if the socket is not ready.
  4. Curl_pp_statemach() does not call Curl_expire() before returning. Curl_pp_pollset() only requests socket input or output, so it does not schedule the server response timeout either.

CURLMOPT_TIMERFUNCTION exists for timeouts that require the application to call libcurl even when there is no file descriptor activity. With a silent peer, the reproducer's timer callback instead receives timeout_ms == -1, and curl_multi_timeout() also returns -1. The documented event-loop pattern therefore has neither file descriptor activity nor a libcurl timeout to process, and the transfer remains still_running.

Documentation and source references:

The reproducer sets CURLOPT_SERVER_RESPONSE_TIMEOUT_MS to 1000. silent_server.py sends a valid protocol greeting, receives the first command, and then keeps the TCP connection open without replying. sockact_client.c implements CURLMOPT_SOCKETFUNCTION and CURLMOPT_TIMERFUNCTION. The timer callback bridges libcurl's internal timeouts to the application's event loop: a nonnegative value installs a single non-repeating timer, and -1 cancels it. The three-second test limit ends the reproducer without calling CURL_SOCKET_TIMEOUT unless libcurl requested a timer.

The test used libcurl built from revision 39088cd295592ca6d4c5e687c75b400a67a87906, with the client linked directly to that build:

CURL_SRC=/path/to/curl
BUILD=/tmp/curl-build

cmake -S "$CURL_SRC" -B "$BUILD" -G Ninja \
  -DCMAKE_BUILD_TYPE=Debug \
  -DBUILD_SHARED_LIBS=ON \
  -DBUILD_STATIC_LIBS=OFF \
  -DBUILD_CURL_EXE=OFF \
  -DBUILD_EXAMPLES=OFF \
  -DBUILD_TESTING=OFF \
  -DCURL_ENABLE_SSL=OFF \
  -DCURL_DISABLE_LDAP=ON \
  -DCURL_DISABLE_LDAPS=ON \
  -DCURL_ZLIB=OFF \
  -DCURL_BROTLI=OFF \
  -DCURL_ZSTD=OFF \
  -DCURL_USE_LIBPSL=OFF \
  -DCURL_USE_LIBSSH2=OFF \
  -DCURL_USE_LIBSSH=OFF \
  -DCURL_USE_GSSAPI=OFF
cmake --build "$BUILD" --target libcurl_shared

cc -std=c11 -D_POSIX_C_SOURCE=200809L -O0 -g \
  -I"$CURL_SRC/include" sockact_client.c \
  "$BUILD/lib/libcurl-d.so" \
  -Wl,-rpath,"$BUILD/lib" \
  -o sockact_client

Start the POP3 server:

python3 silent_server.py pop3

Run the client with the URL printed by the server:

./sockact_client pop3://127.0.0.1:PORT

After receiving CAPA, the server sends no response. At the three-second test limit, the transfer is still active and libcurl has no timeout scheduled:

HANG still_running=1 last_timer=-1 multi_timeout=-1 elapsed=3000ms

The behavior is the same for every protocol whose nonblocking path calls Curl_pp_statemach():

Server command Protocol
python3 silent_server.py ftp FTP, after USER
python3 silent_server.py imap IMAP, after CAPABILITY
python3 silent_server.py pop3 POP3, after CAPA
python3 silent_server.py smtp SMTP, after EHLO
silent_server.py
#!/usr/bin/env python3
"""Send a protocol greeting, receive one command, then remain silent."""

import argparse
import socket
import time


PROTOCOLS = {
    "ftp": (b"220 FTP ready\r\n", b"USER"),
    "imap": (b"* OK IMAP ready\r\n", b"CAPABILITY"),
    "pop3": (b"+OK POP3 ready <test@localhost>\r\n", b"CAPA"),
    "smtp": (b"220 SMTP ready\r\n", b"EHLO"),
}


def url_for(protocol: str, port: int) -> str:
    if protocol == "ftp":
        return f"ftp://127.0.0.1:{port}/file"
    if protocol == "imap":
        return f"imap://127.0.0.1:{port}/"
    return f"{protocol}://127.0.0.1:{port}"


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Loopback server for the server-response timeout reproducer"
    )
    parser.add_argument("protocol", choices=PROTOCOLS)
    parser.add_argument(
        "--hold",
        type=float,
        default=6.0,
        help="seconds to keep the silent connection open (default: 6)",
    )
    args = parser.parse_args()

    greeting, expected_command = PROTOCOLS[args.protocol]

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
        listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        listener.bind(("127.0.0.1", 0))
        listener.listen(1)

        port = listener.getsockname()[1]
        print(f"URL {url_for(args.protocol, port)}", flush=True)
        print(f"WAITING_FOR {expected_command.decode()}", flush=True)

        conn, address = listener.accept()
        with conn:
            print(f"ACCEPT {address}", flush=True)
            conn.sendall(greeting)
            conn.settimeout(3.0)

            received = b""
            while expected_command not in received.upper():
                chunk = conn.recv(4096)
                if not chunk:
                    raise RuntimeError(
                        "client closed before sending the expected command"
                    )
                received += chunk

            print(f"RECV {received!r}", flush=True)
            print(f"SILENT_FOR {args.hold:.1f}s", flush=True)
            time.sleep(args.hold)


if __name__ == "__main__":
    main()
sockact_client.c
/*
 * Minimal curl_multi_socket_action() response-timeout reproducer.
 *
 * Usage: sockact_client URL [harness_ms] [overall_timeout_ms]
 */
#include <curl/curl.h>
#include <limits.h>
#include <poll.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct app {
  curl_socket_t fd;
  short events;
  bool timer_set;
  long last_timer_ms;
  long long timer_due_ms;
};

static long long now_ms(void)
{
  struct timespec ts;
  clock_gettime(CLOCK_MONOTONIC, &ts);
  return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}

static int timer_cb(CURLM *multi, long timeout_ms, void *userp)
{
  struct app *app = userp;
  (void)multi;

  /*
   * Bridge libcurl's internal timeouts to this poll-based event loop.
   * A timeout of -1 cancels the current timer.
   */
  app->last_timer_ms = timeout_ms;
  app->timer_set = timeout_ms >= 0;
  if(app->timer_set)
    app->timer_due_ms = now_ms() + timeout_ms;

  return 0;
}

static int socket_cb(CURL *easy, curl_socket_t fd, int what,
                     void *userp, void *socketp)
{
  struct app *app = userp;
  (void)easy;
  (void)socketp;

  if(what == CURL_POLL_REMOVE) {
    app->fd = CURL_SOCKET_BAD;
    app->events = 0;
    return 0;
  }

  app->fd = fd;
  app->events = 0;
  if(what & CURL_POLL_IN)
    app->events |= POLLIN;
  if(what & CURL_POLL_OUT)
    app->events |= POLLOUT;
  return 0;
}

static int run_action(CURLM *multi, curl_socket_t fd, int events,
                      int *still_running)
{
  CURLMcode result = curl_multi_socket_action(multi, fd, events,
                                               still_running);
  if(result != CURLM_OK) {
    fprintf(stderr, "curl_multi_socket_action: %s\n",
            curl_multi_strerror(result));
    return -1;
  }
  return 0;
}

int main(int argc, char **argv)
{
  struct app app = { CURL_SOCKET_BAD, 0, false, LONG_MIN, 0 };
  long harness_ms = 3000;
  long overall_timeout_ms = 0;
  long long started;
  CURL *easy;
  CURLM *multi;
  int still_running = 0;
  int exit_code = 0;

  if(argc < 2) {
    fprintf(stderr,
            "usage: %s URL [harness_ms] [overall_timeout_ms]\n", argv[0]);
    return 2;
  }
  if(argc > 2)
    harness_ms = strtol(argv[2], NULL, 10);
  if(argc > 3)
    overall_timeout_ms = strtol(argv[3], NULL, 10);

  if(curl_global_init(CURL_GLOBAL_DEFAULT))
    return 2;

  easy = curl_easy_init();
  multi = curl_multi_init();
  if(!easy || !multi) {
    curl_easy_cleanup(easy);
    curl_multi_cleanup(multi);
    curl_global_cleanup();
    return 2;
  }

  curl_easy_setopt(easy, CURLOPT_URL, argv[1]);
  curl_easy_setopt(easy, CURLOPT_SERVER_RESPONSE_TIMEOUT_MS, 1000L);
  if(overall_timeout_ms > 0)
    curl_easy_setopt(easy, CURLOPT_TIMEOUT_MS, overall_timeout_ms);

  curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, socket_cb);
  curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, &app);
  curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, timer_cb);
  curl_multi_setopt(multi, CURLMOPT_TIMERDATA, &app);
  if(curl_multi_add_handle(multi, easy) != CURLM_OK) {
    exit_code = 2;
    goto cleanup;
  }

  started = now_ms();
  if(run_action(multi, CURL_SOCKET_TIMEOUT, 0, &still_running)) {
    exit_code = 2;
    goto remove_handle;
  }

  while(still_running) {
    long long now = now_ms();
    long long harness_left = started + harness_ms - now;
    int wait_ms;
    int poll_result;

    if(harness_left <= 0)
      break;

    /*
     * The harness limit only bounds this demonstration. It must not call
     * CURL_SOCKET_TIMEOUT unless libcurl's timer callback requested one.
     */
    wait_ms = harness_left > INT_MAX ? INT_MAX : (int)harness_left;

    if(app.timer_set) {
      long long timer_left = app.timer_due_ms - now;
      if(timer_left < 0)
        timer_left = 0;
      if(timer_left < wait_ms)
        wait_ms = (int)timer_left;
    }

    if(app.fd == CURL_SOCKET_BAD)
      poll_result = poll(NULL, 0, wait_ms);
    else {
      struct pollfd pfd = { app.fd, app.events, 0 };
      poll_result = poll(&pfd, 1, wait_ms);
      if(poll_result > 0) {
        int events = 0;
        if(pfd.revents & POLLIN)
          events |= CURL_CSELECT_IN;
        if(pfd.revents & POLLOUT)
          events |= CURL_CSELECT_OUT;
        if(pfd.revents & (POLLERR | POLLHUP | POLLNVAL))
          events |= CURL_CSELECT_ERR;
        if(run_action(multi, app.fd, events, &still_running)) {
          exit_code = 2;
          goto remove_handle;
        }
      }
    }

    if(poll_result < 0) {
      perror("poll");
      exit_code = 2;
      goto remove_handle;
    }

    if(still_running && app.timer_set && now_ms() >= app.timer_due_ms) {
      app.timer_set = false;
      if(run_action(multi, CURL_SOCKET_TIMEOUT, 0, &still_running)) {
        exit_code = 2;
        goto remove_handle;
      }
    }
  }

  if(still_running) {
    long multi_timeout_ms = -2;

    /* Diagnostic only: the event loop above uses CURLMOPT_TIMERFUNCTION. */
    curl_multi_timeout(multi, &multi_timeout_ms);
    fprintf(stderr,
            "HANG still_running=1 last_timer=%ld multi_timeout=%ld "
            "elapsed=%lldms\n",
            app.last_timer_ms, multi_timeout_ms, now_ms() - started);
    exit_code = 1;
  }
  else {
    int messages_left = 0;
    CURLMsg *message;
    CURLcode result = CURLE_OK;

    while((message = curl_multi_info_read(multi, &messages_left))) {
      if(message->msg == CURLMSG_DONE) {
        result = message->data.result;
        break;
      }
    }
    fprintf(stderr, "DONE result=%d (%s) elapsed=%lldms\n",
            (int)result, curl_easy_strerror(result), now_ms() - started);
  }

remove_handle:
  curl_multi_remove_handle(multi, easy);
cleanup:
  curl_multi_cleanup(multi);
  curl_easy_cleanup(easy);
  curl_global_cleanup();
  return exit_code;
}

I expected the following

With CURLOPT_SERVER_RESPONSE_TIMEOUT_MS set to 1000, the transfer should fail with CURLE_OPERATION_TIMEDOUT after approximately one second without a server response, including when it is driven using the documented curl_multi_socket_action() event-loop pattern.

Following curl's vulnerability disclosure policy, this report is being filed in the public issue tracker rather than HackerOne. The policy states that curl does not consider "flaws that cause a transfer to never end" security problems.


Reporting on behalf of Microsoft FORGE Lab. This bug was initially discovered with an agentic code scanner; the author verified the finding and prepared this report.

curl/libcurl version

libcurl 8.23.0-DEV, commit 39088cd

operating system

Ubuntu 26.04 LTS (Resolute Raccoon)
Linux 6.6.114.1-microsoft-standard-WSL2 x86_64
gcc 15.2.0

Activity

  1. bagder commented on Sep 22, 2026

    @bagder
    Member

    @qwaz you up to providing a PR to fix this?

  2. karthik20066002 commented on Sep 26, 2026

    @karthik20066002

    Hey, do you mind if i take up this issue?

  3. qwaz commented on Sep 28, 2026

    @qwaz
    Author

    @bagder Hi, I was out of work last week because it was a thanksgiving in Korea. I'm back to work today.

    I'd be happy to try fixing it. I'm also happy to pass the issue to @karthik20066002.

    One thing I wanted to confirm with you is what's the best approach to change this behavior.

    1. Should the code call Curl_expire_set for CURLOPT_SERVER_RESPONSE_TIMEOUT? This is what CURLOPT_TIMEOUT uses. However, it introduces asymmetry with easy_transfer which relies on polling for the server response timeout.
    2. Should it use polling, similar to what easy_transfer is doing right now? If so, where the polling should happen, manually by the application's event loop or somehow internally inside libcurl?
  4. added a commit that references this issue on Oct 8, 2026
    b32baab
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions