1
0

download.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "gguf.h" // for reading GGUF splits
  4. #include "log.h"
  5. #include "download.h"
  6. #define JSON_ASSERT GGML_ASSERT
  7. #include <nlohmann/json.hpp>
  8. #include <algorithm>
  9. #include <filesystem>
  10. #include <fstream>
  11. #include <future>
  12. #include <regex>
  13. #include <string>
  14. #include <thread>
  15. #include <vector>
  16. #if defined(LLAMA_USE_CURL)
  17. #include <curl/curl.h>
  18. #include <curl/easy.h>
  19. #elif defined(LLAMA_USE_HTTPLIB)
  20. #include "http.h"
  21. #endif
  22. #ifdef __linux__
  23. #include <linux/limits.h>
  24. #elif defined(_WIN32)
  25. # if !defined(PATH_MAX)
  26. # define PATH_MAX MAX_PATH
  27. # endif
  28. #elif defined(_AIX)
  29. #include <sys/limits.h>
  30. #else
  31. #include <sys/syslimits.h>
  32. #endif
  33. #define LLAMA_MAX_URL_LENGTH 2084 // Maximum URL Length in Chrome: 2083
  34. // isatty
  35. #if defined(_WIN32)
  36. #include <io.h>
  37. #else
  38. #include <unistd.h>
  39. #endif
  40. using json = nlohmann::ordered_json;
  41. //
  42. // downloader
  43. //
  44. // validate repo name format: owner/repo
  45. static bool validate_repo_name(const std::string & repo) {
  46. static const std::regex repo_regex(R"(^[A-Za-z0-9_.\-]+\/[A-Za-z0-9_.\-]+$)");
  47. return std::regex_match(repo, repo_regex);
  48. }
  49. static std::string get_manifest_path(const std::string & repo, const std::string & tag) {
  50. // we use "=" to avoid clashing with other component, while still being allowed on windows
  51. std::string fname = "manifest=" + repo + "=" + tag + ".json";
  52. if (!validate_repo_name(repo)) {
  53. throw std::runtime_error("error: repo name must be in the format 'owner/repo'");
  54. }
  55. string_replace_all(fname, "/", "=");
  56. return fs_get_cache_file(fname);
  57. }
  58. static std::string read_file(const std::string & fname) {
  59. std::ifstream file(fname);
  60. if (!file) {
  61. throw std::runtime_error(string_format("error: failed to open file '%s'\n", fname.c_str()));
  62. }
  63. std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  64. file.close();
  65. return content;
  66. }
  67. static void write_file(const std::string & fname, const std::string & content) {
  68. const std::string fname_tmp = fname + ".tmp";
  69. std::ofstream file(fname_tmp);
  70. if (!file) {
  71. throw std::runtime_error(string_format("error: failed to open file '%s'\n", fname.c_str()));
  72. }
  73. try {
  74. file << content;
  75. file.close();
  76. // Makes write atomic
  77. if (rename(fname_tmp.c_str(), fname.c_str()) != 0) {
  78. LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, fname_tmp.c_str(), fname.c_str());
  79. // If rename fails, try to delete the temporary file
  80. if (remove(fname_tmp.c_str()) != 0) {
  81. LOG_ERR("%s: unable to delete temporary file: %s\n", __func__, fname_tmp.c_str());
  82. }
  83. }
  84. } catch (...) {
  85. // If anything fails, try to delete the temporary file
  86. if (remove(fname_tmp.c_str()) != 0) {
  87. LOG_ERR("%s: unable to delete temporary file: %s\n", __func__, fname_tmp.c_str());
  88. }
  89. throw std::runtime_error(string_format("error: failed to write file '%s'\n", fname.c_str()));
  90. }
  91. }
  92. static void write_etag(const std::string & path, const std::string & etag) {
  93. const std::string etag_path = path + ".etag";
  94. write_file(etag_path, etag);
  95. LOG_DBG("%s: file etag saved: %s\n", __func__, etag_path.c_str());
  96. }
  97. static std::string read_etag(const std::string & path) {
  98. std::string none;
  99. const std::string etag_path = path + ".etag";
  100. if (std::filesystem::exists(etag_path)) {
  101. std::ifstream etag_in(etag_path);
  102. if (!etag_in) {
  103. LOG_ERR("%s: could not open .etag file for reading: %s\n", __func__, etag_path.c_str());
  104. return none;
  105. }
  106. std::string etag;
  107. std::getline(etag_in, etag);
  108. return etag;
  109. }
  110. // no etag file, but maybe there is an old .json
  111. // remove this code later
  112. const std::string metadata_path = path + ".json";
  113. if (std::filesystem::exists(metadata_path)) {
  114. std::ifstream metadata_in(metadata_path);
  115. try {
  116. nlohmann::json metadata_json;
  117. metadata_in >> metadata_json;
  118. LOG_DBG("%s: previous metadata file found %s: %s\n", __func__, metadata_path.c_str(),
  119. metadata_json.dump().c_str());
  120. if (metadata_json.contains("etag") && metadata_json.at("etag").is_string()) {
  121. std::string etag = metadata_json.at("etag");
  122. write_etag(path, etag);
  123. if (!std::filesystem::remove(metadata_path)) {
  124. LOG_WRN("%s: failed to delete old .json metadata file: %s\n", __func__, metadata_path.c_str());
  125. }
  126. return etag;
  127. }
  128. } catch (const nlohmann::json::exception & e) {
  129. LOG_ERR("%s: error reading metadata file %s: %s\n", __func__, metadata_path.c_str(), e.what());
  130. }
  131. }
  132. return none;
  133. }
  134. #ifdef LLAMA_USE_CURL
  135. //
  136. // CURL utils
  137. //
  138. using curl_ptr = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>;
  139. // cannot use unique_ptr for curl_slist, because we cannot update without destroying the old one
  140. struct curl_slist_ptr {
  141. struct curl_slist * ptr = nullptr;
  142. ~curl_slist_ptr() {
  143. if (ptr) {
  144. curl_slist_free_all(ptr);
  145. }
  146. }
  147. };
  148. static CURLcode common_curl_perf(CURL * curl) {
  149. CURLcode res = curl_easy_perform(curl);
  150. if (res != CURLE_OK) {
  151. LOG_ERR("%s: curl_easy_perform() failed\n", __func__);
  152. }
  153. return res;
  154. }
  155. // Send a HEAD request to retrieve the etag and last-modified headers
  156. struct common_load_model_from_url_headers {
  157. std::string etag;
  158. std::string last_modified;
  159. std::string accept_ranges;
  160. };
  161. struct FILE_deleter {
  162. void operator()(FILE * f) const { fclose(f); }
  163. };
  164. static size_t common_header_callback(char * buffer, size_t, size_t n_items, void * userdata) {
  165. common_load_model_from_url_headers * headers = (common_load_model_from_url_headers *) userdata;
  166. static std::regex header_regex("([^:]+): (.*)\r\n");
  167. static std::regex etag_regex("ETag", std::regex_constants::icase);
  168. static std::regex last_modified_regex("Last-Modified", std::regex_constants::icase);
  169. static std::regex accept_ranges_regex("Accept-Ranges", std::regex_constants::icase);
  170. std::string header(buffer, n_items);
  171. std::smatch match;
  172. if (std::regex_match(header, match, header_regex)) {
  173. const std::string & key = match[1];
  174. const std::string & value = match[2];
  175. if (std::regex_match(key, match, etag_regex)) {
  176. headers->etag = value;
  177. } else if (std::regex_match(key, match, last_modified_regex)) {
  178. headers->last_modified = value;
  179. } else if (std::regex_match(key, match, accept_ranges_regex)) {
  180. headers->accept_ranges = value;
  181. }
  182. }
  183. return n_items;
  184. }
  185. static size_t common_write_callback(void * data, size_t size, size_t nmemb, void * fd) {
  186. return std::fwrite(data, size, nmemb, static_cast<FILE *>(fd));
  187. }
  188. // helper function to hide password in URL
  189. static std::string llama_download_hide_password_in_url(const std::string & url) {
  190. // Use regex to match and replace the user[:password]@ pattern in URLs
  191. // Pattern: scheme://[user[:password]@]host[...]
  192. static const std::regex url_regex(R"(^(?:[A-Za-z][A-Za-z0-9+.-]://)(?:[^/@]+@)?.$)");
  193. std::smatch match;
  194. if (std::regex_match(url, match, url_regex)) {
  195. // match[1] = scheme (e.g., "https://")
  196. // match[2] = user[:password]@ part
  197. // match[3] = rest of URL (host and path)
  198. return match[1].str() + "********@" + match[3].str();
  199. }
  200. return url; // No credentials found or malformed URL
  201. }
  202. static void common_curl_easy_setopt_head(CURL * curl, const std::string & url) {
  203. // Set the URL, allow to follow http redirection
  204. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  205. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  206. # if defined(_WIN32)
  207. // CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
  208. // operating system. Currently implemented under MS-Windows.
  209. curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  210. # endif
  211. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); // will trigger the HEAD verb
  212. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); // hide head request progress
  213. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, common_header_callback);
  214. }
  215. static void common_curl_easy_setopt_get(CURL * curl) {
  216. curl_easy_setopt(curl, CURLOPT_NOBODY, 0L);
  217. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, common_write_callback);
  218. // display download progress
  219. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  220. }
  221. static bool common_pull_file(CURL * curl, const std::string & path_temporary) {
  222. if (std::filesystem::exists(path_temporary)) {
  223. const std::string partial_size = std::to_string(std::filesystem::file_size(path_temporary));
  224. LOG_INF("%s: server supports range requests, resuming download from byte %s\n", __func__, partial_size.c_str());
  225. const std::string range_str = partial_size + "-";
  226. curl_easy_setopt(curl, CURLOPT_RANGE, range_str.c_str());
  227. }
  228. // Always open file in append mode could be resuming
  229. std::unique_ptr<FILE, FILE_deleter> outfile(fopen(path_temporary.c_str(), "ab"));
  230. if (!outfile) {
  231. LOG_ERR("%s: error opening local file for writing: %s\n", __func__, path_temporary.c_str());
  232. return false;
  233. }
  234. common_curl_easy_setopt_get(curl);
  235. curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile.get());
  236. return common_curl_perf(curl) == CURLE_OK;
  237. }
  238. static bool common_download_head(CURL * curl,
  239. curl_slist_ptr & http_headers,
  240. const std::string & url,
  241. const std::string & bearer_token) {
  242. if (!curl) {
  243. LOG_ERR("%s: error initializing libcurl\n", __func__);
  244. return false;
  245. }
  246. http_headers.ptr = curl_slist_append(http_headers.ptr, "User-Agent: llama-cpp");
  247. // Check if hf-token or bearer-token was specified
  248. if (!bearer_token.empty()) {
  249. std::string auth_header = "Authorization: Bearer " + bearer_token;
  250. http_headers.ptr = curl_slist_append(http_headers.ptr, auth_header.c_str());
  251. }
  252. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_headers.ptr);
  253. common_curl_easy_setopt_head(curl, url);
  254. return common_curl_perf(curl) == CURLE_OK;
  255. }
  256. // download one single file from remote URL to local path
  257. static bool common_download_file_single_online(const std::string & url,
  258. const std::string & path,
  259. const std::string & bearer_token) {
  260. static const int max_attempts = 3;
  261. static const int retry_delay_seconds = 2;
  262. for (int i = 0; i < max_attempts; ++i) {
  263. std::string etag;
  264. // Check if the file already exists locally
  265. const auto file_exists = std::filesystem::exists(path);
  266. if (file_exists) {
  267. etag = read_etag(path);
  268. } else {
  269. LOG_INF("%s: no previous model file found %s\n", __func__, path.c_str());
  270. }
  271. bool head_request_ok = false;
  272. bool should_download = !file_exists; // by default, we should download if the file does not exist
  273. // Initialize libcurl
  274. curl_ptr curl(curl_easy_init(), &curl_easy_cleanup);
  275. common_load_model_from_url_headers headers;
  276. curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &headers);
  277. curl_slist_ptr http_headers;
  278. const bool was_perform_successful = common_download_head(curl.get(), http_headers, url, bearer_token);
  279. if (!was_perform_successful) {
  280. head_request_ok = false;
  281. }
  282. long http_code = 0;
  283. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  284. if (http_code == 200) {
  285. head_request_ok = true;
  286. } else {
  287. LOG_WRN("%s: HEAD invalid http status code received: %ld\n", __func__, http_code);
  288. head_request_ok = false;
  289. }
  290. // if head_request_ok is false, we don't have the etag or last-modified headers
  291. // we leave should_download as-is, which is true if the file does not exist
  292. bool should_download_from_scratch = false;
  293. if (head_request_ok) {
  294. // check if ETag or Last-Modified headers are different
  295. // if it is, we need to download the file again
  296. if (!etag.empty() && etag != headers.etag) {
  297. LOG_WRN("%s: ETag header is different (%s != %s): triggering a new download\n", __func__, etag.c_str(),
  298. headers.etag.c_str());
  299. should_download = true;
  300. should_download_from_scratch = true;
  301. }
  302. }
  303. const bool accept_ranges_supported = !headers.accept_ranges.empty() && headers.accept_ranges != "none";
  304. if (should_download) {
  305. if (file_exists &&
  306. !accept_ranges_supported) { // Resumable downloads not supported, delete and start again.
  307. LOG_WRN("%s: deleting previous downloaded file: %s\n", __func__, path.c_str());
  308. if (remove(path.c_str()) != 0) {
  309. LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
  310. return false;
  311. }
  312. }
  313. const std::string path_temporary = path + ".downloadInProgress";
  314. if (should_download_from_scratch) {
  315. if (std::filesystem::exists(path_temporary)) {
  316. if (remove(path_temporary.c_str()) != 0) {
  317. LOG_ERR("%s: unable to delete file: %s\n", __func__, path_temporary.c_str());
  318. return false;
  319. }
  320. }
  321. if (std::filesystem::exists(path)) {
  322. if (remove(path.c_str()) != 0) {
  323. LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
  324. return false;
  325. }
  326. }
  327. }
  328. if (head_request_ok) {
  329. write_etag(path, headers.etag);
  330. }
  331. // start the download
  332. LOG_INF("%s: trying to download model from %s to %s (server_etag:%s, server_last_modified:%s)...\n",
  333. __func__, llama_download_hide_password_in_url(url).c_str(), path_temporary.c_str(),
  334. headers.etag.c_str(), headers.last_modified.c_str());
  335. const bool was_pull_successful = common_pull_file(curl.get(), path_temporary);
  336. if (!was_pull_successful) {
  337. if (i + 1 < max_attempts) {
  338. const int exponential_backoff_delay = std::pow(retry_delay_seconds, i) * 1000;
  339. LOG_WRN("%s: retrying after %d milliseconds...\n", __func__, exponential_backoff_delay);
  340. std::this_thread::sleep_for(std::chrono::milliseconds(exponential_backoff_delay));
  341. } else {
  342. LOG_ERR("%s: curl_easy_perform() failed after %d attempts\n", __func__, max_attempts);
  343. }
  344. continue;
  345. }
  346. long http_code = 0;
  347. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  348. if (http_code < 200 || http_code >= 400) {
  349. LOG_ERR("%s: invalid http status code received: %ld\n", __func__, http_code);
  350. return false;
  351. }
  352. if (rename(path_temporary.c_str(), path.c_str()) != 0) {
  353. LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, path_temporary.c_str(), path.c_str());
  354. return false;
  355. }
  356. } else {
  357. LOG_INF("%s: using cached file: %s\n", __func__, path.c_str());
  358. }
  359. break;
  360. }
  361. return true;
  362. }
  363. std::pair<long, std::vector<char>> common_remote_get_content(const std::string & url, const common_remote_params & params) {
  364. curl_ptr curl(curl_easy_init(), &curl_easy_cleanup);
  365. curl_slist_ptr http_headers;
  366. std::vector<char> res_buffer;
  367. curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
  368. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L);
  369. curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
  370. curl_easy_setopt(curl.get(), CURLOPT_VERBOSE, 1L);
  371. typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * ptr, size_t size, size_t nmemb, void * data);
  372. auto write_callback = [](void * ptr, size_t size, size_t nmemb, void * data) -> size_t {
  373. auto data_vec = static_cast<std::vector<char> *>(data);
  374. data_vec->insert(data_vec->end(), (char *)ptr, (char *)ptr + size * nmemb);
  375. return size * nmemb;
  376. };
  377. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
  378. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &res_buffer);
  379. #if defined(_WIN32)
  380. curl_easy_setopt(curl.get(), CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  381. #endif
  382. if (params.timeout > 0) {
  383. curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, params.timeout);
  384. }
  385. if (params.max_size > 0) {
  386. curl_easy_setopt(curl.get(), CURLOPT_MAXFILESIZE, params.max_size);
  387. }
  388. http_headers.ptr = curl_slist_append(http_headers.ptr, "User-Agent: llama-cpp");
  389. for (const auto & header : params.headers) {
  390. http_headers.ptr = curl_slist_append(http_headers.ptr, header.c_str());
  391. }
  392. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, http_headers.ptr);
  393. CURLcode res = curl_easy_perform(curl.get());
  394. if (res != CURLE_OK) {
  395. std::string error_msg = curl_easy_strerror(res);
  396. throw std::runtime_error("error: cannot make GET request: " + error_msg);
  397. }
  398. long res_code;
  399. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &res_code);
  400. return { res_code, std::move(res_buffer) };
  401. }
  402. #elif defined(LLAMA_USE_HTTPLIB)
  403. static bool is_output_a_tty() {
  404. #if defined(_WIN32)
  405. return _isatty(_fileno(stdout));
  406. #else
  407. return isatty(1);
  408. #endif
  409. }
  410. static void print_progress(size_t current, size_t total) {
  411. if (!is_output_a_tty()) {
  412. return;
  413. }
  414. if (!total) {
  415. return;
  416. }
  417. size_t width = 50;
  418. size_t pct = (100 * current) / total;
  419. size_t pos = (width * current) / total;
  420. std::cout << "["
  421. << std::string(pos, '=')
  422. << (pos < width ? ">" : "")
  423. << std::string(width - pos, ' ')
  424. << "] " << std::setw(3) << pct << "% ("
  425. << current / (1024 * 1024) << " MB / "
  426. << total / (1024 * 1024) << " MB)\r";
  427. std::cout.flush();
  428. }
  429. static bool common_pull_file(httplib::Client & cli,
  430. const std::string & resolve_path,
  431. const std::string & path_tmp,
  432. bool supports_ranges,
  433. size_t existing_size,
  434. size_t & total_size) {
  435. std::ofstream ofs(path_tmp, std::ios::binary | std::ios::app);
  436. if (!ofs.is_open()) {
  437. LOG_ERR("%s: error opening local file for writing: %s\n", __func__, path_tmp.c_str());
  438. return false;
  439. }
  440. httplib::Headers headers;
  441. if (supports_ranges && existing_size > 0) {
  442. headers.emplace("Range", "bytes=" + std::to_string(existing_size) + "-");
  443. }
  444. const char * func = __func__; // avoid __func__ inside a lambda
  445. size_t downloaded = existing_size;
  446. size_t progress_step = 0;
  447. auto res = cli.Get(resolve_path, headers,
  448. [&](const httplib::Response &response) {
  449. if (existing_size > 0 && response.status != 206) {
  450. LOG_WRN("%s: server did not respond with 206 Partial Content for a resume request. Status: %d\n", func, response.status);
  451. return false;
  452. }
  453. if (existing_size == 0 && response.status != 200) {
  454. LOG_WRN("%s: download received non-successful status code: %d\n", func, response.status);
  455. return false;
  456. }
  457. if (total_size == 0 && response.has_header("Content-Length")) {
  458. try {
  459. size_t content_length = std::stoull(response.get_header_value("Content-Length"));
  460. total_size = existing_size + content_length;
  461. } catch (const std::exception &e) {
  462. LOG_WRN("%s: invalid Content-Length header: %s\n", func, e.what());
  463. }
  464. }
  465. return true;
  466. },
  467. [&](const char *data, size_t len) {
  468. ofs.write(data, len);
  469. if (!ofs) {
  470. LOG_ERR("%s: error writing to file: %s\n", func, path_tmp.c_str());
  471. return false;
  472. }
  473. downloaded += len;
  474. progress_step += len;
  475. if (progress_step >= total_size / 1000 || downloaded == total_size) {
  476. print_progress(downloaded, total_size);
  477. progress_step = 0;
  478. }
  479. return true;
  480. },
  481. nullptr
  482. );
  483. std::cout << "\n";
  484. if (!res) {
  485. LOG_ERR("%s: error during download. Status: %d\n", __func__, res ? res->status : -1);
  486. return false;
  487. }
  488. return true;
  489. }
  490. // download one single file from remote URL to local path
  491. static bool common_download_file_single_online(const std::string & url,
  492. const std::string & path,
  493. const std::string & bearer_token) {
  494. static const int max_attempts = 3;
  495. static const int retry_delay_seconds = 2;
  496. auto [cli, parts] = common_http_client(url);
  497. httplib::Headers default_headers = {{"User-Agent", "llama-cpp"}};
  498. if (!bearer_token.empty()) {
  499. default_headers.insert({"Authorization", "Bearer " + bearer_token});
  500. }
  501. cli.set_default_headers(default_headers);
  502. const bool file_exists = std::filesystem::exists(path);
  503. std::string last_etag;
  504. if (file_exists) {
  505. last_etag = read_etag(path);
  506. } else {
  507. LOG_INF("%s: no previous model file found %s\n", __func__, path.c_str());
  508. }
  509. for (int i = 0; i < max_attempts; ++i) {
  510. auto head = cli.Head(parts.path);
  511. bool head_ok = head && head->status >= 200 && head->status < 300;
  512. if (!head_ok) {
  513. LOG_WRN("%s: HEAD invalid http status code received: %d\n", __func__, head ? head->status : -1);
  514. if (file_exists) {
  515. LOG_INF("%s: Using cached file (HEAD failed): %s\n", __func__, path.c_str());
  516. return true;
  517. }
  518. }
  519. std::string etag;
  520. if (head_ok && head->has_header("ETag")) {
  521. etag = head->get_header_value("ETag");
  522. }
  523. size_t total_size = 0;
  524. if (head_ok && head->has_header("Content-Length")) {
  525. try {
  526. total_size = std::stoull(head->get_header_value("Content-Length"));
  527. } catch (const std::exception& e) {
  528. LOG_WRN("%s: Invalid Content-Length in HEAD response: %s\n", __func__, e.what());
  529. }
  530. }
  531. bool supports_ranges = false;
  532. if (head_ok && head->has_header("Accept-Ranges")) {
  533. supports_ranges = head->get_header_value("Accept-Ranges") != "none";
  534. }
  535. bool should_download_from_scratch = false;
  536. if (!last_etag.empty() && !etag.empty() && last_etag != etag) {
  537. LOG_WRN("%s: ETag header is different (%s != %s): triggering a new download\n", __func__,
  538. last_etag.c_str(), etag.c_str());
  539. should_download_from_scratch = true;
  540. }
  541. if (file_exists) {
  542. if (!should_download_from_scratch) {
  543. LOG_INF("%s: using cached file: %s\n", __func__, path.c_str());
  544. return true;
  545. }
  546. LOG_WRN("%s: deleting previous downloaded file: %s\n", __func__, path.c_str());
  547. if (remove(path.c_str()) != 0) {
  548. LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
  549. return false;
  550. }
  551. }
  552. const std::string path_temporary = path + ".downloadInProgress";
  553. size_t existing_size = 0;
  554. if (std::filesystem::exists(path_temporary)) {
  555. if (supports_ranges && !should_download_from_scratch) {
  556. existing_size = std::filesystem::file_size(path_temporary);
  557. } else if (remove(path_temporary.c_str()) != 0) {
  558. LOG_ERR("%s: unable to delete file: %s\n", __func__, path_temporary.c_str());
  559. return false;
  560. }
  561. }
  562. // start the download
  563. LOG_INF("%s: trying to download model from %s to %s (etag:%s)...\n",
  564. __func__, common_http_show_masked_url(parts).c_str(), path_temporary.c_str(), etag.c_str());
  565. const bool was_pull_successful = common_pull_file(cli, parts.path, path_temporary, supports_ranges, existing_size, total_size);
  566. if (!was_pull_successful) {
  567. if (i + 1 < max_attempts) {
  568. const int exponential_backoff_delay = std::pow(retry_delay_seconds, i) * 1000;
  569. LOG_WRN("%s: retrying after %d milliseconds...\n", __func__, exponential_backoff_delay);
  570. std::this_thread::sleep_for(std::chrono::milliseconds(exponential_backoff_delay));
  571. } else {
  572. LOG_ERR("%s: download failed after %d attempts\n", __func__, max_attempts);
  573. }
  574. continue;
  575. }
  576. if (std::rename(path_temporary.c_str(), path.c_str()) != 0) {
  577. LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, path_temporary.c_str(), path.c_str());
  578. return false;
  579. }
  580. if (!etag.empty()) {
  581. write_etag(path, etag);
  582. }
  583. break;
  584. }
  585. return true;
  586. }
  587. std::pair<long, std::vector<char>> common_remote_get_content(const std::string & url,
  588. const common_remote_params & params) {
  589. auto [cli, parts] = common_http_client(url);
  590. httplib::Headers headers = {{"User-Agent", "llama-cpp"}};
  591. for (const auto & header : params.headers) {
  592. size_t pos = header.find(':');
  593. if (pos != std::string::npos) {
  594. headers.emplace(header.substr(0, pos), header.substr(pos + 1));
  595. } else {
  596. headers.emplace(header, "");
  597. }
  598. }
  599. if (params.timeout > 0) {
  600. cli.set_read_timeout(params.timeout, 0);
  601. cli.set_write_timeout(params.timeout, 0);
  602. }
  603. std::vector<char> buf;
  604. auto res = cli.Get(parts.path, headers,
  605. [&](const char *data, size_t len) {
  606. buf.insert(buf.end(), data, data + len);
  607. return params.max_size == 0 ||
  608. buf.size() <= static_cast<size_t>(params.max_size);
  609. },
  610. nullptr
  611. );
  612. if (!res) {
  613. throw std::runtime_error("error: cannot make GET request");
  614. }
  615. return { res->status, std::move(buf) };
  616. }
  617. #endif // LLAMA_USE_CURL
  618. #if defined(LLAMA_USE_CURL) || defined(LLAMA_USE_HTTPLIB)
  619. static bool common_download_file_single(const std::string & url,
  620. const std::string & path,
  621. const std::string & bearer_token,
  622. bool offline) {
  623. if (!offline) {
  624. return common_download_file_single_online(url, path, bearer_token);
  625. }
  626. if (!std::filesystem::exists(path)) {
  627. LOG_ERR("%s: required file is not available in cache (offline mode): %s\n", __func__, path.c_str());
  628. return false;
  629. }
  630. LOG_INF("%s: using cached file (offline mode): %s\n", __func__, path.c_str());
  631. return true;
  632. }
  633. // download multiple files from remote URLs to local paths
  634. // the input is a vector of pairs <url, path>
  635. static bool common_download_file_multiple(const std::vector<std::pair<std::string, std::string>> & urls, const std::string & bearer_token, bool offline) {
  636. // Prepare download in parallel
  637. std::vector<std::future<bool>> futures_download;
  638. for (auto const & item : urls) {
  639. futures_download.push_back(std::async(std::launch::async, [bearer_token, offline](const std::pair<std::string, std::string> & it) -> bool {
  640. return common_download_file_single(it.first, it.second, bearer_token, offline);
  641. }, item));
  642. }
  643. // Wait for all downloads to complete
  644. for (auto & f : futures_download) {
  645. if (!f.get()) {
  646. return false;
  647. }
  648. }
  649. return true;
  650. }
  651. bool common_download_model(
  652. const common_params_model & model,
  653. const std::string & bearer_token,
  654. bool offline) {
  655. // Basic validation of the model.url
  656. if (model.url.empty()) {
  657. LOG_ERR("%s: invalid model url\n", __func__);
  658. return false;
  659. }
  660. if (!common_download_file_single(model.url, model.path, bearer_token, offline)) {
  661. return false;
  662. }
  663. // check for additional GGUFs split to download
  664. int n_split = 0;
  665. {
  666. struct gguf_init_params gguf_params = {
  667. /*.no_alloc = */ true,
  668. /*.ctx = */ NULL,
  669. };
  670. auto * ctx_gguf = gguf_init_from_file(model.path.c_str(), gguf_params);
  671. if (!ctx_gguf) {
  672. LOG_ERR("\n%s: failed to load input GGUF from %s\n", __func__, model.path.c_str());
  673. return false;
  674. }
  675. auto key_n_split = gguf_find_key(ctx_gguf, LLM_KV_SPLIT_COUNT);
  676. if (key_n_split >= 0) {
  677. n_split = gguf_get_val_u16(ctx_gguf, key_n_split);
  678. }
  679. gguf_free(ctx_gguf);
  680. }
  681. if (n_split > 1) {
  682. char split_prefix[PATH_MAX] = {0};
  683. char split_url_prefix[LLAMA_MAX_URL_LENGTH] = {0};
  684. // Verify the first split file format
  685. // and extract split URL and PATH prefixes
  686. {
  687. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), model.path.c_str(), 0, n_split)) {
  688. LOG_ERR("\n%s: unexpected model file name: %s n_split=%d\n", __func__, model.path.c_str(), n_split);
  689. return false;
  690. }
  691. if (!llama_split_prefix(split_url_prefix, sizeof(split_url_prefix), model.url.c_str(), 0, n_split)) {
  692. LOG_ERR("\n%s: unexpected model url: %s n_split=%d\n", __func__, model.url.c_str(), n_split);
  693. return false;
  694. }
  695. }
  696. std::vector<std::pair<std::string, std::string>> urls;
  697. for (int idx = 1; idx < n_split; idx++) {
  698. char split_path[PATH_MAX] = {0};
  699. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  700. char split_url[LLAMA_MAX_URL_LENGTH] = {0};
  701. llama_split_path(split_url, sizeof(split_url), split_url_prefix, idx, n_split);
  702. if (std::string(split_path) == model.path) {
  703. continue; // skip the already downloaded file
  704. }
  705. urls.push_back({split_url, split_path});
  706. }
  707. // Download in parallel
  708. common_download_file_multiple(urls, bearer_token, offline);
  709. }
  710. return true;
  711. }
  712. common_hf_file_res common_get_hf_file(const std::string & hf_repo_with_tag, const std::string & bearer_token, bool offline) {
  713. auto parts = string_split<std::string>(hf_repo_with_tag, ':');
  714. std::string tag = parts.size() > 1 ? parts.back() : "latest";
  715. std::string hf_repo = parts[0];
  716. if (string_split<std::string>(hf_repo, '/').size() != 2) {
  717. throw std::invalid_argument("error: invalid HF repo format, expected <user>/<model>[:quant]\n");
  718. }
  719. std::string url = get_model_endpoint() + "v2/" + hf_repo + "/manifests/" + tag;
  720. // headers
  721. std::vector<std::string> headers;
  722. headers.push_back("Accept: application/json");
  723. if (!bearer_token.empty()) {
  724. headers.push_back("Authorization: Bearer " + bearer_token);
  725. }
  726. // Important: the User-Agent must be "llama-cpp" to get the "ggufFile" field in the response
  727. // User-Agent header is already set in common_remote_get_content, no need to set it here
  728. // make the request
  729. common_remote_params params;
  730. params.headers = headers;
  731. long res_code = 0;
  732. std::string res_str;
  733. bool use_cache = false;
  734. std::string cached_response_path = get_manifest_path(hf_repo, tag);
  735. if (!offline) {
  736. try {
  737. auto res = common_remote_get_content(url, params);
  738. res_code = res.first;
  739. res_str = std::string(res.second.data(), res.second.size());
  740. } catch (const std::exception & e) {
  741. LOG_WRN("error: failed to get manifest at %s: %s\n", url.c_str(), e.what());
  742. }
  743. }
  744. if (res_code == 0) {
  745. if (std::filesystem::exists(cached_response_path)) {
  746. LOG_WRN("trying to read manifest from cache: %s\n", cached_response_path.c_str());
  747. res_str = read_file(cached_response_path);
  748. res_code = 200;
  749. use_cache = true;
  750. } else {
  751. throw std::runtime_error(
  752. offline ? "error: failed to get manifest (offline mode)"
  753. : "error: failed to get manifest (check your internet connection)");
  754. }
  755. }
  756. std::string ggufFile;
  757. std::string mmprojFile;
  758. if (res_code == 200 || res_code == 304) {
  759. try {
  760. auto j = json::parse(res_str);
  761. if (j.contains("ggufFile") && j["ggufFile"].contains("rfilename")) {
  762. ggufFile = j["ggufFile"]["rfilename"].get<std::string>();
  763. }
  764. if (j.contains("mmprojFile") && j["mmprojFile"].contains("rfilename")) {
  765. mmprojFile = j["mmprojFile"]["rfilename"].get<std::string>();
  766. }
  767. } catch (const std::exception & e) {
  768. throw std::runtime_error(std::string("error parsing manifest JSON: ") + e.what());
  769. }
  770. if (!use_cache) {
  771. // if not using cached response, update the cache file
  772. write_file(cached_response_path, res_str);
  773. }
  774. } else if (res_code == 401) {
  775. throw std::runtime_error("error: model is private or does not exist; if you are accessing a gated model, please provide a valid HF token");
  776. } else {
  777. throw std::runtime_error(string_format("error from HF API, response code: %ld, data: %s", res_code, res_str.c_str()));
  778. }
  779. // check response
  780. if (ggufFile.empty()) {
  781. throw std::runtime_error("error: model does not have ggufFile");
  782. }
  783. return { hf_repo, ggufFile, mmprojFile };
  784. }
  785. //
  786. // Docker registry functions
  787. //
  788. static std::string common_docker_get_token(const std::string & repo) {
  789. std::string url = "https://auth.docker.io/token?service=registry.docker.io&scope=repository:" + repo + ":pull";
  790. common_remote_params params;
  791. auto res = common_remote_get_content(url, params);
  792. if (res.first != 200) {
  793. throw std::runtime_error("Failed to get Docker registry token, HTTP code: " + std::to_string(res.first));
  794. }
  795. std::string response_str(res.second.begin(), res.second.end());
  796. nlohmann::ordered_json response = nlohmann::ordered_json::parse(response_str);
  797. if (!response.contains("token")) {
  798. throw std::runtime_error("Docker registry token response missing 'token' field");
  799. }
  800. return response["token"].get<std::string>();
  801. }
  802. std::string common_docker_resolve_model(const std::string & docker) {
  803. // Parse ai/smollm2:135M-Q4_0
  804. size_t colon_pos = docker.find(':');
  805. std::string repo, tag;
  806. if (colon_pos != std::string::npos) {
  807. repo = docker.substr(0, colon_pos);
  808. tag = docker.substr(colon_pos + 1);
  809. } else {
  810. repo = docker;
  811. tag = "latest";
  812. }
  813. // ai/ is the default
  814. size_t slash_pos = docker.find('/');
  815. if (slash_pos == std::string::npos) {
  816. repo.insert(0, "ai/");
  817. }
  818. LOG_INF("%s: Downloading Docker Model: %s:%s\n", __func__, repo.c_str(), tag.c_str());
  819. try {
  820. // --- helper: digest validation ---
  821. auto validate_oci_digest = [](const std::string & digest) -> std::string {
  822. // Expected: algo:hex ; start with sha256 (64 hex chars)
  823. // You can extend this map if supporting other algorithms in future.
  824. static const std::regex re("^sha256:([a-fA-F0-9]{64})$");
  825. std::smatch m;
  826. if (!std::regex_match(digest, m, re)) {
  827. throw std::runtime_error("Invalid OCI digest format received in manifest: " + digest);
  828. }
  829. // normalize hex to lowercase
  830. std::string normalized = digest;
  831. std::transform(normalized.begin()+7, normalized.end(), normalized.begin()+7, [](unsigned char c){
  832. return std::tolower(c);
  833. });
  834. return normalized;
  835. };
  836. std::string token = common_docker_get_token(repo); // Get authentication token
  837. // Get manifest
  838. // TODO: cache the manifest response so that it appears in the model list
  839. const std::string url_prefix = "https://registry-1.docker.io/v2/" + repo;
  840. std::string manifest_url = url_prefix + "/manifests/" + tag;
  841. common_remote_params manifest_params;
  842. manifest_params.headers.push_back("Authorization: Bearer " + token);
  843. manifest_params.headers.push_back(
  844. "Accept: application/vnd.docker.distribution.manifest.v2+json,application/vnd.oci.image.manifest.v1+json");
  845. auto manifest_res = common_remote_get_content(manifest_url, manifest_params);
  846. if (manifest_res.first != 200) {
  847. throw std::runtime_error("Failed to get Docker manifest, HTTP code: " + std::to_string(manifest_res.first));
  848. }
  849. std::string manifest_str(manifest_res.second.begin(), manifest_res.second.end());
  850. nlohmann::ordered_json manifest = nlohmann::ordered_json::parse(manifest_str);
  851. std::string gguf_digest; // Find the GGUF layer
  852. if (manifest.contains("layers")) {
  853. for (const auto & layer : manifest["layers"]) {
  854. if (layer.contains("mediaType")) {
  855. std::string media_type = layer["mediaType"].get<std::string>();
  856. if (media_type == "application/vnd.docker.ai.gguf.v3" ||
  857. media_type.find("gguf") != std::string::npos) {
  858. gguf_digest = layer["digest"].get<std::string>();
  859. break;
  860. }
  861. }
  862. }
  863. }
  864. if (gguf_digest.empty()) {
  865. throw std::runtime_error("No GGUF layer found in Docker manifest");
  866. }
  867. // Validate & normalize digest
  868. gguf_digest = validate_oci_digest(gguf_digest);
  869. LOG_DBG("%s: Using validated digest: %s\n", __func__, gguf_digest.c_str());
  870. // Prepare local filename
  871. std::string model_filename = repo;
  872. std::replace(model_filename.begin(), model_filename.end(), '/', '_');
  873. model_filename += "_" + tag + ".gguf";
  874. std::string local_path = fs_get_cache_file(model_filename);
  875. const std::string blob_url = url_prefix + "/blobs/" + gguf_digest;
  876. if (!common_download_file_single(blob_url, local_path, token, false)) {
  877. throw std::runtime_error("Failed to download Docker Model");
  878. }
  879. LOG_INF("%s: Downloaded Docker Model to: %s\n", __func__, local_path.c_str());
  880. return local_path;
  881. } catch (const std::exception & e) {
  882. LOG_ERR("%s: Docker Model download failed: %s\n", __func__, e.what());
  883. throw;
  884. }
  885. }
  886. #else
  887. common_hf_file_res common_get_hf_file(const std::string &, const std::string &, bool) {
  888. throw std::runtime_error("download functionality is not enabled in this build");
  889. }
  890. bool common_download_model(const common_params_model &, const std::string &, bool) {
  891. throw std::runtime_error("download functionality is not enabled in this build");
  892. }
  893. std::string common_docker_resolve_model(const std::string &) {
  894. throw std::runtime_error("download functionality is not enabled in this build");
  895. }
  896. #endif // LLAMA_USE_CURL || LLAMA_USE_HTTPLIB
  897. std::vector<common_cached_model_info> common_list_cached_models() {
  898. std::vector<common_cached_model_info> models;
  899. const std::string cache_dir = fs_get_cache_directory();
  900. const std::vector<common_file_info> files = fs_list_files(cache_dir);
  901. for (const auto & file : files) {
  902. if (string_starts_with(file.name, "manifest=") && string_ends_with(file.name, ".json")) {
  903. common_cached_model_info model_info;
  904. model_info.manifest_path = file.path;
  905. std::string fname = file.name;
  906. string_replace_all(fname, ".json", ""); // remove extension
  907. auto parts = string_split<std::string>(fname, '=');
  908. if (parts.size() == 4) {
  909. // expect format: manifest=<user>=<model>=<tag>=<other>
  910. model_info.user = parts[1];
  911. model_info.model = parts[2];
  912. model_info.tag = parts[3];
  913. } else {
  914. // invalid format
  915. continue;
  916. }
  917. model_info.size = 0; // TODO: get GGUF size, not manifest size
  918. models.push_back(model_info);
  919. }
  920. }
  921. return models;
  922. }