How can I immediately cancel a curl operation? How can I immediately cancel a curl operation? curl curl

How can I immediately cancel a curl operation?


I met the same problem with curl 7.21.6. When tring to abort smtp protocol.Returning CURL_READFUNC_ABORT from read callback stops the transfer but curl_easy_perform does not return for next 5+ minutes. Probably it waits for tcp timeout.

To walk it around i store socket used by curl (replace curl_opensocket_callback), and close this socket directly when needed.

curl_socket_t storeCurlSocket(SOCKET *data, curlsocktype purpose, struct curl_sockaddr *addr) {    SOCKET sock = socket(addr->family, addr->socktype, addr->protocol);    *data = sock;    return sock;}size_t abort_payload(void *ptr, size_t size, size_t nmemb, SOCKET *curl_socket) {    SOCKET l_socket = INVALID_SOCKET;    swap(l_socket, *curl_socket);    if (l_socket != INVALID_SOCKET) {        shutdown(l_socket, SD_BOTH);        closesocket(l_socket);    }    return CURL_READFUNC_ABORT;}...calling perform...        SOCKET curlSocket;        curet = curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, storeCurlSocket);        curet = curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &curlSocket);        curet = curl_easy_setopt(curl, CURLOPT_READFUNCTION, abort_payload);        curet = curl_easy_setopt(curl, CURLOPT_READDATA, &curlSocket);        curet = curl_easy_perform(curl);        if (curet == CURLE_ABORTED_BY_CALLBACK) {          //expected abort        }...


Your basic idea is right. You should detach the curl operation from the UI. However, the implementation should be changed a bit. You shouldn't be using a global should_cancel. Instead, you should have a global current_request pointer, to an object of type Request. This type should have an internal cancel flag, and a public Cancel() function. In response to the cancel button, you call Cancel on the current_request and then null it. A cancelled request is then repsonsible for its own cleanup at a later time (it's a thread, after all).

You'll need to be careful with your mutexes to prevent zombie objects. There's an inherent race condition between a cancel and a request completion.


The delay could happens because curl_easy_perform is busy with the write or read callback, try to return 0 from the write callback or CURL_READFUNC_ABORT from the read callback. According with the documentation, if the value returned by the write callback differs from the value received by the function the transfer will be aborted, and if the read callback return CURL_READFUNC_ABORT, the transfer will be aborted too (valid from version 7.12.1 of the library).