1 #include "git-compat-util.h"
5 #include "run-command.h"
8 #include "credential.h"
12 #include "transport.h"
16 size_t http_post_buffer
= 16 * LARGE_PACKET_MAX
;
18 #if LIBCURL_VERSION_NUM >= 0x070a06
19 #define LIBCURL_CAN_HANDLE_AUTH_ANY
22 static int min_curl_sessions
= 1;
23 static int curl_session_count
;
25 static int max_requests
= -1;
28 #ifndef NO_CURL_EASY_DUPHANDLE
29 static CURL
*curl_default
;
32 #define PREV_BUF_SIZE 4096
33 #define RANGE_HEADER_SIZE 30
35 char curl_errorstr
[CURL_ERROR_SIZE
];
37 static int curl_ssl_verify
= -1;
38 static int curl_ssl_try
;
39 static const char *ssl_cert
;
40 static const char *ssl_cipherlist
;
41 static const char *ssl_version
;
46 { "sslv2", CURL_SSLVERSION_SSLv2
},
47 { "sslv3", CURL_SSLVERSION_SSLv3
},
48 { "tlsv1", CURL_SSLVERSION_TLSv1
},
49 #if LIBCURL_VERSION_NUM >= 0x072200
50 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0
},
51 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1
},
52 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2
},
55 #if LIBCURL_VERSION_NUM >= 0x070903
56 static const char *ssl_key
;
58 #if LIBCURL_VERSION_NUM >= 0x070908
59 static const char *ssl_capath
;
61 static const char *ssl_cainfo
;
62 static long curl_low_speed_limit
= -1;
63 static long curl_low_speed_time
= -1;
64 static int curl_ftp_no_epsv
;
65 static const char *curl_http_proxy
;
66 static const char *curl_cookie_file
;
67 static int curl_save_cookies
;
68 struct credential http_auth
= CREDENTIAL_INIT
;
69 static int http_proactive_auth
;
70 static const char *user_agent
;
72 #if LIBCURL_VERSION_NUM >= 0x071700
73 /* Use CURLOPT_KEYPASSWD as is */
74 #elif LIBCURL_VERSION_NUM >= 0x070903
75 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
77 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
80 static struct credential cert_auth
= CREDENTIAL_INIT
;
81 static int ssl_cert_password_required
;
82 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
83 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
86 static struct curl_slist
*pragma_header
;
87 static struct curl_slist
*no_pragma_header
;
89 static struct active_request_slot
*active_queue_head
;
91 static char *cached_accept_language
;
93 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
95 size_t size
= eltsize
* nmemb
;
96 struct buffer
*buffer
= buffer_
;
98 if (size
> buffer
->buf
.len
- buffer
->posn
)
99 size
= buffer
->buf
.len
- buffer
->posn
;
100 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
101 buffer
->posn
+= size
;
106 #ifndef NO_CURL_IOCTL
107 curlioerr
ioctl_buffer(CURL
*handle
, int cmd
, void *clientp
)
109 struct buffer
*buffer
= clientp
;
115 case CURLIOCMD_RESTARTREAD
:
120 return CURLIOE_UNKNOWNCMD
;
125 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
127 size_t size
= eltsize
* nmemb
;
128 struct strbuf
*buffer
= buffer_
;
130 strbuf_add(buffer
, ptr
, size
);
134 size_t fwrite_null(char *ptr
, size_t eltsize
, size_t nmemb
, void *strbuf
)
136 return eltsize
* nmemb
;
139 static void closedown_active_slot(struct active_request_slot
*slot
)
145 static void finish_active_slot(struct active_request_slot
*slot
)
147 closedown_active_slot(slot
);
148 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
150 if (slot
->finished
!= NULL
)
151 (*slot
->finished
) = 1;
153 /* Store slot results so they can be read after the slot is reused */
154 if (slot
->results
!= NULL
) {
155 slot
->results
->curl_result
= slot
->curl_result
;
156 slot
->results
->http_code
= slot
->http_code
;
157 #if LIBCURL_VERSION_NUM >= 0x070a08
158 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
159 &slot
->results
->auth_avail
);
161 slot
->results
->auth_avail
= 0;
165 /* Run callback if appropriate */
166 if (slot
->callback_func
!= NULL
)
167 slot
->callback_func(slot
->callback_data
);
170 #ifdef USE_CURL_MULTI
171 static void process_curl_messages(void)
174 struct active_request_slot
*slot
;
175 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
177 while (curl_message
!= NULL
) {
178 if (curl_message
->msg
== CURLMSG_DONE
) {
179 int curl_result
= curl_message
->data
.result
;
180 slot
= active_queue_head
;
181 while (slot
!= NULL
&&
182 slot
->curl
!= curl_message
->easy_handle
)
185 curl_multi_remove_handle(curlm
, slot
->curl
);
186 slot
->curl_result
= curl_result
;
187 finish_active_slot(slot
);
189 fprintf(stderr
, "Received DONE message for unknown request!\n");
192 fprintf(stderr
, "Unknown CURL message received: %d\n",
193 (int)curl_message
->msg
);
195 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
200 static int http_options(const char *var
, const char *value
, void *cb
)
202 if (!strcmp("http.sslverify", var
)) {
203 curl_ssl_verify
= git_config_bool(var
, value
);
206 if (!strcmp("http.sslcipherlist", var
))
207 return git_config_string(&ssl_cipherlist
, var
, value
);
208 if (!strcmp("http.sslversion", var
))
209 return git_config_string(&ssl_version
, var
, value
);
210 if (!strcmp("http.sslcert", var
))
211 return git_config_string(&ssl_cert
, var
, value
);
212 #if LIBCURL_VERSION_NUM >= 0x070903
213 if (!strcmp("http.sslkey", var
))
214 return git_config_string(&ssl_key
, var
, value
);
216 #if LIBCURL_VERSION_NUM >= 0x070908
217 if (!strcmp("http.sslcapath", var
))
218 return git_config_pathname(&ssl_capath
, var
, value
);
220 if (!strcmp("http.sslcainfo", var
))
221 return git_config_pathname(&ssl_cainfo
, var
, value
);
222 if (!strcmp("http.sslcertpasswordprotected", var
)) {
223 ssl_cert_password_required
= git_config_bool(var
, value
);
226 if (!strcmp("http.ssltry", var
)) {
227 curl_ssl_try
= git_config_bool(var
, value
);
230 if (!strcmp("http.minsessions", var
)) {
231 min_curl_sessions
= git_config_int(var
, value
);
232 #ifndef USE_CURL_MULTI
233 if (min_curl_sessions
> 1)
234 min_curl_sessions
= 1;
238 #ifdef USE_CURL_MULTI
239 if (!strcmp("http.maxrequests", var
)) {
240 max_requests
= git_config_int(var
, value
);
244 if (!strcmp("http.lowspeedlimit", var
)) {
245 curl_low_speed_limit
= (long)git_config_int(var
, value
);
248 if (!strcmp("http.lowspeedtime", var
)) {
249 curl_low_speed_time
= (long)git_config_int(var
, value
);
253 if (!strcmp("http.noepsv", var
)) {
254 curl_ftp_no_epsv
= git_config_bool(var
, value
);
257 if (!strcmp("http.proxy", var
))
258 return git_config_string(&curl_http_proxy
, var
, value
);
260 if (!strcmp("http.cookiefile", var
))
261 return git_config_string(&curl_cookie_file
, var
, value
);
262 if (!strcmp("http.savecookies", var
)) {
263 curl_save_cookies
= git_config_bool(var
, value
);
267 if (!strcmp("http.postbuffer", var
)) {
268 http_post_buffer
= git_config_int(var
, value
);
269 if (http_post_buffer
< LARGE_PACKET_MAX
)
270 http_post_buffer
= LARGE_PACKET_MAX
;
274 if (!strcmp("http.useragent", var
))
275 return git_config_string(&user_agent
, var
, value
);
277 /* Fall back on the default ones */
278 return git_default_config(var
, value
, cb
);
281 static void init_curl_http_auth(CURL
*result
)
283 if (!http_auth
.username
)
286 credential_fill(&http_auth
);
288 #if LIBCURL_VERSION_NUM >= 0x071301
289 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
290 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
293 static struct strbuf up
= STRBUF_INIT
;
295 * Note that we assume we only ever have a single set of
296 * credentials in a given program run, so we do not have
297 * to worry about updating this buffer, only setting its
301 strbuf_addf(&up
, "%s:%s",
302 http_auth
.username
, http_auth
.password
);
303 curl_easy_setopt(result
, CURLOPT_USERPWD
, up
.buf
);
308 static int has_cert_password(void)
310 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
312 if (!cert_auth
.password
) {
313 cert_auth
.protocol
= xstrdup("cert");
314 cert_auth
.username
= xstrdup("");
315 cert_auth
.path
= xstrdup(ssl_cert
);
316 credential_fill(&cert_auth
);
321 #if LIBCURL_VERSION_NUM >= 0x071900
322 static void set_curl_keepalive(CURL
*c
)
324 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
327 #elif LIBCURL_VERSION_NUM >= 0x071000
328 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
332 socklen_t len
= (socklen_t
)sizeof(ka
);
334 if (type
!= CURLSOCKTYPE_IPCXN
)
337 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
339 warning("unable to set SO_KEEPALIVE on socket %s",
342 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
345 static void set_curl_keepalive(CURL
*c
)
347 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
351 static void set_curl_keepalive(CURL
*c
)
353 /* not supported on older curl versions */
357 static CURL
*get_curl_handle(void)
359 CURL
*result
= curl_easy_init();
360 long allowed_protocols
= 0;
363 die("curl_easy_init failed");
365 if (!curl_ssl_verify
) {
366 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
367 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
369 /* Verify authenticity of the peer's certificate */
370 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
371 /* The name in the cert must match whom we tried to connect */
372 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
375 #if LIBCURL_VERSION_NUM >= 0x070907
376 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
378 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
379 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
382 if (http_proactive_auth
)
383 init_curl_http_auth(result
);
385 if (getenv("GIT_SSL_VERSION"))
386 ssl_version
= getenv("GIT_SSL_VERSION");
387 if (ssl_version
&& *ssl_version
) {
389 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
390 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
391 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
392 sslversions
[i
].ssl_version
);
396 if (i
== ARRAY_SIZE(sslversions
))
397 warning("unsupported ssl version %s: using default",
401 if (getenv("GIT_SSL_CIPHER_LIST"))
402 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
403 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
404 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
407 if (ssl_cert
!= NULL
)
408 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
409 if (has_cert_password())
410 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
411 #if LIBCURL_VERSION_NUM >= 0x070903
413 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
415 #if LIBCURL_VERSION_NUM >= 0x070908
416 if (ssl_capath
!= NULL
)
417 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
419 if (ssl_cainfo
!= NULL
)
420 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
422 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
423 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
424 curl_low_speed_limit
);
425 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
426 curl_low_speed_time
);
429 curl_easy_setopt(result
, CURLOPT_FOLLOWLOCATION
, 1);
430 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
431 #if LIBCURL_VERSION_NUM >= 0x071301
432 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
433 #elif LIBCURL_VERSION_NUM >= 0x071101
434 curl_easy_setopt(result
, CURLOPT_POST301
, 1);
436 #if LIBCURL_VERSION_NUM >= 0x071304
437 if (is_transport_allowed("http"))
438 allowed_protocols
|= CURLPROTO_HTTP
;
439 if (is_transport_allowed("https"))
440 allowed_protocols
|= CURLPROTO_HTTPS
;
441 if (is_transport_allowed("ftp"))
442 allowed_protocols
|= CURLPROTO_FTP
;
443 if (is_transport_allowed("ftps"))
444 allowed_protocols
|= CURLPROTO_FTPS
;
445 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
, allowed_protocols
);
447 if (transport_restrict_protocols())
448 warning("protocol restrictions not applied to curl redirects because\n"
449 "your curl version is too old (>= 7.19.4)");
452 if (getenv("GIT_CURL_VERBOSE"))
453 curl_easy_setopt(result
, CURLOPT_VERBOSE
, 1);
455 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
456 user_agent
? user_agent
: git_user_agent());
458 if (curl_ftp_no_epsv
)
459 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
461 #ifdef CURLOPT_USE_SSL
463 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
466 if (curl_http_proxy
) {
467 curl_easy_setopt(result
, CURLOPT_PROXY
, curl_http_proxy
);
468 #if LIBCURL_VERSION_NUM >= 0x071800
469 if (starts_with(curl_http_proxy
, "socks5h"))
470 curl_easy_setopt(result
,
471 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5_HOSTNAME
);
472 else if (starts_with(curl_http_proxy
, "socks5"))
473 curl_easy_setopt(result
,
474 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
475 else if (starts_with(curl_http_proxy
, "socks4a"))
476 curl_easy_setopt(result
,
477 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
478 else if (starts_with(curl_http_proxy
, "socks"))
479 curl_easy_setopt(result
,
480 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
483 #if LIBCURL_VERSION_NUM >= 0x070a07
484 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
487 set_curl_keepalive(result
);
492 static void set_from_env(const char **var
, const char *envname
)
494 const char *val
= getenv(envname
);
499 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
501 char *low_speed_limit
;
502 char *low_speed_time
;
503 char *normalized_url
;
504 struct urlmatch_config config
= { STRING_LIST_INIT_DUP
};
506 config
.section
= "http";
508 config
.collect_fn
= http_options
;
509 config
.cascade_fn
= git_default_config
;
513 normalized_url
= url_normalize(url
, &config
.url
);
515 git_config(urlmatch_config_entry
, &config
);
516 free(normalized_url
);
518 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
519 die("curl_global_init failed");
521 http_proactive_auth
= proactive_auth
;
523 if (remote
&& remote
->http_proxy
)
524 curl_http_proxy
= xstrdup(remote
->http_proxy
);
526 pragma_header
= curl_slist_append(pragma_header
, "Pragma: no-cache");
527 no_pragma_header
= curl_slist_append(no_pragma_header
, "Pragma:");
529 #ifdef USE_CURL_MULTI
531 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
532 if (http_max_requests
!= NULL
)
533 max_requests
= atoi(http_max_requests
);
536 curlm
= curl_multi_init();
538 die("curl_multi_init failed");
541 if (getenv("GIT_SSL_NO_VERIFY"))
544 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
545 #if LIBCURL_VERSION_NUM >= 0x070903
546 set_from_env(&ssl_key
, "GIT_SSL_KEY");
548 #if LIBCURL_VERSION_NUM >= 0x070908
549 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
551 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
553 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
555 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
556 if (low_speed_limit
!= NULL
)
557 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
558 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
559 if (low_speed_time
!= NULL
)
560 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
562 if (curl_ssl_verify
== -1)
565 curl_session_count
= 0;
566 #ifdef USE_CURL_MULTI
567 if (max_requests
< 1)
568 max_requests
= DEFAULT_MAX_REQUESTS
;
571 if (getenv("GIT_CURL_FTP_NO_EPSV"))
572 curl_ftp_no_epsv
= 1;
575 credential_from_url(&http_auth
, url
);
576 if (!ssl_cert_password_required
&&
577 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
578 starts_with(url
, "https://"))
579 ssl_cert_password_required
= 1;
582 #ifndef NO_CURL_EASY_DUPHANDLE
583 curl_default
= get_curl_handle();
587 void http_cleanup(void)
589 struct active_request_slot
*slot
= active_queue_head
;
591 while (slot
!= NULL
) {
592 struct active_request_slot
*next
= slot
->next
;
593 if (slot
->curl
!= NULL
) {
594 #ifdef USE_CURL_MULTI
595 curl_multi_remove_handle(curlm
, slot
->curl
);
597 curl_easy_cleanup(slot
->curl
);
602 active_queue_head
= NULL
;
604 #ifndef NO_CURL_EASY_DUPHANDLE
605 curl_easy_cleanup(curl_default
);
608 #ifdef USE_CURL_MULTI
609 curl_multi_cleanup(curlm
);
611 curl_global_cleanup();
613 curl_slist_free_all(pragma_header
);
614 pragma_header
= NULL
;
616 curl_slist_free_all(no_pragma_header
);
617 no_pragma_header
= NULL
;
619 if (curl_http_proxy
) {
620 free((void *)curl_http_proxy
);
621 curl_http_proxy
= NULL
;
624 if (cert_auth
.password
!= NULL
) {
625 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
626 free(cert_auth
.password
);
627 cert_auth
.password
= NULL
;
629 ssl_cert_password_required
= 0;
631 free(cached_accept_language
);
632 cached_accept_language
= NULL
;
635 struct active_request_slot
*get_active_slot(void)
637 struct active_request_slot
*slot
= active_queue_head
;
638 struct active_request_slot
*newslot
;
640 #ifdef USE_CURL_MULTI
643 /* Wait for a slot to open up if the queue is full */
644 while (active_requests
>= max_requests
) {
645 curl_multi_perform(curlm
, &num_transfers
);
646 if (num_transfers
< active_requests
)
647 process_curl_messages();
651 while (slot
!= NULL
&& slot
->in_use
)
655 newslot
= xmalloc(sizeof(*newslot
));
656 newslot
->curl
= NULL
;
658 newslot
->next
= NULL
;
660 slot
= active_queue_head
;
662 active_queue_head
= newslot
;
664 while (slot
->next
!= NULL
)
666 slot
->next
= newslot
;
671 if (slot
->curl
== NULL
) {
672 #ifdef NO_CURL_EASY_DUPHANDLE
673 slot
->curl
= get_curl_handle();
675 slot
->curl
= curl_easy_duphandle(curl_default
);
677 curl_session_count
++;
682 slot
->results
= NULL
;
683 slot
->finished
= NULL
;
684 slot
->callback_data
= NULL
;
685 slot
->callback_func
= NULL
;
686 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
687 if (curl_save_cookies
)
688 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
689 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
690 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
691 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
692 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
693 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
694 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
695 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
696 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
697 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
698 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
699 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
701 if (http_auth
.password
)
702 init_curl_http_auth(slot
->curl
);
707 int start_active_slot(struct active_request_slot
*slot
)
709 #ifdef USE_CURL_MULTI
710 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
713 if (curlm_result
!= CURLM_OK
&&
714 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
721 * We know there must be something to do, since we just added
724 curl_multi_perform(curlm
, &num_transfers
);
729 #ifdef USE_CURL_MULTI
733 struct fill_chain
*next
;
736 static struct fill_chain
*fill_cfg
;
738 void add_fill_function(void *data
, int (*fill
)(void *))
740 struct fill_chain
*new = xmalloc(sizeof(*new));
741 struct fill_chain
**linkp
= &fill_cfg
;
746 linkp
= &(*linkp
)->next
;
750 void fill_active_slots(void)
752 struct active_request_slot
*slot
= active_queue_head
;
754 while (active_requests
< max_requests
) {
755 struct fill_chain
*fill
;
756 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
757 if (fill
->fill(fill
->data
))
764 while (slot
!= NULL
) {
765 if (!slot
->in_use
&& slot
->curl
!= NULL
766 && curl_session_count
> min_curl_sessions
) {
767 curl_easy_cleanup(slot
->curl
);
769 curl_session_count
--;
775 void step_active_slots(void)
778 CURLMcode curlm_result
;
781 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
782 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
783 if (num_transfers
< active_requests
) {
784 process_curl_messages();
790 void run_active_slot(struct active_request_slot
*slot
)
792 #ifdef USE_CURL_MULTI
797 struct timeval select_timeout
;
800 slot
->finished
= &finished
;
805 #if LIBCURL_VERSION_NUM >= 0x070f04
807 curl_multi_timeout(curlm
, &curl_timeout
);
808 if (curl_timeout
== 0) {
810 } else if (curl_timeout
== -1) {
811 select_timeout
.tv_sec
= 0;
812 select_timeout
.tv_usec
= 50000;
814 select_timeout
.tv_sec
= curl_timeout
/ 1000;
815 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
818 select_timeout
.tv_sec
= 0;
819 select_timeout
.tv_usec
= 50000;
826 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
829 * It can happen that curl_multi_timeout returns a pathologically
830 * long timeout when curl_multi_fdset returns no file descriptors
831 * to read. See commit message for more details.
834 (select_timeout
.tv_sec
> 0 ||
835 select_timeout
.tv_usec
> 50000)) {
836 select_timeout
.tv_sec
= 0;
837 select_timeout
.tv_usec
= 50000;
840 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
844 while (slot
->in_use
) {
845 slot
->curl_result
= curl_easy_perform(slot
->curl
);
846 finish_active_slot(slot
);
851 static void release_active_slot(struct active_request_slot
*slot
)
853 closedown_active_slot(slot
);
854 if (slot
->curl
&& curl_session_count
> min_curl_sessions
) {
855 #ifdef USE_CURL_MULTI
856 curl_multi_remove_handle(curlm
, slot
->curl
);
858 curl_easy_cleanup(slot
->curl
);
860 curl_session_count
--;
862 #ifdef USE_CURL_MULTI
867 void finish_all_active_slots(void)
869 struct active_request_slot
*slot
= active_queue_head
;
873 run_active_slot(slot
);
874 slot
= active_queue_head
;
880 /* Helpers for modifying and creating URLs */
881 static inline int needs_quote(int ch
)
883 if (((ch
>= 'A') && (ch
<= 'Z'))
884 || ((ch
>= 'a') && (ch
<= 'z'))
885 || ((ch
>= '0') && (ch
<= '9'))
893 static char *quote_ref_url(const char *base
, const char *ref
)
895 struct strbuf buf
= STRBUF_INIT
;
899 end_url_with_slash(&buf
, base
);
901 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
903 strbuf_addf(&buf
, "%%%02x", ch
);
905 strbuf_addch(&buf
, *cp
);
907 return strbuf_detach(&buf
, NULL
);
910 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
912 int only_two_digit_prefix
)
914 end_url_with_slash(buf
, url
);
916 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
917 if (!only_two_digit_prefix
)
918 strbuf_addf(buf
, "%s", hex
+2);
921 char *get_remote_object_url(const char *url
, const char *hex
,
922 int only_two_digit_prefix
)
924 struct strbuf buf
= STRBUF_INIT
;
925 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
926 return strbuf_detach(&buf
, NULL
);
929 static int handle_curl_result(struct slot_results
*results
)
932 * If we see a failing http code with CURLE_OK, we have turned off
933 * FAILONERROR (to keep the server's custom error response), and should
934 * translate the code into failure here.
936 if (results
->curl_result
== CURLE_OK
&&
937 results
->http_code
>= 400) {
938 results
->curl_result
= CURLE_HTTP_RETURNED_ERROR
;
940 * Normally curl will already have put the "reason phrase"
941 * from the server into curl_errorstr; unfortunately without
942 * FAILONERROR it is lost, so we can give only the numeric
945 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
946 "The requested URL returned error: %ld",
950 if (results
->curl_result
== CURLE_OK
) {
951 credential_approve(&http_auth
);
953 } else if (missing_target(results
))
954 return HTTP_MISSING_TARGET
;
955 else if (results
->http_code
== 401) {
956 if (http_auth
.username
&& http_auth
.password
) {
957 credential_reject(&http_auth
);
960 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
961 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
966 #if LIBCURL_VERSION_NUM >= 0x070c00
967 if (!curl_errorstr
[0])
968 strlcpy(curl_errorstr
,
969 curl_easy_strerror(results
->curl_result
),
970 sizeof(curl_errorstr
));
976 int run_one_slot(struct active_request_slot
*slot
,
977 struct slot_results
*results
)
979 slot
->results
= results
;
980 if (!start_active_slot(slot
)) {
981 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
982 "failed to start HTTP request");
983 return HTTP_START_FAILED
;
986 run_active_slot(slot
);
987 return handle_curl_result(results
);
990 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
996 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
998 strbuf_addstr(buf
, ptr
);
1003 * Check for and extract a content-type parameter. "raw"
1004 * should be positioned at the start of the potential
1005 * parameter, with any whitespace already removed.
1007 * "name" is the name of the parameter. The value is appended
1010 static int extract_param(const char *raw
, const char *name
,
1013 size_t len
= strlen(name
);
1015 if (strncasecmp(raw
, name
, len
))
1023 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1024 strbuf_addch(out
, *raw
++);
1029 * Extract a normalized version of the content type, with any
1030 * spaces suppressed, all letters lowercased, and no trailing ";"
1033 * Note that we will silently remove even invalid whitespace. For
1034 * example, "text / plain" is specifically forbidden by RFC 2616,
1035 * but "text/plain" is the only reasonable output, and this keeps
1038 * If the "charset" argument is not NULL, store the value of any
1039 * charset parameter there.
1042 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1043 * "text / plain" -> "text/plain"
1045 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1046 struct strbuf
*charset
)
1051 strbuf_grow(type
, raw
->len
);
1052 for (p
= raw
->buf
; *p
; p
++) {
1059 strbuf_addch(type
, tolower(*p
));
1065 strbuf_reset(charset
);
1067 while (isspace(*p
) || *p
== ';')
1069 if (!extract_param(p
, "charset", charset
))
1071 while (*p
&& !isspace(*p
))
1075 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1076 strbuf_addstr(charset
, "ISO-8859-1");
1079 static void write_accept_language(struct strbuf
*buf
)
1082 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1083 * that, q-value will be smaller than 0.001, the minimum q-value the
1084 * HTTP specification allows. See
1085 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1087 const int MAX_DECIMAL_PLACES
= 3;
1088 const int MAX_LANGUAGE_TAGS
= 1000;
1089 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1090 char **language_tags
= NULL
;
1092 const char *s
= get_preferred_languages();
1094 struct strbuf tag
= STRBUF_INIT
;
1096 /* Don't add Accept-Language header if no language is preferred. */
1101 * Split the colon-separated string of preferred languages into
1102 * language_tags array.
1105 /* collect language tag */
1106 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1107 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1109 /* skip .codeset, @modifier and any other unnecessary parts */
1110 while (*s
&& *s
!= ':')
1115 REALLOC_ARRAY(language_tags
, num_langs
);
1116 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1117 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1122 /* write Accept-Language header into buf */
1124 int last_buf_len
= 0;
1130 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1131 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1133 /* compute decimal_places */
1134 for (max_q
= 1, decimal_places
= 0;
1135 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1136 decimal_places
++, max_q
*= 10)
1139 sprintf(q_format
, ";q=0.%%0%dd", decimal_places
);
1141 strbuf_addstr(buf
, "Accept-Language: ");
1143 for (i
= 0; i
< num_langs
; i
++) {
1145 strbuf_addstr(buf
, ", ");
1147 strbuf_addstr(buf
, language_tags
[i
]);
1150 strbuf_addf(buf
, q_format
, max_q
- i
);
1152 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1153 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1157 last_buf_len
= buf
->len
;
1161 /* free language tags -- last one is a static '*' */
1162 for (i
= 0; i
< num_langs
- 1; i
++)
1163 free(language_tags
[i
]);
1164 free(language_tags
);
1168 * Get an Accept-Language header which indicates user's preferred languages.
1172 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1173 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1174 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1175 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1176 * LANGUAGE= LANG=C -> ""
1178 static const char *get_accept_language(void)
1180 if (!cached_accept_language
) {
1181 struct strbuf buf
= STRBUF_INIT
;
1182 write_accept_language(&buf
);
1184 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1187 return cached_accept_language
;
1190 /* http_request() targets */
1191 #define HTTP_REQUEST_STRBUF 0
1192 #define HTTP_REQUEST_FILE 1
1194 static int http_request(const char *url
,
1195 void *result
, int target
,
1196 const struct http_get_options
*options
)
1198 struct active_request_slot
*slot
;
1199 struct slot_results results
;
1200 struct curl_slist
*headers
= NULL
;
1201 struct strbuf buf
= STRBUF_INIT
;
1202 const char *accept_language
;
1205 slot
= get_active_slot();
1206 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1208 if (result
== NULL
) {
1209 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
1211 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
1212 curl_easy_setopt(slot
->curl
, CURLOPT_FILE
, result
);
1214 if (target
== HTTP_REQUEST_FILE
) {
1215 long posn
= ftell(result
);
1216 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1219 strbuf_addf(&buf
, "Range: bytes=%ld-", posn
);
1220 headers
= curl_slist_append(headers
, buf
.buf
);
1224 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1228 accept_language
= get_accept_language();
1230 if (accept_language
)
1231 headers
= curl_slist_append(headers
, accept_language
);
1233 strbuf_addstr(&buf
, "Pragma:");
1234 if (options
&& options
->no_cache
)
1235 strbuf_addstr(&buf
, " no-cache");
1236 if (options
&& options
->keep_error
)
1237 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
1239 headers
= curl_slist_append(headers
, buf
.buf
);
1241 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
1242 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
1243 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "gzip");
1245 ret
= run_one_slot(slot
, &results
);
1247 if (options
&& options
->content_type
) {
1248 struct strbuf raw
= STRBUF_INIT
;
1249 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
1250 extract_content_type(&raw
, options
->content_type
,
1252 strbuf_release(&raw
);
1255 if (options
&& options
->effective_url
)
1256 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
1257 options
->effective_url
);
1259 curl_slist_free_all(headers
);
1260 strbuf_release(&buf
);
1266 * Update the "base" url to a more appropriate value, as deduced by
1267 * redirects seen when requesting a URL starting with "url".
1269 * The "asked" parameter is a URL that we asked curl to access, and must begin
1272 * The "got" parameter is the URL that curl reported to us as where we ended
1275 * Returns 1 if we updated the base url, 0 otherwise.
1277 * Our basic strategy is to compare "base" and "asked" to find the bits
1278 * specific to our request. We then strip those bits off of "got" to yield the
1279 * new base. So for example, if our base is "http://example.com/foo.git",
1280 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1281 * with "https://other.example.com/foo.git/info/refs". We would want the
1282 * new URL to become "https://other.example.com/foo.git".
1284 * Note that this assumes a sane redirect scheme. It's entirely possible
1285 * in the example above to end up at a URL that does not even end in
1286 * "info/refs". In such a case we simply punt, as there is not much we can
1287 * do (and such a scheme is unlikely to represent a real git repository,
1288 * which means we are likely about to abort anyway).
1290 static int update_url_from_redirect(struct strbuf
*base
,
1292 const struct strbuf
*got
)
1297 if (!strcmp(asked
, got
->buf
))
1300 if (!skip_prefix(asked
, base
->buf
, &tail
))
1301 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1304 tail_len
= strlen(tail
);
1306 if (got
->len
< tail_len
||
1307 strcmp(tail
, got
->buf
+ got
->len
- tail_len
))
1308 return 0; /* insane redirect scheme */
1311 strbuf_add(base
, got
->buf
, got
->len
- tail_len
);
1315 static int http_request_reauth(const char *url
,
1316 void *result
, int target
,
1317 struct http_get_options
*options
)
1319 int ret
= http_request(url
, result
, target
, options
);
1321 if (options
&& options
->effective_url
&& options
->base_url
) {
1322 if (update_url_from_redirect(options
->base_url
,
1323 url
, options
->effective_url
)) {
1324 credential_from_url(&http_auth
, options
->base_url
->buf
);
1325 url
= options
->effective_url
->buf
;
1329 if (ret
!= HTTP_REAUTH
)
1333 * If we are using KEEP_ERROR, the previous request may have
1334 * put cruft into our output stream; we should clear it out before
1335 * making our next request. We only know how to do this for
1336 * the strbuf case, but that is enough to satisfy current callers.
1338 if (options
&& options
->keep_error
) {
1340 case HTTP_REQUEST_STRBUF
:
1341 strbuf_reset(result
);
1344 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1348 credential_fill(&http_auth
);
1350 return http_request(url
, result
, target
, options
);
1353 int http_get_strbuf(const char *url
,
1354 struct strbuf
*result
,
1355 struct http_get_options
*options
)
1357 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
1361 * Downloads a URL and stores the result in the given file.
1363 * If a previous interrupted download is detected (i.e. a previous temporary
1364 * file is still around) the download is resumed.
1366 static int http_get_file(const char *url
, const char *filename
,
1367 struct http_get_options
*options
)
1370 struct strbuf tmpfile
= STRBUF_INIT
;
1373 strbuf_addf(&tmpfile
, "%s.temp", filename
);
1374 result
= fopen(tmpfile
.buf
, "a");
1376 error("Unable to open local file %s", tmpfile
.buf
);
1381 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
1384 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
1387 strbuf_release(&tmpfile
);
1391 int http_fetch_ref(const char *base
, struct ref
*ref
)
1393 struct http_get_options options
= {0};
1395 struct strbuf buffer
= STRBUF_INIT
;
1398 options
.no_cache
= 1;
1400 url
= quote_ref_url(base
, ref
->name
);
1401 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
1402 strbuf_rtrim(&buffer
);
1403 if (buffer
.len
== 40)
1404 ret
= get_sha1_hex(buffer
.buf
, ref
->old_sha1
);
1405 else if (starts_with(buffer
.buf
, "ref: ")) {
1406 ref
->symref
= xstrdup(buffer
.buf
+ 5);
1411 strbuf_release(&buffer
);
1416 /* Helpers for fetching packs */
1417 static char *fetch_pack_index(unsigned char *sha1
, const char *base_url
)
1420 struct strbuf buf
= STRBUF_INIT
;
1422 if (http_is_verbose
)
1423 fprintf(stderr
, "Getting index for pack %s\n", sha1_to_hex(sha1
));
1425 end_url_with_slash(&buf
, base_url
);
1426 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", sha1_to_hex(sha1
));
1427 url
= strbuf_detach(&buf
, NULL
);
1429 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(sha1
));
1430 tmp
= strbuf_detach(&buf
, NULL
);
1432 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
1433 error("Unable to get pack index %s", url
);
1442 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
1443 unsigned char *sha1
, const char *base_url
)
1445 struct packed_git
*new_pack
;
1446 char *tmp_idx
= NULL
;
1449 if (has_pack_index(sha1
)) {
1450 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
1452 return -1; /* parse_pack_index() already issued error message */
1456 tmp_idx
= fetch_pack_index(sha1
, base_url
);
1460 new_pack
= parse_pack_index(sha1
, tmp_idx
);
1465 return -1; /* parse_pack_index() already issued error message */
1468 ret
= verify_pack_index(new_pack
);
1470 close_pack_index(new_pack
);
1471 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
1478 new_pack
->next
= *packs_head
;
1479 *packs_head
= new_pack
;
1483 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
1485 struct http_get_options options
= {0};
1488 struct strbuf buf
= STRBUF_INIT
;
1489 unsigned char sha1
[20];
1491 end_url_with_slash(&buf
, base_url
);
1492 strbuf_addstr(&buf
, "objects/info/packs");
1493 url
= strbuf_detach(&buf
, NULL
);
1495 options
.no_cache
= 1;
1496 ret
= http_get_strbuf(url
, &buf
, &options
);
1501 while (i
< buf
.len
) {
1505 if (i
+ 52 <= buf
.len
&&
1506 starts_with(data
+ i
, " pack-") &&
1507 starts_with(data
+ i
+ 46, ".pack\n")) {
1508 get_sha1_hex(data
+ i
+ 6, sha1
);
1509 fetch_and_setup_pack_index(packs_head
, sha1
,
1515 while (i
< buf
.len
&& data
[i
] != '\n')
1526 void release_http_pack_request(struct http_pack_request
*preq
)
1528 if (preq
->packfile
!= NULL
) {
1529 fclose(preq
->packfile
);
1530 preq
->packfile
= NULL
;
1532 if (preq
->range_header
!= NULL
) {
1533 curl_slist_free_all(preq
->range_header
);
1534 preq
->range_header
= NULL
;
1541 int finish_http_pack_request(struct http_pack_request
*preq
)
1543 struct packed_git
**lst
;
1544 struct packed_git
*p
= preq
->target
;
1546 struct child_process ip
= CHILD_PROCESS_INIT
;
1547 const char *ip_argv
[8];
1549 close_pack_index(p
);
1551 fclose(preq
->packfile
);
1552 preq
->packfile
= NULL
;
1556 lst
= &((*lst
)->next
);
1557 *lst
= (*lst
)->next
;
1559 tmp_idx
= xstrdup(preq
->tmpfile
);
1560 strcpy(tmp_idx
+ strlen(tmp_idx
) - strlen(".pack.temp"),
1563 ip_argv
[0] = "index-pack";
1565 ip_argv
[2] = tmp_idx
;
1566 ip_argv
[3] = preq
->tmpfile
;
1574 if (run_command(&ip
)) {
1575 unlink(preq
->tmpfile
);
1581 unlink(sha1_pack_index_name(p
->sha1
));
1583 if (finalize_object_file(preq
->tmpfile
, sha1_pack_name(p
->sha1
))
1584 || finalize_object_file(tmp_idx
, sha1_pack_index_name(p
->sha1
))) {
1589 install_packed_git(p
);
1594 struct http_pack_request
*new_http_pack_request(
1595 struct packed_git
*target
, const char *base_url
)
1598 char range
[RANGE_HEADER_SIZE
];
1599 struct strbuf buf
= STRBUF_INIT
;
1600 struct http_pack_request
*preq
;
1602 preq
= xcalloc(1, sizeof(*preq
));
1603 preq
->target
= target
;
1605 end_url_with_slash(&buf
, base_url
);
1606 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
1607 sha1_to_hex(target
->sha1
));
1608 preq
->url
= strbuf_detach(&buf
, NULL
);
1610 snprintf(preq
->tmpfile
, sizeof(preq
->tmpfile
), "%s.temp",
1611 sha1_pack_name(target
->sha1
));
1612 preq
->packfile
= fopen(preq
->tmpfile
, "a");
1613 if (!preq
->packfile
) {
1614 error("Unable to open local file %s for pack",
1619 preq
->slot
= get_active_slot();
1620 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_FILE
, preq
->packfile
);
1621 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
1622 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
1623 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
1627 * If there is data present from a previous transfer attempt,
1628 * resume where it left off
1630 prev_posn
= ftell(preq
->packfile
);
1632 if (http_is_verbose
)
1634 "Resuming fetch of pack %s at byte %ld\n",
1635 sha1_to_hex(target
->sha1
), prev_posn
);
1636 sprintf(range
, "Range: bytes=%ld-", prev_posn
);
1637 preq
->range_header
= curl_slist_append(NULL
, range
);
1638 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
1639 preq
->range_header
);
1650 /* Helpers for fetching objects (loose) */
1651 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
1654 unsigned char expn
[4096];
1655 size_t size
= eltsize
* nmemb
;
1657 struct http_object_request
*freq
=
1658 (struct http_object_request
*)data
;
1660 ssize_t retval
= xwrite(freq
->localfile
,
1661 (char *) ptr
+ posn
, size
- posn
);
1665 } while (posn
< size
);
1667 freq
->stream
.avail_in
= size
;
1668 freq
->stream
.next_in
= (void *)ptr
;
1670 freq
->stream
.next_out
= expn
;
1671 freq
->stream
.avail_out
= sizeof(expn
);
1672 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
1673 git_SHA1_Update(&freq
->c
, expn
,
1674 sizeof(expn
) - freq
->stream
.avail_out
);
1675 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
1679 struct http_object_request
*new_http_object_request(const char *base_url
,
1680 unsigned char *sha1
)
1682 char *hex
= sha1_to_hex(sha1
);
1683 const char *filename
;
1684 char prevfile
[PATH_MAX
];
1686 char prev_buf
[PREV_BUF_SIZE
];
1687 ssize_t prev_read
= 0;
1689 char range
[RANGE_HEADER_SIZE
];
1690 struct curl_slist
*range_header
= NULL
;
1691 struct http_object_request
*freq
;
1693 freq
= xcalloc(1, sizeof(*freq
));
1694 hashcpy(freq
->sha1
, sha1
);
1695 freq
->localfile
= -1;
1697 filename
= sha1_file_name(sha1
);
1698 snprintf(freq
->tmpfile
, sizeof(freq
->tmpfile
),
1699 "%s.temp", filename
);
1701 snprintf(prevfile
, sizeof(prevfile
), "%s.prev", filename
);
1702 unlink_or_warn(prevfile
);
1703 rename(freq
->tmpfile
, prevfile
);
1704 unlink_or_warn(freq
->tmpfile
);
1706 if (freq
->localfile
!= -1)
1707 error("fd leakage in start: %d", freq
->localfile
);
1708 freq
->localfile
= open(freq
->tmpfile
,
1709 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1711 * This could have failed due to the "lazy directory creation";
1712 * try to mkdir the last path component.
1714 if (freq
->localfile
< 0 && errno
== ENOENT
) {
1715 char *dir
= strrchr(freq
->tmpfile
, '/');
1718 mkdir(freq
->tmpfile
, 0777);
1721 freq
->localfile
= open(freq
->tmpfile
,
1722 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1725 if (freq
->localfile
< 0) {
1726 error("Couldn't create temporary file %s: %s",
1727 freq
->tmpfile
, strerror(errno
));
1731 git_inflate_init(&freq
->stream
);
1733 git_SHA1_Init(&freq
->c
);
1735 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
1738 * If a previous temp file is present, process what was already
1741 prevlocal
= open(prevfile
, O_RDONLY
);
1742 if (prevlocal
!= -1) {
1744 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
1746 if (fwrite_sha1_file(prev_buf
,
1749 freq
) == prev_read
) {
1750 prev_posn
+= prev_read
;
1755 } while (prev_read
> 0);
1758 unlink_or_warn(prevfile
);
1761 * Reset inflate/SHA1 if there was an error reading the previous temp
1762 * file; also rewind to the beginning of the local file.
1764 if (prev_read
== -1) {
1765 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
1766 git_inflate_init(&freq
->stream
);
1767 git_SHA1_Init(&freq
->c
);
1770 lseek(freq
->localfile
, 0, SEEK_SET
);
1771 if (ftruncate(freq
->localfile
, 0) < 0) {
1772 error("Couldn't truncate temporary file %s: %s",
1773 freq
->tmpfile
, strerror(errno
));
1779 freq
->slot
= get_active_slot();
1781 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FILE
, freq
);
1782 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
1783 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
1784 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
1785 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
1788 * If we have successfully processed data from a previous fetch
1789 * attempt, only fetch the data we don't already have.
1792 if (http_is_verbose
)
1794 "Resuming fetch of object %s at byte %ld\n",
1796 sprintf(range
, "Range: bytes=%ld-", prev_posn
);
1797 range_header
= curl_slist_append(range_header
, range
);
1798 curl_easy_setopt(freq
->slot
->curl
,
1799 CURLOPT_HTTPHEADER
, range_header
);
1810 void process_http_object_request(struct http_object_request
*freq
)
1812 if (freq
->slot
== NULL
)
1814 freq
->curl_result
= freq
->slot
->curl_result
;
1815 freq
->http_code
= freq
->slot
->http_code
;
1819 int finish_http_object_request(struct http_object_request
*freq
)
1823 close(freq
->localfile
);
1824 freq
->localfile
= -1;
1826 process_http_object_request(freq
);
1828 if (freq
->http_code
== 416) {
1829 warning("requested range invalid; we may already have all the data.");
1830 } else if (freq
->curl_result
!= CURLE_OK
) {
1831 if (stat(freq
->tmpfile
, &st
) == 0)
1832 if (st
.st_size
== 0)
1833 unlink_or_warn(freq
->tmpfile
);
1837 git_inflate_end(&freq
->stream
);
1838 git_SHA1_Final(freq
->real_sha1
, &freq
->c
);
1839 if (freq
->zret
!= Z_STREAM_END
) {
1840 unlink_or_warn(freq
->tmpfile
);
1843 if (hashcmp(freq
->sha1
, freq
->real_sha1
)) {
1844 unlink_or_warn(freq
->tmpfile
);
1848 finalize_object_file(freq
->tmpfile
, sha1_file_name(freq
->sha1
));
1850 return freq
->rename
;
1853 void abort_http_object_request(struct http_object_request
*freq
)
1855 unlink_or_warn(freq
->tmpfile
);
1857 release_http_object_request(freq
);
1860 void release_http_object_request(struct http_object_request
*freq
)
1862 if (freq
->localfile
!= -1) {
1863 close(freq
->localfile
);
1864 freq
->localfile
= -1;
1866 if (freq
->url
!= NULL
) {
1870 if (freq
->slot
!= NULL
) {
1871 freq
->slot
->callback_func
= NULL
;
1872 freq
->slot
->callback_data
= NULL
;
1873 release_active_slot(freq
->slot
);