From 3d98e1682f45b59bad5337359a1c02289968a78f Mon Sep 17 00:00:00 2001
From: Xiaoling Bao <xiaolingbao@chromium.org>
Date: Sat, 12 Nov 2022 03:32:18 +0000
Subject: [PATCH] Ensure request buffer is available for WinHTTP.

Bug: 1383611
Change-Id: I5bd138a8b2e0c80de686f655e93bbfe254e3b1a6
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/4024532
Auto-Submit: Xiaoling Bao <xiaolingbao@chromium.org>
Reviewed-by: Sorin Jianu <sorin@chromium.org>
Commit-Queue: Sorin Jianu <sorin@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1070627}
---
 components/winhttp/network_fetcher.cc | 11 ++++++++---
 components/winhttp/network_fetcher.h  |  1 +
 2 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/components/winhttp/network_fetcher.cc b/components/winhttp/network_fetcher.cc
index 1ec77d9d0c46d..10b3922f2d9f2 100644
--- a/components/winhttp/network_fetcher.cc
+++ b/components/winhttp/network_fetcher.cc
@@ -267,9 +267,14 @@ HRESULT NetworkFetcher::SendRequest(const std::string& data) {
 
   VLOG(2) << data;
 
-  const uint32_t bytes_to_send = base::saturated_cast<uint32_t>(data.size());
-  void* request_body =
-      bytes_to_send ? const_cast<char*>(data.c_str()) : WINHTTP_NO_REQUEST_DATA;
+  // Make a copy of the request data to ensure the buffer is available until
+  // the request is processed.
+  request_data_ = data;
+
+  const uint32_t bytes_to_send =
+      base::saturated_cast<uint32_t>(request_data_.size());
+  void* request_body = bytes_to_send ? const_cast<char*>(request_data_.c_str())
+                                     : WINHTTP_NO_REQUEST_DATA;
   if (!::WinHttpSendRequest(request_handle_.get(),
                             WINHTTP_NO_ADDITIONAL_HEADERS, 0, request_body,
                             bytes_to_send, bytes_to_send, context())) {
diff --git a/components/winhttp/network_fetcher.h b/components/winhttp/network_fetcher.h
index db8fcc1ccdfa4..001a1350448ae 100644
--- a/components/winhttp/network_fetcher.h
+++ b/components/winhttp/network_fetcher.h
@@ -133,6 +133,7 @@ class NetworkFetcher : public base::RefCountedThreadSafe<NetworkFetcher> {
   std::string path_for_request_;
 
   base::WStringPiece verb_;
+  std::string request_data_;
   // The value of Content-Type header, e.g. "application/json".
   std::string content_type_;
   WriteDataCallback write_data_callback_;