download.cpp 41 KB

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