aboutsummaryrefslogtreecommitdiffstats
path: root/host/commands/fetcher/curl_wrapper.cc
blob: 81865ff462e534b3a3eb11026f7fddec5b0589cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
//
// Copyright (C) 2019 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "host/commands/fetcher/curl_wrapper.h"

#include <stdio.h>

#include <mutex>
#include <sstream>
#include <string>

#include <android-base/logging.h>
#include <curl/curl.h>
#include <json/json.h>

namespace cuttlefish {
namespace {

size_t file_write_callback(char *ptr, size_t, size_t nmemb, void *userdata) {
  std::stringstream* stream = (std::stringstream*) userdata;
  stream->write(ptr, nmemb);
  return nmemb;
}

curl_slist* build_slist(const std::vector<std::string>& strings) {
  curl_slist* curl_headers = nullptr;
  for (const auto& str : strings) {
    curl_slist* temp = curl_slist_append(curl_headers, str.c_str());
    if (temp == nullptr) {
      LOG(ERROR) << "curl_slist_append failed to add " << str;
      if (curl_headers) {
        curl_slist_free_all(curl_headers);
        return nullptr;
      }
    }
    curl_headers = temp;
  }
  return curl_headers;
}

} // namespace

CurlWrapper::CurlWrapper() {
  curl_ = curl_easy_init();
  if (!curl_) {
    LOG(ERROR) << "failed to initialize curl";
    return;
  }
}

CurlWrapper::~CurlWrapper() { curl_easy_cleanup(curl_); }

CurlResponse<std::string> CurlWrapper::DownloadToFile(const std::string& url,
                                                      const std::string& path) {
  return CurlWrapper::DownloadToFile(url, path, {});
}

CurlResponse<std::string> CurlWrapper::DownloadToFile(
    const std::string& url, const std::string& path,
    const std::vector<std::string>& headers) {
  std::lock_guard<std::mutex> lock(mutex_);
  LOG(INFO) << "Attempting to save \"" << url << "\" to \"" << path << "\"";
  if (!curl_) {
    LOG(ERROR) << "curl_ was not initialized\n";
    return {"", -1};
  }
  curl_slist* curl_headers = build_slist(headers);
  curl_easy_reset(curl_);
  curl_easy_setopt(curl_, CURLOPT_CAINFO, "/etc/ssl/certs/ca-certificates.crt");
  curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, curl_headers);
  curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());
  char error_buf[CURL_ERROR_SIZE];
  curl_easy_setopt(curl_, CURLOPT_ERRORBUFFER, error_buf);
  curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1L);
  FILE* file = fopen(path.c_str(), "w");
  if (!file) {
    LOG(ERROR) << "could not open file " << path;
    return {"", -1};
  }
  curl_easy_setopt(curl_, CURLOPT_WRITEDATA, (void*)file);
  CURLcode res = curl_easy_perform(curl_);
  if (curl_headers) {
    curl_slist_free_all(curl_headers);
  }
  fclose(file);
  if (res != CURLE_OK) {
    LOG(ERROR) << "curl_easy_perform() failed. "
        << "Code was \"" << res << "\". "
        << "Strerror was \"" << curl_easy_strerror(res) << "\". "
        << "Error buffer was \"" << error_buf << "\".";
    return {"", -1};
  }
  long http_code = 0;
  curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &http_code);
  return {path, http_code};
}

CurlResponse<std::string> CurlWrapper::DownloadToString(
    const std::string& url) {
  return DownloadToString(url, {});
}

CurlResponse<std::string> CurlWrapper::DownloadToString(
    const std::string& url, const std::vector<std::string>& headers) {
  std::lock_guard<std::mutex> lock(mutex_);
  LOG(INFO) << "Attempting to download \"" << url << "\"";
  if (!curl_) {
    LOG(ERROR) << "curl was not initialized\n";
    return {"", -1};
  }
  curl_slist* curl_headers = build_slist(headers);
  curl_easy_reset(curl_);
  curl_easy_setopt(curl_, CURLOPT_CAINFO, "/etc/ssl/certs/ca-certificates.crt");
  curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, curl_headers);
  curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());
  std::stringstream data;
  curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, file_write_callback);
  curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &data);
  char error_buf[CURL_ERROR_SIZE];
  curl_easy_setopt(curl_, CURLOPT_ERRORBUFFER, error_buf);
  curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1L);
  CURLcode res = curl_easy_perform(curl_);
  if (curl_headers) {
    curl_slist_free_all(curl_headers);
  }
  if (res != CURLE_OK) {
    LOG(ERROR) << "curl_easy_perform() failed. "
        << "Code was \"" << res << "\". "
        << "Strerror was \"" << curl_easy_strerror(res) << "\". "
        << "Error buffer was \"" << error_buf << "\".";
    return {"", -1};
  }
  long http_code = 0;
  curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &http_code);
  return {data.str(), http_code};
}

CurlResponse<Json::Value> CurlWrapper::DownloadToJson(const std::string& url) {
  return DownloadToJson(url, {});
}

CurlResponse<Json::Value> CurlWrapper::DownloadToJson(
    const std::string& url, const std::vector<std::string>& headers) {
  CurlResponse<std::string> response = DownloadToString(url, headers);
  const std::string& contents = response.data;
  Json::CharReaderBuilder builder;
  std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
  Json::Value json;
  std::string errorMessage;
  if (!reader->parse(&*contents.begin(), &*contents.end(), &json, &errorMessage)) {
    LOG(ERROR) << "Could not parse json: " << errorMessage;
    json["error"] = "Failed to parse json.";
    json["response"] = contents;
  }
  return {json, response.http_code};
}
}