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