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