http.c 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606
  1. #include "git-compat-util.h"
  2. #include "http.h"
  3. #include "config.h"
  4. #include "pack.h"
  5. #include "sideband.h"
  6. #include "run-command.h"
  7. #include "url.h"
  8. #include "urlmatch.h"
  9. #include "credential.h"
  10. #include "version.h"
  11. #include "pkt-line.h"
  12. #include "gettext.h"
  13. #include "transport.h"
  14. #include "packfile.h"
  15. #include "protocol.h"
  16. #include "string-list.h"
  17. #include "object-store.h"
  18. static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
  19. static int trace_curl_data = 1;
  20. static int trace_curl_redact = 1;
  21. #if LIBCURL_VERSION_NUM >= 0x070a08
  22. long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
  23. #else
  24. long int git_curl_ipresolve;
  25. #endif
  26. int active_requests;
  27. int http_is_verbose;
  28. ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
  29. #if LIBCURL_VERSION_NUM >= 0x070a06
  30. #define LIBCURL_CAN_HANDLE_AUTH_ANY
  31. #endif
  32. static int min_curl_sessions = 1;
  33. static int curl_session_count;
  34. #ifdef USE_CURL_MULTI
  35. static int max_requests = -1;
  36. static CURLM *curlm;
  37. #endif
  38. #ifndef NO_CURL_EASY_DUPHANDLE
  39. static CURL *curl_default;
  40. #endif
  41. #define PREV_BUF_SIZE 4096
  42. char curl_errorstr[CURL_ERROR_SIZE];
  43. static int curl_ssl_verify = -1;
  44. static int curl_ssl_try;
  45. static const char *curl_http_version = NULL;
  46. static const char *ssl_cert;
  47. static const char *ssl_cipherlist;
  48. static const char *ssl_version;
  49. static struct {
  50. const char *name;
  51. long ssl_version;
  52. } sslversions[] = {
  53. { "sslv2", CURL_SSLVERSION_SSLv2 },
  54. { "sslv3", CURL_SSLVERSION_SSLv3 },
  55. { "tlsv1", CURL_SSLVERSION_TLSv1 },
  56. #if LIBCURL_VERSION_NUM >= 0x072200
  57. { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
  58. { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
  59. { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
  60. #endif
  61. #if LIBCURL_VERSION_NUM >= 0x073400
  62. { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
  63. #endif
  64. };
  65. #if LIBCURL_VERSION_NUM >= 0x070903
  66. static const char *ssl_key;
  67. #endif
  68. #if LIBCURL_VERSION_NUM >= 0x070908
  69. static const char *ssl_capath;
  70. #endif
  71. #if LIBCURL_VERSION_NUM >= 0x071304
  72. static const char *curl_no_proxy;
  73. #endif
  74. #if LIBCURL_VERSION_NUM >= 0x072c00
  75. static const char *ssl_pinnedkey;
  76. #endif
  77. static const char *ssl_cainfo;
  78. static long curl_low_speed_limit = -1;
  79. static long curl_low_speed_time = -1;
  80. static int curl_ftp_no_epsv;
  81. static const char *curl_http_proxy;
  82. static const char *http_proxy_authmethod;
  83. static const char *http_proxy_ssl_cert;
  84. static const char *http_proxy_ssl_key;
  85. static const char *http_proxy_ssl_ca_info;
  86. static struct credential proxy_cert_auth = CREDENTIAL_INIT;
  87. static int proxy_ssl_cert_password_required;
  88. static struct {
  89. const char *name;
  90. long curlauth_param;
  91. } proxy_authmethods[] = {
  92. { "basic", CURLAUTH_BASIC },
  93. { "digest", CURLAUTH_DIGEST },
  94. { "negotiate", CURLAUTH_GSSNEGOTIATE },
  95. { "ntlm", CURLAUTH_NTLM },
  96. #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
  97. { "anyauth", CURLAUTH_ANY },
  98. #endif
  99. /*
  100. * CURLAUTH_DIGEST_IE has no corresponding command-line option in
  101. * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
  102. * here, too
  103. */
  104. };
  105. #ifdef CURLGSSAPI_DELEGATION_FLAG
  106. static const char *curl_deleg;
  107. static struct {
  108. const char *name;
  109. long curl_deleg_param;
  110. } curl_deleg_levels[] = {
  111. { "none", CURLGSSAPI_DELEGATION_NONE },
  112. { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
  113. { "always", CURLGSSAPI_DELEGATION_FLAG },
  114. };
  115. #endif
  116. static struct credential proxy_auth = CREDENTIAL_INIT;
  117. static const char *curl_proxyuserpwd;
  118. static const char *curl_cookie_file;
  119. static int curl_save_cookies;
  120. struct credential http_auth = CREDENTIAL_INIT;
  121. static int http_proactive_auth;
  122. static const char *user_agent;
  123. static int curl_empty_auth = -1;
  124. enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
  125. #if LIBCURL_VERSION_NUM >= 0x071700
  126. /* Use CURLOPT_KEYPASSWD as is */
  127. #elif LIBCURL_VERSION_NUM >= 0x070903
  128. #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
  129. #else
  130. #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
  131. #endif
  132. static struct credential cert_auth = CREDENTIAL_INIT;
  133. static int ssl_cert_password_required;
  134. #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
  135. static unsigned long http_auth_methods = CURLAUTH_ANY;
  136. static int http_auth_methods_restricted;
  137. /* Modes for which empty_auth cannot actually help us. */
  138. static unsigned long empty_auth_useless =
  139. CURLAUTH_BASIC
  140. #ifdef CURLAUTH_DIGEST_IE
  141. | CURLAUTH_DIGEST_IE
  142. #endif
  143. | CURLAUTH_DIGEST;
  144. #endif
  145. static struct curl_slist *pragma_header;
  146. static struct curl_slist *no_pragma_header;
  147. static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
  148. static struct active_request_slot *active_queue_head;
  149. static char *cached_accept_language;
  150. static char *http_ssl_backend;
  151. static int http_schannel_check_revoke = 1;
  152. /*
  153. * With the backend being set to `schannel`, setting sslCAinfo would override
  154. * the Certificate Store in cURL v7.60.0 and later, which is not what we want
  155. * by default.
  156. */
  157. static int http_schannel_use_ssl_cainfo;
  158. size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
  159. {
  160. size_t size = eltsize * nmemb;
  161. struct buffer *buffer = buffer_;
  162. if (size > buffer->buf.len - buffer->posn)
  163. size = buffer->buf.len - buffer->posn;
  164. memcpy(ptr, buffer->buf.buf + buffer->posn, size);
  165. buffer->posn += size;
  166. return size / eltsize;
  167. }
  168. #ifndef NO_CURL_IOCTL
  169. curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
  170. {
  171. struct buffer *buffer = clientp;
  172. switch (cmd) {
  173. case CURLIOCMD_NOP:
  174. return CURLIOE_OK;
  175. case CURLIOCMD_RESTARTREAD:
  176. buffer->posn = 0;
  177. return CURLIOE_OK;
  178. default:
  179. return CURLIOE_UNKNOWNCMD;
  180. }
  181. }
  182. #endif
  183. size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
  184. {
  185. size_t size = eltsize * nmemb;
  186. struct strbuf *buffer = buffer_;
  187. strbuf_add(buffer, ptr, size);
  188. return nmemb;
  189. }
  190. size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
  191. {
  192. return nmemb;
  193. }
  194. static void closedown_active_slot(struct active_request_slot *slot)
  195. {
  196. active_requests--;
  197. slot->in_use = 0;
  198. }
  199. static void finish_active_slot(struct active_request_slot *slot)
  200. {
  201. closedown_active_slot(slot);
  202. curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
  203. if (slot->finished != NULL)
  204. (*slot->finished) = 1;
  205. /* Store slot results so they can be read after the slot is reused */
  206. if (slot->results != NULL) {
  207. slot->results->curl_result = slot->curl_result;
  208. slot->results->http_code = slot->http_code;
  209. #if LIBCURL_VERSION_NUM >= 0x070a08
  210. curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
  211. &slot->results->auth_avail);
  212. #else
  213. slot->results->auth_avail = 0;
  214. #endif
  215. curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
  216. &slot->results->http_connectcode);
  217. }
  218. /* Run callback if appropriate */
  219. if (slot->callback_func != NULL)
  220. slot->callback_func(slot->callback_data);
  221. }
  222. static void xmulti_remove_handle(struct active_request_slot *slot)
  223. {
  224. #ifdef USE_CURL_MULTI
  225. curl_multi_remove_handle(curlm, slot->curl);
  226. #endif
  227. }
  228. #ifdef USE_CURL_MULTI
  229. static void process_curl_messages(void)
  230. {
  231. int num_messages;
  232. struct active_request_slot *slot;
  233. CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
  234. while (curl_message != NULL) {
  235. if (curl_message->msg == CURLMSG_DONE) {
  236. int curl_result = curl_message->data.result;
  237. slot = active_queue_head;
  238. while (slot != NULL &&
  239. slot->curl != curl_message->easy_handle)
  240. slot = slot->next;
  241. if (slot != NULL) {
  242. xmulti_remove_handle(slot);
  243. slot->curl_result = curl_result;
  244. finish_active_slot(slot);
  245. } else {
  246. fprintf(stderr, "Received DONE message for unknown request!\n");
  247. }
  248. } else {
  249. fprintf(stderr, "Unknown CURL message received: %d\n",
  250. (int)curl_message->msg);
  251. }
  252. curl_message = curl_multi_info_read(curlm, &num_messages);
  253. }
  254. }
  255. #endif
  256. static int http_options(const char *var, const char *value, void *cb)
  257. {
  258. if (!strcmp("http.version", var)) {
  259. return git_config_string(&curl_http_version, var, value);
  260. }
  261. if (!strcmp("http.sslverify", var)) {
  262. curl_ssl_verify = git_config_bool(var, value);
  263. return 0;
  264. }
  265. if (!strcmp("http.sslcipherlist", var))
  266. return git_config_string(&ssl_cipherlist, var, value);
  267. if (!strcmp("http.sslversion", var))
  268. return git_config_string(&ssl_version, var, value);
  269. if (!strcmp("http.sslcert", var))
  270. return git_config_pathname(&ssl_cert, var, value);
  271. #if LIBCURL_VERSION_NUM >= 0x070903
  272. if (!strcmp("http.sslkey", var))
  273. return git_config_pathname(&ssl_key, var, value);
  274. #endif
  275. #if LIBCURL_VERSION_NUM >= 0x070908
  276. if (!strcmp("http.sslcapath", var))
  277. return git_config_pathname(&ssl_capath, var, value);
  278. #endif
  279. if (!strcmp("http.sslcainfo", var))
  280. return git_config_pathname(&ssl_cainfo, var, value);
  281. if (!strcmp("http.sslcertpasswordprotected", var)) {
  282. ssl_cert_password_required = git_config_bool(var, value);
  283. return 0;
  284. }
  285. if (!strcmp("http.ssltry", var)) {
  286. curl_ssl_try = git_config_bool(var, value);
  287. return 0;
  288. }
  289. if (!strcmp("http.sslbackend", var)) {
  290. free(http_ssl_backend);
  291. http_ssl_backend = xstrdup_or_null(value);
  292. return 0;
  293. }
  294. if (!strcmp("http.schannelcheckrevoke", var)) {
  295. http_schannel_check_revoke = git_config_bool(var, value);
  296. return 0;
  297. }
  298. if (!strcmp("http.schannelusesslcainfo", var)) {
  299. http_schannel_use_ssl_cainfo = git_config_bool(var, value);
  300. return 0;
  301. }
  302. if (!strcmp("http.minsessions", var)) {
  303. min_curl_sessions = git_config_int(var, value);
  304. #ifndef USE_CURL_MULTI
  305. if (min_curl_sessions > 1)
  306. min_curl_sessions = 1;
  307. #endif
  308. return 0;
  309. }
  310. #ifdef USE_CURL_MULTI
  311. if (!strcmp("http.maxrequests", var)) {
  312. max_requests = git_config_int(var, value);
  313. return 0;
  314. }
  315. #endif
  316. if (!strcmp("http.lowspeedlimit", var)) {
  317. curl_low_speed_limit = (long)git_config_int(var, value);
  318. return 0;
  319. }
  320. if (!strcmp("http.lowspeedtime", var)) {
  321. curl_low_speed_time = (long)git_config_int(var, value);
  322. return 0;
  323. }
  324. if (!strcmp("http.noepsv", var)) {
  325. curl_ftp_no_epsv = git_config_bool(var, value);
  326. return 0;
  327. }
  328. if (!strcmp("http.proxy", var))
  329. return git_config_string(&curl_http_proxy, var, value);
  330. if (!strcmp("http.proxyauthmethod", var))
  331. return git_config_string(&http_proxy_authmethod, var, value);
  332. if (!strcmp("http.proxysslcert", var))
  333. return git_config_string(&http_proxy_ssl_cert, var, value);
  334. if (!strcmp("http.proxysslkey", var))
  335. return git_config_string(&http_proxy_ssl_key, var, value);
  336. if (!strcmp("http.proxysslcainfo", var))
  337. return git_config_string(&http_proxy_ssl_ca_info, var, value);
  338. if (!strcmp("http.proxysslcertpasswordprotected", var)) {
  339. proxy_ssl_cert_password_required = git_config_bool(var, value);
  340. return 0;
  341. }
  342. if (!strcmp("http.cookiefile", var))
  343. return git_config_pathname(&curl_cookie_file, var, value);
  344. if (!strcmp("http.savecookies", var)) {
  345. curl_save_cookies = git_config_bool(var, value);
  346. return 0;
  347. }
  348. if (!strcmp("http.postbuffer", var)) {
  349. http_post_buffer = git_config_ssize_t(var, value);
  350. if (http_post_buffer < 0)
  351. warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
  352. if (http_post_buffer < LARGE_PACKET_MAX)
  353. http_post_buffer = LARGE_PACKET_MAX;
  354. return 0;
  355. }
  356. if (!strcmp("http.useragent", var))
  357. return git_config_string(&user_agent, var, value);
  358. if (!strcmp("http.emptyauth", var)) {
  359. if (value && !strcmp("auto", value))
  360. curl_empty_auth = -1;
  361. else
  362. curl_empty_auth = git_config_bool(var, value);
  363. return 0;
  364. }
  365. if (!strcmp("http.delegation", var)) {
  366. #ifdef CURLGSSAPI_DELEGATION_FLAG
  367. return git_config_string(&curl_deleg, var, value);
  368. #else
  369. warning(_("Delegation control is not supported with cURL < 7.22.0"));
  370. return 0;
  371. #endif
  372. }
  373. if (!strcmp("http.pinnedpubkey", var)) {
  374. #if LIBCURL_VERSION_NUM >= 0x072c00
  375. return git_config_pathname(&ssl_pinnedkey, var, value);
  376. #else
  377. warning(_("Public key pinning not supported with cURL < 7.44.0"));
  378. return 0;
  379. #endif
  380. }
  381. if (!strcmp("http.extraheader", var)) {
  382. if (!value) {
  383. return config_error_nonbool(var);
  384. } else if (!*value) {
  385. string_list_clear(&extra_http_headers, 0);
  386. } else {
  387. string_list_append(&extra_http_headers, value);
  388. }
  389. return 0;
  390. }
  391. if (!strcmp("http.followredirects", var)) {
  392. if (value && !strcmp(value, "initial"))
  393. http_follow_config = HTTP_FOLLOW_INITIAL;
  394. else if (git_config_bool(var, value))
  395. http_follow_config = HTTP_FOLLOW_ALWAYS;
  396. else
  397. http_follow_config = HTTP_FOLLOW_NONE;
  398. return 0;
  399. }
  400. /* Fall back on the default ones */
  401. return git_default_config(var, value, cb);
  402. }
  403. static int curl_empty_auth_enabled(void)
  404. {
  405. if (curl_empty_auth >= 0)
  406. return curl_empty_auth;
  407. #ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
  408. /*
  409. * Our libcurl is too old to do AUTH_ANY in the first place;
  410. * just default to turning the feature off.
  411. */
  412. #else
  413. /*
  414. * In the automatic case, kick in the empty-auth
  415. * hack as long as we would potentially try some
  416. * method more exotic than "Basic" or "Digest".
  417. *
  418. * But only do this when this is our second or
  419. * subsequent request, as by then we know what
  420. * methods are available.
  421. */
  422. if (http_auth_methods_restricted &&
  423. (http_auth_methods & ~empty_auth_useless))
  424. return 1;
  425. #endif
  426. return 0;
  427. }
  428. static void init_curl_http_auth(CURL *result)
  429. {
  430. if (!http_auth.username || !*http_auth.username) {
  431. if (curl_empty_auth_enabled())
  432. curl_easy_setopt(result, CURLOPT_USERPWD, ":");
  433. return;
  434. }
  435. credential_fill(&http_auth);
  436. #if LIBCURL_VERSION_NUM >= 0x071301
  437. curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
  438. curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
  439. #else
  440. {
  441. static struct strbuf up = STRBUF_INIT;
  442. /*
  443. * Note that we assume we only ever have a single set of
  444. * credentials in a given program run, so we do not have
  445. * to worry about updating this buffer, only setting its
  446. * initial value.
  447. */
  448. if (!up.len)
  449. strbuf_addf(&up, "%s:%s",
  450. http_auth.username, http_auth.password);
  451. curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
  452. }
  453. #endif
  454. }
  455. /* *var must be free-able */
  456. static void var_override(const char **var, char *value)
  457. {
  458. if (value) {
  459. free((void *)*var);
  460. *var = xstrdup(value);
  461. }
  462. }
  463. static void set_proxyauth_name_password(CURL *result)
  464. {
  465. #if LIBCURL_VERSION_NUM >= 0x071301
  466. curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
  467. proxy_auth.username);
  468. curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
  469. proxy_auth.password);
  470. #else
  471. struct strbuf s = STRBUF_INIT;
  472. strbuf_addstr_urlencode(&s, proxy_auth.username,
  473. is_rfc3986_unreserved);
  474. strbuf_addch(&s, ':');
  475. strbuf_addstr_urlencode(&s, proxy_auth.password,
  476. is_rfc3986_unreserved);
  477. curl_proxyuserpwd = strbuf_detach(&s, NULL);
  478. curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
  479. #endif
  480. }
  481. static void init_curl_proxy_auth(CURL *result)
  482. {
  483. if (proxy_auth.username) {
  484. if (!proxy_auth.password)
  485. credential_fill(&proxy_auth);
  486. set_proxyauth_name_password(result);
  487. }
  488. var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
  489. #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
  490. if (http_proxy_authmethod) {
  491. int i;
  492. for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
  493. if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
  494. curl_easy_setopt(result, CURLOPT_PROXYAUTH,
  495. proxy_authmethods[i].curlauth_param);
  496. break;
  497. }
  498. }
  499. if (i == ARRAY_SIZE(proxy_authmethods)) {
  500. warning("unsupported proxy authentication method %s: using anyauth",
  501. http_proxy_authmethod);
  502. curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
  503. }
  504. }
  505. else
  506. curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
  507. #endif
  508. }
  509. static int has_cert_password(void)
  510. {
  511. if (ssl_cert == NULL || ssl_cert_password_required != 1)
  512. return 0;
  513. if (!cert_auth.password) {
  514. cert_auth.protocol = xstrdup("cert");
  515. cert_auth.host = xstrdup("");
  516. cert_auth.username = xstrdup("");
  517. cert_auth.path = xstrdup(ssl_cert);
  518. credential_fill(&cert_auth);
  519. }
  520. return 1;
  521. }
  522. #if LIBCURL_VERSION_NUM >= 0x073400
  523. static int has_proxy_cert_password(void)
  524. {
  525. if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
  526. return 0;
  527. if (!proxy_cert_auth.password) {
  528. proxy_cert_auth.protocol = xstrdup("cert");
  529. proxy_cert_auth.host = xstrdup("");
  530. proxy_cert_auth.username = xstrdup("");
  531. proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
  532. credential_fill(&proxy_cert_auth);
  533. }
  534. return 1;
  535. }
  536. #endif
  537. #if LIBCURL_VERSION_NUM >= 0x071900
  538. static void set_curl_keepalive(CURL *c)
  539. {
  540. curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
  541. }
  542. #elif LIBCURL_VERSION_NUM >= 0x071000
  543. static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
  544. {
  545. int ka = 1;
  546. int rc;
  547. socklen_t len = (socklen_t)sizeof(ka);
  548. if (type != CURLSOCKTYPE_IPCXN)
  549. return 0;
  550. rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
  551. if (rc < 0)
  552. warning_errno("unable to set SO_KEEPALIVE on socket");
  553. return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
  554. }
  555. static void set_curl_keepalive(CURL *c)
  556. {
  557. curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
  558. }
  559. #else
  560. static void set_curl_keepalive(CURL *c)
  561. {
  562. /* not supported on older curl versions */
  563. }
  564. #endif
  565. static void redact_sensitive_header(struct strbuf *header)
  566. {
  567. const char *sensitive_header;
  568. if (trace_curl_redact &&
  569. (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
  570. skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header))) {
  571. /* The first token is the type, which is OK to log */
  572. while (isspace(*sensitive_header))
  573. sensitive_header++;
  574. while (*sensitive_header && !isspace(*sensitive_header))
  575. sensitive_header++;
  576. /* Everything else is opaque and possibly sensitive */
  577. strbuf_setlen(header, sensitive_header - header->buf);
  578. strbuf_addstr(header, " <redacted>");
  579. } else if (trace_curl_redact &&
  580. skip_prefix(header->buf, "Cookie:", &sensitive_header)) {
  581. struct strbuf redacted_header = STRBUF_INIT;
  582. const char *cookie;
  583. while (isspace(*sensitive_header))
  584. sensitive_header++;
  585. cookie = sensitive_header;
  586. while (cookie) {
  587. char *equals;
  588. char *semicolon = strstr(cookie, "; ");
  589. if (semicolon)
  590. *semicolon = 0;
  591. equals = strchrnul(cookie, '=');
  592. if (!equals) {
  593. /* invalid cookie, just append and continue */
  594. strbuf_addstr(&redacted_header, cookie);
  595. continue;
  596. }
  597. strbuf_add(&redacted_header, cookie, equals - cookie);
  598. strbuf_addstr(&redacted_header, "=<redacted>");
  599. if (semicolon) {
  600. /*
  601. * There are more cookies. (Or, for some
  602. * reason, the input string ends in "; ".)
  603. */
  604. strbuf_addstr(&redacted_header, "; ");
  605. cookie = semicolon + strlen("; ");
  606. } else {
  607. cookie = NULL;
  608. }
  609. }
  610. strbuf_setlen(header, sensitive_header - header->buf);
  611. strbuf_addbuf(header, &redacted_header);
  612. }
  613. }
  614. static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
  615. {
  616. struct strbuf out = STRBUF_INIT;
  617. struct strbuf **headers, **header;
  618. strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
  619. text, (long)size, (long)size);
  620. trace_strbuf(&trace_curl, &out);
  621. strbuf_reset(&out);
  622. strbuf_add(&out, ptr, size);
  623. headers = strbuf_split_max(&out, '\n', 0);
  624. for (header = headers; *header; header++) {
  625. if (hide_sensitive_header)
  626. redact_sensitive_header(*header);
  627. strbuf_insertstr((*header), 0, text);
  628. strbuf_insertstr((*header), strlen(text), ": ");
  629. strbuf_rtrim((*header));
  630. strbuf_addch((*header), '\n');
  631. trace_strbuf(&trace_curl, (*header));
  632. }
  633. strbuf_list_free(headers);
  634. strbuf_release(&out);
  635. }
  636. static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
  637. {
  638. size_t i;
  639. struct strbuf out = STRBUF_INIT;
  640. unsigned int width = 60;
  641. strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
  642. text, (long)size, (long)size);
  643. trace_strbuf(&trace_curl, &out);
  644. for (i = 0; i < size; i += width) {
  645. size_t w;
  646. strbuf_reset(&out);
  647. strbuf_addf(&out, "%s: ", text);
  648. for (w = 0; (w < width) && (i + w < size); w++) {
  649. unsigned char ch = ptr[i + w];
  650. strbuf_addch(&out,
  651. (ch >= 0x20) && (ch < 0x80)
  652. ? ch : '.');
  653. }
  654. strbuf_addch(&out, '\n');
  655. trace_strbuf(&trace_curl, &out);
  656. }
  657. strbuf_release(&out);
  658. }
  659. static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
  660. {
  661. const char *text;
  662. enum { NO_FILTER = 0, DO_FILTER = 1 };
  663. switch (type) {
  664. case CURLINFO_TEXT:
  665. trace_printf_key(&trace_curl, "== Info: %s", data);
  666. break;
  667. case CURLINFO_HEADER_OUT:
  668. text = "=> Send header";
  669. curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
  670. break;
  671. case CURLINFO_DATA_OUT:
  672. if (trace_curl_data) {
  673. text = "=> Send data";
  674. curl_dump_data(text, (unsigned char *)data, size);
  675. }
  676. break;
  677. case CURLINFO_SSL_DATA_OUT:
  678. if (trace_curl_data) {
  679. text = "=> Send SSL data";
  680. curl_dump_data(text, (unsigned char *)data, size);
  681. }
  682. break;
  683. case CURLINFO_HEADER_IN:
  684. text = "<= Recv header";
  685. curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
  686. break;
  687. case CURLINFO_DATA_IN:
  688. if (trace_curl_data) {
  689. text = "<= Recv data";
  690. curl_dump_data(text, (unsigned char *)data, size);
  691. }
  692. break;
  693. case CURLINFO_SSL_DATA_IN:
  694. if (trace_curl_data) {
  695. text = "<= Recv SSL data";
  696. curl_dump_data(text, (unsigned char *)data, size);
  697. }
  698. break;
  699. default: /* we ignore unknown types by default */
  700. return 0;
  701. }
  702. return 0;
  703. }
  704. void http_trace_curl_no_data(void)
  705. {
  706. trace_override_envvar(&trace_curl, "1");
  707. trace_curl_data = 0;
  708. }
  709. void setup_curl_trace(CURL *handle)
  710. {
  711. if (!trace_want(&trace_curl))
  712. return;
  713. curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
  714. curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
  715. curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
  716. }
  717. #ifdef CURLPROTO_HTTP
  718. static long get_curl_allowed_protocols(int from_user)
  719. {
  720. long allowed_protocols = 0;
  721. if (is_transport_allowed("http", from_user))
  722. allowed_protocols |= CURLPROTO_HTTP;
  723. if (is_transport_allowed("https", from_user))
  724. allowed_protocols |= CURLPROTO_HTTPS;
  725. if (is_transport_allowed("ftp", from_user))
  726. allowed_protocols |= CURLPROTO_FTP;
  727. if (is_transport_allowed("ftps", from_user))
  728. allowed_protocols |= CURLPROTO_FTPS;
  729. return allowed_protocols;
  730. }
  731. #endif
  732. #if LIBCURL_VERSION_NUM >=0x072f00
  733. static int get_curl_http_version_opt(const char *version_string, long *opt)
  734. {
  735. int i;
  736. static struct {
  737. const char *name;
  738. long opt_token;
  739. } choice[] = {
  740. { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
  741. { "HTTP/2", CURL_HTTP_VERSION_2 }
  742. };
  743. for (i = 0; i < ARRAY_SIZE(choice); i++) {
  744. if (!strcmp(version_string, choice[i].name)) {
  745. *opt = choice[i].opt_token;
  746. return 0;
  747. }
  748. }
  749. warning("unknown value given to http.version: '%s'", version_string);
  750. return -1; /* not found */
  751. }
  752. #endif
  753. static CURL *get_curl_handle(void)
  754. {
  755. CURL *result = curl_easy_init();
  756. if (!result)
  757. die("curl_easy_init failed");
  758. if (!curl_ssl_verify) {
  759. curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
  760. curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
  761. } else {
  762. /* Verify authenticity of the peer's certificate */
  763. curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
  764. /* The name in the cert must match whom we tried to connect */
  765. curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
  766. }
  767. #if LIBCURL_VERSION_NUM >= 0x072f00 // 7.47.0
  768. if (curl_http_version) {
  769. long opt;
  770. if (!get_curl_http_version_opt(curl_http_version, &opt)) {
  771. /* Set request use http version */
  772. curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
  773. }
  774. }
  775. #endif
  776. #if LIBCURL_VERSION_NUM >= 0x070907
  777. curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
  778. #endif
  779. #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
  780. curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  781. #endif
  782. #ifdef CURLGSSAPI_DELEGATION_FLAG
  783. if (curl_deleg) {
  784. int i;
  785. for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
  786. if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
  787. curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
  788. curl_deleg_levels[i].curl_deleg_param);
  789. break;
  790. }
  791. }
  792. if (i == ARRAY_SIZE(curl_deleg_levels))
  793. warning("Unknown delegation method '%s': using default",
  794. curl_deleg);
  795. }
  796. #endif
  797. if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
  798. !http_schannel_check_revoke) {
  799. #if LIBCURL_VERSION_NUM >= 0x072c00
  800. curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
  801. #else
  802. warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
  803. #endif
  804. }
  805. if (http_proactive_auth)
  806. init_curl_http_auth(result);
  807. if (getenv("GIT_SSL_VERSION"))
  808. ssl_version = getenv("GIT_SSL_VERSION");
  809. if (ssl_version && *ssl_version) {
  810. int i;
  811. for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
  812. if (!strcmp(ssl_version, sslversions[i].name)) {
  813. curl_easy_setopt(result, CURLOPT_SSLVERSION,
  814. sslversions[i].ssl_version);
  815. break;
  816. }
  817. }
  818. if (i == ARRAY_SIZE(sslversions))
  819. warning("unsupported ssl version %s: using default",
  820. ssl_version);
  821. }
  822. if (getenv("GIT_SSL_CIPHER_LIST"))
  823. ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
  824. if (ssl_cipherlist != NULL && *ssl_cipherlist)
  825. curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
  826. ssl_cipherlist);
  827. if (ssl_cert != NULL)
  828. curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
  829. if (has_cert_password())
  830. curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
  831. #if LIBCURL_VERSION_NUM >= 0x070903
  832. if (ssl_key != NULL)
  833. curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
  834. #endif
  835. #if LIBCURL_VERSION_NUM >= 0x070908
  836. if (ssl_capath != NULL)
  837. curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
  838. #endif
  839. #if LIBCURL_VERSION_NUM >= 0x072c00
  840. if (ssl_pinnedkey != NULL)
  841. curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
  842. #endif
  843. if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
  844. !http_schannel_use_ssl_cainfo) {
  845. curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
  846. #if LIBCURL_VERSION_NUM >= 0x073400
  847. curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
  848. #endif
  849. } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
  850. if (ssl_cainfo != NULL)
  851. curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
  852. #if LIBCURL_VERSION_NUM >= 0x073400
  853. if (http_proxy_ssl_ca_info != NULL)
  854. curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
  855. #endif
  856. }
  857. if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
  858. curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
  859. curl_low_speed_limit);
  860. curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
  861. curl_low_speed_time);
  862. }
  863. curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
  864. #if LIBCURL_VERSION_NUM >= 0x071301
  865. curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
  866. #elif LIBCURL_VERSION_NUM >= 0x071101
  867. curl_easy_setopt(result, CURLOPT_POST301, 1);
  868. #endif
  869. #ifdef CURLPROTO_HTTP
  870. curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
  871. get_curl_allowed_protocols(0));
  872. curl_easy_setopt(result, CURLOPT_PROTOCOLS,
  873. get_curl_allowed_protocols(-1));
  874. #else
  875. warning(_("Protocol restrictions not supported with cURL < 7.19.4"));
  876. #endif
  877. if (getenv("GIT_CURL_VERBOSE"))
  878. http_trace_curl_no_data();
  879. setup_curl_trace(result);
  880. if (getenv("GIT_TRACE_CURL_NO_DATA"))
  881. trace_curl_data = 0;
  882. if (!git_env_bool("GIT_TRACE_REDACT", 1))
  883. trace_curl_redact = 0;
  884. curl_easy_setopt(result, CURLOPT_USERAGENT,
  885. user_agent ? user_agent : git_user_agent());
  886. if (curl_ftp_no_epsv)
  887. curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
  888. #ifdef CURLOPT_USE_SSL
  889. if (curl_ssl_try)
  890. curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  891. #endif
  892. /*
  893. * CURL also examines these variables as a fallback; but we need to query
  894. * them here in order to decide whether to prompt for missing password (cf.
  895. * init_curl_proxy_auth()).
  896. *
  897. * Unlike many other common environment variables, these are historically
  898. * lowercase only. It appears that CURL did not know this and implemented
  899. * only uppercase variants, which was later corrected to take both - with
  900. * the exception of http_proxy, which is lowercase only also in CURL. As
  901. * the lowercase versions are the historical quasi-standard, they take
  902. * precedence here, as in CURL.
  903. */
  904. if (!curl_http_proxy) {
  905. if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
  906. var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
  907. var_override(&curl_http_proxy, getenv("https_proxy"));
  908. } else {
  909. var_override(&curl_http_proxy, getenv("http_proxy"));
  910. }
  911. if (!curl_http_proxy) {
  912. var_override(&curl_http_proxy, getenv("ALL_PROXY"));
  913. var_override(&curl_http_proxy, getenv("all_proxy"));
  914. }
  915. }
  916. if (curl_http_proxy && curl_http_proxy[0] == '\0') {
  917. /*
  918. * Handle case with the empty http.proxy value here to keep
  919. * common code clean.
  920. * NB: empty option disables proxying at all.
  921. */
  922. curl_easy_setopt(result, CURLOPT_PROXY, "");
  923. } else if (curl_http_proxy) {
  924. #if LIBCURL_VERSION_NUM >= 0x071800
  925. if (starts_with(curl_http_proxy, "socks5h"))
  926. curl_easy_setopt(result,
  927. CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
  928. else if (starts_with(curl_http_proxy, "socks5"))
  929. curl_easy_setopt(result,
  930. CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  931. else if (starts_with(curl_http_proxy, "socks4a"))
  932. curl_easy_setopt(result,
  933. CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
  934. else if (starts_with(curl_http_proxy, "socks"))
  935. curl_easy_setopt(result,
  936. CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  937. #endif
  938. #if LIBCURL_VERSION_NUM >= 0x073400
  939. else if (starts_with(curl_http_proxy, "https")) {
  940. curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
  941. if (http_proxy_ssl_cert)
  942. curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
  943. if (http_proxy_ssl_key)
  944. curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
  945. if (has_proxy_cert_password())
  946. curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
  947. }
  948. #endif
  949. if (strstr(curl_http_proxy, "://"))
  950. credential_from_url(&proxy_auth, curl_http_proxy);
  951. else {
  952. struct strbuf url = STRBUF_INIT;
  953. strbuf_addf(&url, "http://%s", curl_http_proxy);
  954. credential_from_url(&proxy_auth, url.buf);
  955. strbuf_release(&url);
  956. }
  957. if (!proxy_auth.host)
  958. die("Invalid proxy URL '%s'", curl_http_proxy);
  959. curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
  960. #if LIBCURL_VERSION_NUM >= 0x071304
  961. var_override(&curl_no_proxy, getenv("NO_PROXY"));
  962. var_override(&curl_no_proxy, getenv("no_proxy"));
  963. curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
  964. #endif
  965. }
  966. init_curl_proxy_auth(result);
  967. set_curl_keepalive(result);
  968. return result;
  969. }
  970. static void set_from_env(const char **var, const char *envname)
  971. {
  972. const char *val = getenv(envname);
  973. if (val)
  974. *var = val;
  975. }
  976. void http_init(struct remote *remote, const char *url, int proactive_auth)
  977. {
  978. char *low_speed_limit;
  979. char *low_speed_time;
  980. char *normalized_url;
  981. struct urlmatch_config config = { STRING_LIST_INIT_DUP };
  982. config.section = "http";
  983. config.key = NULL;
  984. config.collect_fn = http_options;
  985. config.cascade_fn = git_default_config;
  986. config.cb = NULL;
  987. http_is_verbose = 0;
  988. normalized_url = url_normalize(url, &config.url);
  989. git_config(urlmatch_config_entry, &config);
  990. free(normalized_url);
  991. string_list_clear(&config.vars, 1);
  992. #if LIBCURL_VERSION_NUM >= 0x073800
  993. if (http_ssl_backend) {
  994. const curl_ssl_backend **backends;
  995. struct strbuf buf = STRBUF_INIT;
  996. int i;
  997. switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
  998. case CURLSSLSET_UNKNOWN_BACKEND:
  999. strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
  1000. "Supported SSL backends:"),
  1001. http_ssl_backend);
  1002. for (i = 0; backends[i]; i++)
  1003. strbuf_addf(&buf, "\n\t%s", backends[i]->name);
  1004. die("%s", buf.buf);
  1005. case CURLSSLSET_NO_BACKENDS:
  1006. die(_("Could not set SSL backend to '%s': "
  1007. "cURL was built without SSL backends"),
  1008. http_ssl_backend);
  1009. case CURLSSLSET_TOO_LATE:
  1010. die(_("Could not set SSL backend to '%s': already set"),
  1011. http_ssl_backend);
  1012. case CURLSSLSET_OK:
  1013. break; /* Okay! */
  1014. }
  1015. }
  1016. #endif
  1017. if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
  1018. die("curl_global_init failed");
  1019. http_proactive_auth = proactive_auth;
  1020. if (remote && remote->http_proxy)
  1021. curl_http_proxy = xstrdup(remote->http_proxy);
  1022. if (remote)
  1023. var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
  1024. pragma_header = curl_slist_append(http_copy_default_headers(),
  1025. "Pragma: no-cache");
  1026. no_pragma_header = curl_slist_append(http_copy_default_headers(),
  1027. "Pragma:");
  1028. #ifdef USE_CURL_MULTI
  1029. {
  1030. char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
  1031. if (http_max_requests != NULL)
  1032. max_requests = atoi(http_max_requests);
  1033. }
  1034. curlm = curl_multi_init();
  1035. if (!curlm)
  1036. die("curl_multi_init failed");
  1037. #endif
  1038. if (getenv("GIT_SSL_NO_VERIFY"))
  1039. curl_ssl_verify = 0;
  1040. set_from_env(&ssl_cert, "GIT_SSL_CERT");
  1041. #if LIBCURL_VERSION_NUM >= 0x070903
  1042. set_from_env(&ssl_key, "GIT_SSL_KEY");
  1043. #endif
  1044. #if LIBCURL_VERSION_NUM >= 0x070908
  1045. set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
  1046. #endif
  1047. set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
  1048. set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
  1049. low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
  1050. if (low_speed_limit != NULL)
  1051. curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
  1052. low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
  1053. if (low_speed_time != NULL)
  1054. curl_low_speed_time = strtol(low_speed_time, NULL, 10);
  1055. if (curl_ssl_verify == -1)
  1056. curl_ssl_verify = 1;
  1057. curl_session_count = 0;
  1058. #ifdef USE_CURL_MULTI
  1059. if (max_requests < 1)
  1060. max_requests = DEFAULT_MAX_REQUESTS;
  1061. #endif
  1062. set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
  1063. set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
  1064. set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
  1065. if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
  1066. proxy_ssl_cert_password_required = 1;
  1067. if (getenv("GIT_CURL_FTP_NO_EPSV"))
  1068. curl_ftp_no_epsv = 1;
  1069. if (url) {
  1070. credential_from_url(&http_auth, url);
  1071. if (!ssl_cert_password_required &&
  1072. getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
  1073. starts_with(url, "https://"))
  1074. ssl_cert_password_required = 1;
  1075. }
  1076. #ifndef NO_CURL_EASY_DUPHANDLE
  1077. curl_default = get_curl_handle();
  1078. #endif
  1079. }
  1080. void http_cleanup(void)
  1081. {
  1082. struct active_request_slot *slot = active_queue_head;
  1083. while (slot != NULL) {
  1084. struct active_request_slot *next = slot->next;
  1085. if (slot->curl != NULL) {
  1086. xmulti_remove_handle(slot);
  1087. curl_easy_cleanup(slot->curl);
  1088. }
  1089. free(slot);
  1090. slot = next;
  1091. }
  1092. active_queue_head = NULL;
  1093. #ifndef NO_CURL_EASY_DUPHANDLE
  1094. curl_easy_cleanup(curl_default);
  1095. #endif
  1096. #ifdef USE_CURL_MULTI
  1097. curl_multi_cleanup(curlm);
  1098. #endif
  1099. curl_global_cleanup();
  1100. string_list_clear(&extra_http_headers, 0);
  1101. curl_slist_free_all(pragma_header);
  1102. pragma_header = NULL;
  1103. curl_slist_free_all(no_pragma_header);
  1104. no_pragma_header = NULL;
  1105. if (curl_http_proxy) {
  1106. free((void *)curl_http_proxy);
  1107. curl_http_proxy = NULL;
  1108. }
  1109. if (proxy_auth.password) {
  1110. memset(proxy_auth.password, 0, strlen(proxy_auth.password));
  1111. FREE_AND_NULL(proxy_auth.password);
  1112. }
  1113. free((void *)curl_proxyuserpwd);
  1114. curl_proxyuserpwd = NULL;
  1115. free((void *)http_proxy_authmethod);
  1116. http_proxy_authmethod = NULL;
  1117. if (cert_auth.password != NULL) {
  1118. memset(cert_auth.password, 0, strlen(cert_auth.password));
  1119. FREE_AND_NULL(cert_auth.password);
  1120. }
  1121. ssl_cert_password_required = 0;
  1122. if (proxy_cert_auth.password != NULL) {
  1123. memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
  1124. FREE_AND_NULL(proxy_cert_auth.password);
  1125. }
  1126. proxy_ssl_cert_password_required = 0;
  1127. FREE_AND_NULL(cached_accept_language);
  1128. }
  1129. struct active_request_slot *get_active_slot(void)
  1130. {
  1131. struct active_request_slot *slot = active_queue_head;
  1132. struct active_request_slot *newslot;
  1133. #ifdef USE_CURL_MULTI
  1134. int num_transfers;
  1135. /* Wait for a slot to open up if the queue is full */
  1136. while (active_requests >= max_requests) {
  1137. curl_multi_perform(curlm, &num_transfers);
  1138. if (num_transfers < active_requests)
  1139. process_curl_messages();
  1140. }
  1141. #endif
  1142. while (slot != NULL && slot->in_use)
  1143. slot = slot->next;
  1144. if (slot == NULL) {
  1145. newslot = xmalloc(sizeof(*newslot));
  1146. newslot->curl = NULL;
  1147. newslot->in_use = 0;
  1148. newslot->next = NULL;
  1149. slot = active_queue_head;
  1150. if (slot == NULL) {
  1151. active_queue_head = newslot;
  1152. } else {
  1153. while (slot->next != NULL)
  1154. slot = slot->next;
  1155. slot->next = newslot;
  1156. }
  1157. slot = newslot;
  1158. }
  1159. if (slot->curl == NULL) {
  1160. #ifdef NO_CURL_EASY_DUPHANDLE
  1161. slot->curl = get_curl_handle();
  1162. #else
  1163. slot->curl = curl_easy_duphandle(curl_default);
  1164. #endif
  1165. curl_session_count++;
  1166. }
  1167. active_requests++;
  1168. slot->in_use = 1;
  1169. slot->results = NULL;
  1170. slot->finished = NULL;
  1171. slot->callback_data = NULL;
  1172. slot->callback_func = NULL;
  1173. curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
  1174. if (curl_save_cookies)
  1175. curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
  1176. curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
  1177. curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
  1178. curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
  1179. curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
  1180. curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
  1181. curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
  1182. curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
  1183. curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
  1184. curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
  1185. curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
  1186. /*
  1187. * Default following to off unless "ALWAYS" is configured; this gives
  1188. * callers a sane starting point, and they can tweak for individual
  1189. * HTTP_FOLLOW_* cases themselves.
  1190. */
  1191. if (http_follow_config == HTTP_FOLLOW_ALWAYS)
  1192. curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
  1193. else
  1194. curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
  1195. #if LIBCURL_VERSION_NUM >= 0x070a08
  1196. curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
  1197. #endif
  1198. #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
  1199. curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
  1200. #endif
  1201. if (http_auth.password || curl_empty_auth_enabled())
  1202. init_curl_http_auth(slot->curl);
  1203. return slot;
  1204. }
  1205. int start_active_slot(struct active_request_slot *slot)
  1206. {
  1207. #ifdef USE_CURL_MULTI
  1208. CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
  1209. int num_transfers;
  1210. if (curlm_result != CURLM_OK &&
  1211. curlm_result != CURLM_CALL_MULTI_PERFORM) {
  1212. warning("curl_multi_add_handle failed: %s",
  1213. curl_multi_strerror(curlm_result));
  1214. active_requests--;
  1215. slot->in_use = 0;
  1216. return 0;
  1217. }
  1218. /*
  1219. * We know there must be something to do, since we just added
  1220. * something.
  1221. */
  1222. curl_multi_perform(curlm, &num_transfers);
  1223. #endif
  1224. return 1;
  1225. }
  1226. #ifdef USE_CURL_MULTI
  1227. struct fill_chain {
  1228. void *data;
  1229. int (*fill)(void *);
  1230. struct fill_chain *next;
  1231. };
  1232. static struct fill_chain *fill_cfg;
  1233. void add_fill_function(void *data, int (*fill)(void *))
  1234. {
  1235. struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
  1236. struct fill_chain **linkp = &fill_cfg;
  1237. new_fill->data = data;
  1238. new_fill->fill = fill;
  1239. new_fill->next = NULL;
  1240. while (*linkp)
  1241. linkp = &(*linkp)->next;
  1242. *linkp = new_fill;
  1243. }
  1244. void fill_active_slots(void)
  1245. {
  1246. struct active_request_slot *slot = active_queue_head;
  1247. while (active_requests < max_requests) {
  1248. struct fill_chain *fill;
  1249. for (fill = fill_cfg; fill; fill = fill->next)
  1250. if (fill->fill(fill->data))
  1251. break;
  1252. if (!fill)
  1253. break;
  1254. }
  1255. while (slot != NULL) {
  1256. if (!slot->in_use && slot->curl != NULL
  1257. && curl_session_count > min_curl_sessions) {
  1258. curl_easy_cleanup(slot->curl);
  1259. slot->curl = NULL;
  1260. curl_session_count--;
  1261. }
  1262. slot = slot->next;
  1263. }
  1264. }
  1265. void step_active_slots(void)
  1266. {
  1267. int num_transfers;
  1268. CURLMcode curlm_result;
  1269. do {
  1270. curlm_result = curl_multi_perform(curlm, &num_transfers);
  1271. } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
  1272. if (num_transfers < active_requests) {
  1273. process_curl_messages();
  1274. fill_active_slots();
  1275. }
  1276. }
  1277. #endif
  1278. void run_active_slot(struct active_request_slot *slot)
  1279. {
  1280. #ifdef USE_CURL_MULTI
  1281. fd_set readfds;
  1282. fd_set writefds;
  1283. fd_set excfds;
  1284. int max_fd;
  1285. struct timeval select_timeout;
  1286. int finished = 0;
  1287. slot->finished = &finished;
  1288. while (!finished) {
  1289. step_active_slots();
  1290. if (slot->in_use) {
  1291. #if LIBCURL_VERSION_NUM >= 0x070f04
  1292. long curl_timeout;
  1293. curl_multi_timeout(curlm, &curl_timeout);
  1294. if (curl_timeout == 0) {
  1295. continue;
  1296. } else if (curl_timeout == -1) {
  1297. select_timeout.tv_sec = 0;
  1298. select_timeout.tv_usec = 50000;
  1299. } else {
  1300. select_timeout.tv_sec = curl_timeout / 1000;
  1301. select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
  1302. }
  1303. #else
  1304. select_timeout.tv_sec = 0;
  1305. select_timeout.tv_usec = 50000;
  1306. #endif
  1307. max_fd = -1;
  1308. FD_ZERO(&readfds);
  1309. FD_ZERO(&writefds);
  1310. FD_ZERO(&excfds);
  1311. curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
  1312. /*
  1313. * It can happen that curl_multi_timeout returns a pathologically
  1314. * long timeout when curl_multi_fdset returns no file descriptors
  1315. * to read. See commit message for more details.
  1316. */
  1317. if (max_fd < 0 &&
  1318. (select_timeout.tv_sec > 0 ||
  1319. select_timeout.tv_usec > 50000)) {
  1320. select_timeout.tv_sec = 0;
  1321. select_timeout.tv_usec = 50000;
  1322. }
  1323. select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
  1324. }
  1325. }
  1326. #else
  1327. while (slot->in_use) {
  1328. slot->curl_result = curl_easy_perform(slot->curl);
  1329. finish_active_slot(slot);
  1330. }
  1331. #endif
  1332. }
  1333. static void release_active_slot(struct active_request_slot *slot)
  1334. {
  1335. closedown_active_slot(slot);
  1336. if (slot->curl) {
  1337. xmulti_remove_handle(slot);
  1338. if (curl_session_count > min_curl_sessions) {
  1339. curl_easy_cleanup(slot->curl);
  1340. slot->curl = NULL;
  1341. curl_session_count--;
  1342. }
  1343. }
  1344. #ifdef USE_CURL_MULTI
  1345. fill_active_slots();
  1346. #endif
  1347. }
  1348. void finish_all_active_slots(void)
  1349. {
  1350. struct active_request_slot *slot = active_queue_head;
  1351. while (slot != NULL)
  1352. if (slot->in_use) {
  1353. run_active_slot(slot);
  1354. slot = active_queue_head;
  1355. } else {
  1356. slot = slot->next;
  1357. }
  1358. }
  1359. /* Helpers for modifying and creating URLs */
  1360. static inline int needs_quote(int ch)
  1361. {
  1362. if (((ch >= 'A') && (ch <= 'Z'))
  1363. || ((ch >= 'a') && (ch <= 'z'))
  1364. || ((ch >= '0') && (ch <= '9'))
  1365. || (ch == '/')
  1366. || (ch == '-')
  1367. || (ch == '.'))
  1368. return 0;
  1369. return 1;
  1370. }
  1371. static char *quote_ref_url(const char *base, const char *ref)
  1372. {
  1373. struct strbuf buf = STRBUF_INIT;
  1374. const char *cp;
  1375. int ch;
  1376. end_url_with_slash(&buf, base);
  1377. for (cp = ref; (ch = *cp) != 0; cp++)
  1378. if (needs_quote(ch))
  1379. strbuf_addf(&buf, "%%%02x", ch);
  1380. else
  1381. strbuf_addch(&buf, *cp);
  1382. return strbuf_detach(&buf, NULL);
  1383. }
  1384. void append_remote_object_url(struct strbuf *buf, const char *url,
  1385. const char *hex,
  1386. int only_two_digit_prefix)
  1387. {
  1388. end_url_with_slash(buf, url);
  1389. strbuf_addf(buf, "objects/%.*s/", 2, hex);
  1390. if (!only_two_digit_prefix)
  1391. strbuf_addstr(buf, hex + 2);
  1392. }
  1393. char *get_remote_object_url(const char *url, const char *hex,
  1394. int only_two_digit_prefix)
  1395. {
  1396. struct strbuf buf = STRBUF_INIT;
  1397. append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
  1398. return strbuf_detach(&buf, NULL);
  1399. }
  1400. void normalize_curl_result(CURLcode *result, long http_code,
  1401. char *errorstr, size_t errorlen)
  1402. {
  1403. /*
  1404. * If we see a failing http code with CURLE_OK, we have turned off
  1405. * FAILONERROR (to keep the server's custom error response), and should
  1406. * translate the code into failure here.
  1407. *
  1408. * Likewise, if we see a redirect (30x code), that means we turned off
  1409. * redirect-following, and we should treat the result as an error.
  1410. */
  1411. if (*result == CURLE_OK && http_code >= 300) {
  1412. *result = CURLE_HTTP_RETURNED_ERROR;
  1413. /*
  1414. * Normally curl will already have put the "reason phrase"
  1415. * from the server into curl_errorstr; unfortunately without
  1416. * FAILONERROR it is lost, so we can give only the numeric
  1417. * status code.
  1418. */
  1419. xsnprintf(errorstr, errorlen,
  1420. "The requested URL returned error: %ld",
  1421. http_code);
  1422. }
  1423. }
  1424. static int handle_curl_result(struct slot_results *results)
  1425. {
  1426. normalize_curl_result(&results->curl_result, results->http_code,
  1427. curl_errorstr, sizeof(curl_errorstr));
  1428. if (results->curl_result == CURLE_OK) {
  1429. credential_approve(&http_auth);
  1430. if (proxy_auth.password)
  1431. credential_approve(&proxy_auth);
  1432. return HTTP_OK;
  1433. } else if (missing_target(results))
  1434. return HTTP_MISSING_TARGET;
  1435. else if (results->http_code == 401) {
  1436. if (http_auth.username && http_auth.password) {
  1437. credential_reject(&http_auth);
  1438. return HTTP_NOAUTH;
  1439. } else {
  1440. #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
  1441. http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
  1442. if (results->auth_avail) {
  1443. http_auth_methods &= results->auth_avail;
  1444. http_auth_methods_restricted = 1;
  1445. }
  1446. #endif
  1447. return HTTP_REAUTH;
  1448. }
  1449. } else {
  1450. if (results->http_connectcode == 407)
  1451. credential_reject(&proxy_auth);
  1452. #if LIBCURL_VERSION_NUM >= 0x070c00
  1453. if (!curl_errorstr[0])
  1454. strlcpy(curl_errorstr,
  1455. curl_easy_strerror(results->curl_result),
  1456. sizeof(curl_errorstr));
  1457. #endif
  1458. return HTTP_ERROR;
  1459. }
  1460. }
  1461. int run_one_slot(struct active_request_slot *slot,
  1462. struct slot_results *results)
  1463. {
  1464. slot->results = results;
  1465. if (!start_active_slot(slot)) {
  1466. xsnprintf(curl_errorstr, sizeof(curl_errorstr),
  1467. "failed to start HTTP request");
  1468. return HTTP_START_FAILED;
  1469. }
  1470. run_active_slot(slot);
  1471. return handle_curl_result(results);
  1472. }
  1473. struct curl_slist *http_copy_default_headers(void)
  1474. {
  1475. struct curl_slist *headers = NULL;
  1476. const struct string_list_item *item;
  1477. for_each_string_list_item(item, &extra_http_headers)
  1478. headers = curl_slist_append(headers, item->string);
  1479. return headers;
  1480. }
  1481. static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
  1482. {
  1483. char *ptr;
  1484. CURLcode ret;
  1485. strbuf_reset(buf);
  1486. ret = curl_easy_getinfo(curl, info, &ptr);
  1487. if (!ret && ptr)
  1488. strbuf_addstr(buf, ptr);
  1489. return ret;
  1490. }
  1491. /*
  1492. * Check for and extract a content-type parameter. "raw"
  1493. * should be positioned at the start of the potential
  1494. * parameter, with any whitespace already removed.
  1495. *
  1496. * "name" is the name of the parameter. The value is appended
  1497. * to "out".
  1498. */
  1499. static int extract_param(const char *raw, const char *name,
  1500. struct strbuf *out)
  1501. {
  1502. size_t len = strlen(name);
  1503. if (strncasecmp(raw, name, len))
  1504. return -1;
  1505. raw += len;
  1506. if (*raw != '=')
  1507. return -1;
  1508. raw++;
  1509. while (*raw && !isspace(*raw) && *raw != ';')
  1510. strbuf_addch(out, *raw++);
  1511. return 0;
  1512. }
  1513. /*
  1514. * Extract a normalized version of the content type, with any
  1515. * spaces suppressed, all letters lowercased, and no trailing ";"
  1516. * or parameters.
  1517. *
  1518. * Note that we will silently remove even invalid whitespace. For
  1519. * example, "text / plain" is specifically forbidden by RFC 2616,
  1520. * but "text/plain" is the only reasonable output, and this keeps
  1521. * our code simple.
  1522. *
  1523. * If the "charset" argument is not NULL, store the value of any
  1524. * charset parameter there.
  1525. *
  1526. * Example:
  1527. * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
  1528. * "text / plain" -> "text/plain"
  1529. */
  1530. static void extract_content_type(struct strbuf *raw, struct strbuf *type,
  1531. struct strbuf *charset)
  1532. {
  1533. const char *p;
  1534. strbuf_reset(type);
  1535. strbuf_grow(type, raw->len);
  1536. for (p = raw->buf; *p; p++) {
  1537. if (isspace(*p))
  1538. continue;
  1539. if (*p == ';') {
  1540. p++;
  1541. break;
  1542. }
  1543. strbuf_addch(type, tolower(*p));
  1544. }
  1545. if (!charset)
  1546. return;
  1547. strbuf_reset(charset);
  1548. while (*p) {
  1549. while (isspace(*p) || *p == ';')
  1550. p++;
  1551. if (!extract_param(p, "charset", charset))
  1552. return;
  1553. while (*p && !isspace(*p))
  1554. p++;
  1555. }
  1556. if (!charset->len && starts_with(type->buf, "text/"))
  1557. strbuf_addstr(charset, "ISO-8859-1");
  1558. }
  1559. static void write_accept_language(struct strbuf *buf)
  1560. {
  1561. /*
  1562. * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
  1563. * that, q-value will be smaller than 0.001, the minimum q-value the
  1564. * HTTP specification allows. See
  1565. * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
  1566. */
  1567. const int MAX_DECIMAL_PLACES = 3;
  1568. const int MAX_LANGUAGE_TAGS = 1000;
  1569. const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
  1570. char **language_tags = NULL;
  1571. int num_langs = 0;
  1572. const char *s = get_preferred_languages();
  1573. int i;
  1574. struct strbuf tag = STRBUF_INIT;
  1575. /* Don't add Accept-Language header if no language is preferred. */
  1576. if (!s)
  1577. return;
  1578. /*
  1579. * Split the colon-separated string of preferred languages into
  1580. * language_tags array.
  1581. */
  1582. do {
  1583. /* collect language tag */
  1584. for (; *s && (isalnum(*s) || *s == '_'); s++)
  1585. strbuf_addch(&tag, *s == '_' ? '-' : *s);
  1586. /* skip .codeset, @modifier and any other unnecessary parts */
  1587. while (*s && *s != ':')
  1588. s++;
  1589. if (tag.len) {
  1590. num_langs++;
  1591. REALLOC_ARRAY(language_tags, num_langs);
  1592. language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
  1593. if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
  1594. break;
  1595. }
  1596. } while (*s++);
  1597. /* write Accept-Language header into buf */
  1598. if (num_langs) {
  1599. int last_buf_len = 0;
  1600. int max_q;
  1601. int decimal_places;
  1602. char q_format[32];
  1603. /* add '*' */
  1604. REALLOC_ARRAY(language_tags, num_langs + 1);
  1605. language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
  1606. /* compute decimal_places */
  1607. for (max_q = 1, decimal_places = 0;
  1608. max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
  1609. decimal_places++, max_q *= 10)
  1610. ;
  1611. xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
  1612. strbuf_addstr(buf, "Accept-Language: ");
  1613. for (i = 0; i < num_langs; i++) {
  1614. if (i > 0)
  1615. strbuf_addstr(buf, ", ");
  1616. strbuf_addstr(buf, language_tags[i]);
  1617. if (i > 0)
  1618. strbuf_addf(buf, q_format, max_q - i);
  1619. if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
  1620. strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
  1621. break;
  1622. }
  1623. last_buf_len = buf->len;
  1624. }
  1625. }
  1626. /* free language tags -- last one is a static '*' */
  1627. for (i = 0; i < num_langs - 1; i++)
  1628. free(language_tags[i]);
  1629. free(language_tags);
  1630. }
  1631. /*
  1632. * Get an Accept-Language header which indicates user's preferred languages.
  1633. *
  1634. * Examples:
  1635. * LANGUAGE= -> ""
  1636. * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
  1637. * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
  1638. * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
  1639. * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
  1640. * LANGUAGE= LANG=C -> ""
  1641. */
  1642. static const char *get_accept_language(void)
  1643. {
  1644. if (!cached_accept_language) {
  1645. struct strbuf buf = STRBUF_INIT;
  1646. write_accept_language(&buf);
  1647. if (buf.len > 0)
  1648. cached_accept_language = strbuf_detach(&buf, NULL);
  1649. }
  1650. return cached_accept_language;
  1651. }
  1652. static void http_opt_request_remainder(CURL *curl, off_t pos)
  1653. {
  1654. char buf[128];
  1655. xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
  1656. curl_easy_setopt(curl, CURLOPT_RANGE, buf);
  1657. }
  1658. /* http_request() targets */
  1659. #define HTTP_REQUEST_STRBUF 0
  1660. #define HTTP_REQUEST_FILE 1
  1661. static int http_request(const char *url,
  1662. void *result, int target,
  1663. const struct http_get_options *options)
  1664. {
  1665. struct active_request_slot *slot;
  1666. struct slot_results results;
  1667. struct curl_slist *headers = http_copy_default_headers();
  1668. struct strbuf buf = STRBUF_INIT;
  1669. const char *accept_language;
  1670. int ret;
  1671. slot = get_active_slot();
  1672. curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
  1673. if (result == NULL) {
  1674. curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
  1675. } else {
  1676. curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
  1677. curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
  1678. if (target == HTTP_REQUEST_FILE) {
  1679. off_t posn = ftello(result);
  1680. curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
  1681. fwrite);
  1682. if (posn > 0)
  1683. http_opt_request_remainder(slot->curl, posn);
  1684. } else
  1685. curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
  1686. fwrite_buffer);
  1687. }
  1688. accept_language = get_accept_language();
  1689. if (accept_language)
  1690. headers = curl_slist_append(headers, accept_language);
  1691. strbuf_addstr(&buf, "Pragma:");
  1692. if (options && options->no_cache)
  1693. strbuf_addstr(&buf, " no-cache");
  1694. if (options && options->initial_request &&
  1695. http_follow_config == HTTP_FOLLOW_INITIAL)
  1696. curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
  1697. headers = curl_slist_append(headers, buf.buf);
  1698. /* Add additional headers here */
  1699. if (options && options->extra_headers) {
  1700. const struct string_list_item *item;
  1701. for_each_string_list_item(item, options->extra_headers) {
  1702. headers = curl_slist_append(headers, item->string);
  1703. }
  1704. }
  1705. curl_easy_setopt(slot->curl, CURLOPT_URL, url);
  1706. curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
  1707. curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
  1708. curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
  1709. ret = run_one_slot(slot, &results);
  1710. if (options && options->content_type) {
  1711. struct strbuf raw = STRBUF_INIT;
  1712. curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
  1713. extract_content_type(&raw, options->content_type,
  1714. options->charset);
  1715. strbuf_release(&raw);
  1716. }
  1717. if (options && options->effective_url)
  1718. curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
  1719. options->effective_url);
  1720. curl_slist_free_all(headers);
  1721. strbuf_release(&buf);
  1722. return ret;
  1723. }
  1724. /*
  1725. * Update the "base" url to a more appropriate value, as deduced by
  1726. * redirects seen when requesting a URL starting with "url".
  1727. *
  1728. * The "asked" parameter is a URL that we asked curl to access, and must begin
  1729. * with "base".
  1730. *
  1731. * The "got" parameter is the URL that curl reported to us as where we ended
  1732. * up.
  1733. *
  1734. * Returns 1 if we updated the base url, 0 otherwise.
  1735. *
  1736. * Our basic strategy is to compare "base" and "asked" to find the bits
  1737. * specific to our request. We then strip those bits off of "got" to yield the
  1738. * new base. So for example, if our base is "http://example.com/foo.git",
  1739. * and we ask for "http://example.com/foo.git/info/refs", we might end up
  1740. * with "https://other.example.com/foo.git/info/refs". We would want the
  1741. * new URL to become "https://other.example.com/foo.git".
  1742. *
  1743. * Note that this assumes a sane redirect scheme. It's entirely possible
  1744. * in the example above to end up at a URL that does not even end in
  1745. * "info/refs". In such a case we die. There's not much we can do, such a
  1746. * scheme is unlikely to represent a real git repository, and failing to
  1747. * rewrite the base opens options for malicious redirects to do funny things.
  1748. */
  1749. static int update_url_from_redirect(struct strbuf *base,
  1750. const char *asked,
  1751. const struct strbuf *got)
  1752. {
  1753. const char *tail;
  1754. size_t new_len;
  1755. if (!strcmp(asked, got->buf))
  1756. return 0;
  1757. if (!skip_prefix(asked, base->buf, &tail))
  1758. BUG("update_url_from_redirect: %s is not a superset of %s",
  1759. asked, base->buf);
  1760. new_len = got->len;
  1761. if (!strip_suffix_mem(got->buf, &new_len, tail))
  1762. die(_("unable to update url base from redirection:\n"
  1763. " asked for: %s\n"
  1764. " redirect: %s"),
  1765. asked, got->buf);
  1766. strbuf_reset(base);
  1767. strbuf_add(base, got->buf, new_len);
  1768. return 1;
  1769. }
  1770. static int http_request_reauth(const char *url,
  1771. void *result, int target,
  1772. struct http_get_options *options)
  1773. {
  1774. int ret = http_request(url, result, target, options);
  1775. if (ret != HTTP_OK && ret != HTTP_REAUTH)
  1776. return ret;
  1777. if (options && options->effective_url && options->base_url) {
  1778. if (update_url_from_redirect(options->base_url,
  1779. url, options->effective_url)) {
  1780. credential_from_url(&http_auth, options->base_url->buf);
  1781. url = options->effective_url->buf;
  1782. }
  1783. }
  1784. if (ret != HTTP_REAUTH)
  1785. return ret;
  1786. /*
  1787. * The previous request may have put cruft into our output stream; we
  1788. * should clear it out before making our next request.
  1789. */
  1790. switch (target) {
  1791. case HTTP_REQUEST_STRBUF:
  1792. strbuf_reset(result);
  1793. break;
  1794. case HTTP_REQUEST_FILE:
  1795. if (fflush(result)) {
  1796. error_errno("unable to flush a file");
  1797. return HTTP_START_FAILED;
  1798. }
  1799. rewind(result);
  1800. if (ftruncate(fileno(result), 0) < 0) {
  1801. error_errno("unable to truncate a file");
  1802. return HTTP_START_FAILED;
  1803. }
  1804. break;
  1805. default:
  1806. BUG("Unknown http_request target");
  1807. }
  1808. credential_fill(&http_auth);
  1809. return http_request(url, result, target, options);
  1810. }
  1811. int http_get_strbuf(const char *url,
  1812. struct strbuf *result,
  1813. struct http_get_options *options)
  1814. {
  1815. return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
  1816. }
  1817. /*
  1818. * Downloads a URL and stores the result in the given file.
  1819. *
  1820. * If a previous interrupted download is detected (i.e. a previous temporary
  1821. * file is still around) the download is resumed.
  1822. */
  1823. static int http_get_file(const char *url, const char *filename,
  1824. struct http_get_options *options)
  1825. {
  1826. int ret;
  1827. struct strbuf tmpfile = STRBUF_INIT;
  1828. FILE *result;
  1829. strbuf_addf(&tmpfile, "%s.temp", filename);
  1830. result = fopen(tmpfile.buf, "a");
  1831. if (!result) {
  1832. error("Unable to open local file %s", tmpfile.buf);
  1833. ret = HTTP_ERROR;
  1834. goto cleanup;
  1835. }
  1836. ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
  1837. fclose(result);
  1838. if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
  1839. ret = HTTP_ERROR;
  1840. cleanup:
  1841. strbuf_release(&tmpfile);
  1842. return ret;
  1843. }
  1844. int http_fetch_ref(const char *base, struct ref *ref)
  1845. {
  1846. struct http_get_options options = {0};
  1847. char *url;
  1848. struct strbuf buffer = STRBUF_INIT;
  1849. int ret = -1;
  1850. options.no_cache = 1;
  1851. url = quote_ref_url(base, ref->name);
  1852. if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
  1853. strbuf_rtrim(&buffer);
  1854. if (buffer.len == the_hash_algo->hexsz)
  1855. ret = get_oid_hex(buffer.buf, &ref->old_oid);
  1856. else if (starts_with(buffer.buf, "ref: ")) {
  1857. ref->symref = xstrdup(buffer.buf + 5);
  1858. ret = 0;
  1859. }
  1860. }
  1861. strbuf_release(&buffer);
  1862. free(url);
  1863. return ret;
  1864. }
  1865. /* Helpers for fetching packs */
  1866. static char *fetch_pack_index(unsigned char *hash, const char *base_url)
  1867. {
  1868. char *url, *tmp;
  1869. struct strbuf buf = STRBUF_INIT;
  1870. if (http_is_verbose)
  1871. fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
  1872. end_url_with_slash(&buf, base_url);
  1873. strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
  1874. url = strbuf_detach(&buf, NULL);
  1875. strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
  1876. tmp = strbuf_detach(&buf, NULL);
  1877. if (http_get_file(url, tmp, NULL) != HTTP_OK) {
  1878. error("Unable to get pack index %s", url);
  1879. FREE_AND_NULL(tmp);
  1880. }
  1881. free(url);
  1882. return tmp;
  1883. }
  1884. static int fetch_and_setup_pack_index(struct packed_git **packs_head,
  1885. unsigned char *sha1, const char *base_url)
  1886. {
  1887. struct packed_git *new_pack;
  1888. char *tmp_idx = NULL;
  1889. int ret;
  1890. if (has_pack_index(sha1)) {
  1891. new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
  1892. if (!new_pack)
  1893. return -1; /* parse_pack_index() already issued error message */
  1894. goto add_pack;
  1895. }
  1896. tmp_idx = fetch_pack_index(sha1, base_url);
  1897. if (!tmp_idx)
  1898. return -1;
  1899. new_pack = parse_pack_index(sha1, tmp_idx);
  1900. if (!new_pack) {
  1901. unlink(tmp_idx);
  1902. free(tmp_idx);
  1903. return -1; /* parse_pack_index() already issued error message */
  1904. }
  1905. ret = verify_pack_index(new_pack);
  1906. if (!ret) {
  1907. close_pack_index(new_pack);
  1908. ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
  1909. }
  1910. free(tmp_idx);
  1911. if (ret)
  1912. return -1;
  1913. add_pack:
  1914. new_pack->next = *packs_head;
  1915. *packs_head = new_pack;
  1916. return 0;
  1917. }
  1918. int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
  1919. {
  1920. struct http_get_options options = {0};
  1921. int ret = 0;
  1922. char *url;
  1923. const char *data;
  1924. struct strbuf buf = STRBUF_INIT;
  1925. struct object_id oid;
  1926. end_url_with_slash(&buf, base_url);
  1927. strbuf_addstr(&buf, "objects/info/packs");
  1928. url = strbuf_detach(&buf, NULL);
  1929. options.no_cache = 1;
  1930. ret = http_get_strbuf(url, &buf, &options);
  1931. if (ret != HTTP_OK)
  1932. goto cleanup;
  1933. data = buf.buf;
  1934. while (*data) {
  1935. if (skip_prefix(data, "P pack-", &data) &&
  1936. !parse_oid_hex(data, &oid, &data) &&
  1937. skip_prefix(data, ".pack", &data) &&
  1938. (*data == '\n' || *data == '\0')) {
  1939. fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
  1940. } else {
  1941. data = strchrnul(data, '\n');
  1942. }
  1943. if (*data)
  1944. data++; /* skip past newline */
  1945. }
  1946. cleanup:
  1947. free(url);
  1948. return ret;
  1949. }
  1950. void release_http_pack_request(struct http_pack_request *preq)
  1951. {
  1952. if (preq->packfile != NULL) {
  1953. fclose(preq->packfile);
  1954. preq->packfile = NULL;
  1955. }
  1956. preq->slot = NULL;
  1957. strbuf_release(&preq->tmpfile);
  1958. free(preq->url);
  1959. free(preq);
  1960. }
  1961. int finish_http_pack_request(struct http_pack_request *preq)
  1962. {
  1963. struct child_process ip = CHILD_PROCESS_INIT;
  1964. int tmpfile_fd;
  1965. int ret = 0;
  1966. fclose(preq->packfile);
  1967. preq->packfile = NULL;
  1968. tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
  1969. strvec_push(&ip.args, "index-pack");
  1970. strvec_push(&ip.args, "--stdin");
  1971. ip.git_cmd = 1;
  1972. ip.in = tmpfile_fd;
  1973. if (preq->generate_keep) {
  1974. strvec_pushf(&ip.args, "--keep=git %"PRIuMAX,
  1975. (uintmax_t)getpid());
  1976. ip.out = 0;
  1977. } else {
  1978. ip.no_stdout = 1;
  1979. }
  1980. if (run_command(&ip)) {
  1981. ret = -1;
  1982. goto cleanup;
  1983. }
  1984. cleanup:
  1985. close(tmpfile_fd);
  1986. unlink(preq->tmpfile.buf);
  1987. return ret;
  1988. }
  1989. void http_install_packfile(struct packed_git *p,
  1990. struct packed_git **list_to_remove_from)
  1991. {
  1992. struct packed_git **lst = list_to_remove_from;
  1993. while (*lst != p)
  1994. lst = &((*lst)->next);
  1995. *lst = (*lst)->next;
  1996. install_packed_git(the_repository, p);
  1997. }
  1998. struct http_pack_request *new_http_pack_request(
  1999. const unsigned char *packed_git_hash, const char *base_url) {
  2000. struct strbuf buf = STRBUF_INIT;
  2001. end_url_with_slash(&buf, base_url);
  2002. strbuf_addf(&buf, "objects/pack/pack-%s.pack",
  2003. hash_to_hex(packed_git_hash));
  2004. return new_direct_http_pack_request(packed_git_hash,
  2005. strbuf_detach(&buf, NULL));
  2006. }
  2007. struct http_pack_request *new_direct_http_pack_request(
  2008. const unsigned char *packed_git_hash, char *url)
  2009. {
  2010. off_t prev_posn = 0;
  2011. struct http_pack_request *preq;
  2012. preq = xcalloc(1, sizeof(*preq));
  2013. strbuf_init(&preq->tmpfile, 0);
  2014. preq->url = url;
  2015. strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
  2016. preq->packfile = fopen(preq->tmpfile.buf, "a");
  2017. if (!preq->packfile) {
  2018. error("Unable to open local file %s for pack",
  2019. preq->tmpfile.buf);
  2020. goto abort;
  2021. }
  2022. preq->slot = get_active_slot();
  2023. curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
  2024. curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
  2025. curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
  2026. curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
  2027. no_pragma_header);
  2028. /*
  2029. * If there is data present from a previous transfer attempt,
  2030. * resume where it left off
  2031. */
  2032. prev_posn = ftello(preq->packfile);
  2033. if (prev_posn>0) {
  2034. if (http_is_verbose)
  2035. fprintf(stderr,
  2036. "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
  2037. hash_to_hex(packed_git_hash),
  2038. (uintmax_t)prev_posn);
  2039. http_opt_request_remainder(preq->slot->curl, prev_posn);
  2040. }
  2041. return preq;
  2042. abort:
  2043. strbuf_release(&preq->tmpfile);
  2044. free(preq->url);
  2045. free(preq);
  2046. return NULL;
  2047. }
  2048. /* Helpers for fetching objects (loose) */
  2049. static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
  2050. void *data)
  2051. {
  2052. unsigned char expn[4096];
  2053. size_t size = eltsize * nmemb;
  2054. int posn = 0;
  2055. struct http_object_request *freq = data;
  2056. struct active_request_slot *slot = freq->slot;
  2057. if (slot) {
  2058. CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
  2059. &slot->http_code);
  2060. if (c != CURLE_OK)
  2061. BUG("curl_easy_getinfo for HTTP code failed: %s",
  2062. curl_easy_strerror(c));
  2063. if (slot->http_code >= 300)
  2064. return nmemb;
  2065. }
  2066. do {
  2067. ssize_t retval = xwrite(freq->localfile,
  2068. (char *) ptr + posn, size - posn);
  2069. if (retval < 0)
  2070. return posn / eltsize;
  2071. posn += retval;
  2072. } while (posn < size);
  2073. freq->stream.avail_in = size;
  2074. freq->stream.next_in = (void *)ptr;
  2075. do {
  2076. freq->stream.next_out = expn;
  2077. freq->stream.avail_out = sizeof(expn);
  2078. freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
  2079. the_hash_algo->update_fn(&freq->c, expn,
  2080. sizeof(expn) - freq->stream.avail_out);
  2081. } while (freq->stream.avail_in && freq->zret == Z_OK);
  2082. return nmemb;
  2083. }
  2084. struct http_object_request *new_http_object_request(const char *base_url,
  2085. const struct object_id *oid)
  2086. {
  2087. char *hex = oid_to_hex(oid);
  2088. struct strbuf filename = STRBUF_INIT;
  2089. struct strbuf prevfile = STRBUF_INIT;
  2090. int prevlocal;
  2091. char prev_buf[PREV_BUF_SIZE];
  2092. ssize_t prev_read = 0;
  2093. off_t prev_posn = 0;
  2094. struct http_object_request *freq;
  2095. freq = xcalloc(1, sizeof(*freq));
  2096. strbuf_init(&freq->tmpfile, 0);
  2097. oidcpy(&freq->oid, oid);
  2098. freq->localfile = -1;
  2099. loose_object_path(the_repository, &filename, oid);
  2100. strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
  2101. strbuf_addf(&prevfile, "%s.prev", filename.buf);
  2102. unlink_or_warn(prevfile.buf);
  2103. rename(freq->tmpfile.buf, prevfile.buf);
  2104. unlink_or_warn(freq->tmpfile.buf);
  2105. strbuf_release(&filename);
  2106. if (freq->localfile != -1)
  2107. error("fd leakage in start: %d", freq->localfile);
  2108. freq->localfile = open(freq->tmpfile.buf,
  2109. O_WRONLY | O_CREAT | O_EXCL, 0666);
  2110. /*
  2111. * This could have failed due to the "lazy directory creation";
  2112. * try to mkdir the last path component.
  2113. */
  2114. if (freq->localfile < 0 && errno == ENOENT) {
  2115. char *dir = strrchr(freq->tmpfile.buf, '/');
  2116. if (dir) {
  2117. *dir = 0;
  2118. mkdir(freq->tmpfile.buf, 0777);
  2119. *dir = '/';
  2120. }
  2121. freq->localfile = open(freq->tmpfile.buf,
  2122. O_WRONLY | O_CREAT | O_EXCL, 0666);
  2123. }
  2124. if (freq->localfile < 0) {
  2125. error_errno("Couldn't create temporary file %s",
  2126. freq->tmpfile.buf);
  2127. goto abort;
  2128. }
  2129. git_inflate_init(&freq->stream);
  2130. the_hash_algo->init_fn(&freq->c);
  2131. freq->url = get_remote_object_url(base_url, hex, 0);
  2132. /*
  2133. * If a previous temp file is present, process what was already
  2134. * fetched.
  2135. */
  2136. prevlocal = open(prevfile.buf, O_RDONLY);
  2137. if (prevlocal != -1) {
  2138. do {
  2139. prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
  2140. if (prev_read>0) {
  2141. if (fwrite_sha1_file(prev_buf,
  2142. 1,
  2143. prev_read,
  2144. freq) == prev_read) {
  2145. prev_posn += prev_read;
  2146. } else {
  2147. prev_read = -1;
  2148. }
  2149. }
  2150. } while (prev_read > 0);
  2151. close(prevlocal);
  2152. }
  2153. unlink_or_warn(prevfile.buf);
  2154. strbuf_release(&prevfile);
  2155. /*
  2156. * Reset inflate/SHA1 if there was an error reading the previous temp
  2157. * file; also rewind to the beginning of the local file.
  2158. */
  2159. if (prev_read == -1) {
  2160. memset(&freq->stream, 0, sizeof(freq->stream));
  2161. git_inflate_init(&freq->stream);
  2162. the_hash_algo->init_fn(&freq->c);
  2163. if (prev_posn>0) {
  2164. prev_posn = 0;
  2165. lseek(freq->localfile, 0, SEEK_SET);
  2166. if (ftruncate(freq->localfile, 0) < 0) {
  2167. error_errno("Couldn't truncate temporary file %s",
  2168. freq->tmpfile.buf);
  2169. goto abort;
  2170. }
  2171. }
  2172. }
  2173. freq->slot = get_active_slot();
  2174. curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
  2175. curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
  2176. curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
  2177. curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
  2178. curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
  2179. curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
  2180. /*
  2181. * If we have successfully processed data from a previous fetch
  2182. * attempt, only fetch the data we don't already have.
  2183. */
  2184. if (prev_posn>0) {
  2185. if (http_is_verbose)
  2186. fprintf(stderr,
  2187. "Resuming fetch of object %s at byte %"PRIuMAX"\n",
  2188. hex, (uintmax_t)prev_posn);
  2189. http_opt_request_remainder(freq->slot->curl, prev_posn);
  2190. }
  2191. return freq;
  2192. abort:
  2193. strbuf_release(&prevfile);
  2194. free(freq->url);
  2195. free(freq);
  2196. return NULL;
  2197. }
  2198. void process_http_object_request(struct http_object_request *freq)
  2199. {
  2200. if (freq->slot == NULL)
  2201. return;
  2202. freq->curl_result = freq->slot->curl_result;
  2203. freq->http_code = freq->slot->http_code;
  2204. freq->slot = NULL;
  2205. }
  2206. int finish_http_object_request(struct http_object_request *freq)
  2207. {
  2208. struct stat st;
  2209. struct strbuf filename = STRBUF_INIT;
  2210. close(freq->localfile);
  2211. freq->localfile = -1;
  2212. process_http_object_request(freq);
  2213. if (freq->http_code == 416) {
  2214. warning("requested range invalid; we may already have all the data.");
  2215. } else if (freq->curl_result != CURLE_OK) {
  2216. if (stat(freq->tmpfile.buf, &st) == 0)
  2217. if (st.st_size == 0)
  2218. unlink_or_warn(freq->tmpfile.buf);
  2219. return -1;
  2220. }
  2221. git_inflate_end(&freq->stream);
  2222. the_hash_algo->final_fn(freq->real_oid.hash, &freq->c);
  2223. if (freq->zret != Z_STREAM_END) {
  2224. unlink_or_warn(freq->tmpfile.buf);
  2225. return -1;
  2226. }
  2227. if (!oideq(&freq->oid, &freq->real_oid)) {
  2228. unlink_or_warn(freq->tmpfile.buf);
  2229. return -1;
  2230. }
  2231. loose_object_path(the_repository, &filename, &freq->oid);
  2232. freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
  2233. strbuf_release(&filename);
  2234. return freq->rename;
  2235. }
  2236. void abort_http_object_request(struct http_object_request *freq)
  2237. {
  2238. unlink_or_warn(freq->tmpfile.buf);
  2239. release_http_object_request(freq);
  2240. }
  2241. void release_http_object_request(struct http_object_request *freq)
  2242. {
  2243. if (freq->localfile != -1) {
  2244. close(freq->localfile);
  2245. freq->localfile = -1;
  2246. }
  2247. FREE_AND_NULL(freq->url);
  2248. if (freq->slot != NULL) {
  2249. freq->slot->callback_func = NULL;
  2250. freq->slot->callback_data = NULL;
  2251. release_active_slot(freq->slot);
  2252. freq->slot = NULL;
  2253. }
  2254. strbuf_release(&freq->tmpfile);
  2255. }