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