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