download.cpp 44 KB

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