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 static void xmulti_remove_handle(struct active_request_slot
*slot
)
172 #ifdef USE_CURL_MULTI
173 curl_multi_remove_handle(curlm
, slot
->curl
);
177 #ifdef USE_CURL_MULTI
178 static void process_curl_messages(void)
181 struct active_request_slot
*slot
;
182 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
184 while (curl_message
!= NULL
) {
185 if (curl_message
->msg
== CURLMSG_DONE
) {
186 int curl_result
= curl_message
->data
.result
;
187 slot
= active_queue_head
;
188 while (slot
!= NULL
&&
189 slot
->curl
!= curl_message
->easy_handle
)
192 xmulti_remove_handle(slot
);
193 slot
->curl_result
= curl_result
;
194 finish_active_slot(slot
);
196 fprintf(stderr
, "Received DONE message for unknown request!\n");
199 fprintf(stderr
, "Unknown CURL message received: %d\n",
200 (int)curl_message
->msg
);
202 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
207 static int http_options(const char *var
, const char *value
, void *cb
)
209 if (!strcmp("http.sslverify", var
)) {
210 curl_ssl_verify
= git_config_bool(var
, value
);
213 if (!strcmp("http.sslcipherlist", var
))
214 return git_config_string(&ssl_cipherlist
, var
, value
);
215 if (!strcmp("http.sslversion", var
))
216 return git_config_string(&ssl_version
, var
, value
);
217 if (!strcmp("http.sslcert", var
))
218 return git_config_string(&ssl_cert
, var
, value
);
219 #if LIBCURL_VERSION_NUM >= 0x070903
220 if (!strcmp("http.sslkey", var
))
221 return git_config_string(&ssl_key
, var
, value
);
223 #if LIBCURL_VERSION_NUM >= 0x070908
224 if (!strcmp("http.sslcapath", var
))
225 return git_config_pathname(&ssl_capath
, var
, value
);
227 if (!strcmp("http.sslcainfo", var
))
228 return git_config_pathname(&ssl_cainfo
, var
, value
);
229 if (!strcmp("http.sslcertpasswordprotected", var
)) {
230 ssl_cert_password_required
= git_config_bool(var
, value
);
233 if (!strcmp("http.ssltry", var
)) {
234 curl_ssl_try
= git_config_bool(var
, value
);
237 if (!strcmp("http.minsessions", var
)) {
238 min_curl_sessions
= git_config_int(var
, value
);
239 #ifndef USE_CURL_MULTI
240 if (min_curl_sessions
> 1)
241 min_curl_sessions
= 1;
245 #ifdef USE_CURL_MULTI
246 if (!strcmp("http.maxrequests", var
)) {
247 max_requests
= git_config_int(var
, value
);
251 if (!strcmp("http.lowspeedlimit", var
)) {
252 curl_low_speed_limit
= (long)git_config_int(var
, value
);
255 if (!strcmp("http.lowspeedtime", var
)) {
256 curl_low_speed_time
= (long)git_config_int(var
, value
);
260 if (!strcmp("http.noepsv", var
)) {
261 curl_ftp_no_epsv
= git_config_bool(var
, value
);
264 if (!strcmp("http.proxy", var
))
265 return git_config_string(&curl_http_proxy
, var
, value
);
267 if (!strcmp("http.cookiefile", var
))
268 return git_config_string(&curl_cookie_file
, var
, value
);
269 if (!strcmp("http.savecookies", var
)) {
270 curl_save_cookies
= git_config_bool(var
, value
);
274 if (!strcmp("http.postbuffer", var
)) {
275 http_post_buffer
= git_config_int(var
, value
);
276 if (http_post_buffer
< LARGE_PACKET_MAX
)
277 http_post_buffer
= LARGE_PACKET_MAX
;
281 if (!strcmp("http.useragent", var
))
282 return git_config_string(&user_agent
, var
, value
);
284 /* Fall back on the default ones */
285 return git_default_config(var
, value
, cb
);
288 static void init_curl_http_auth(CURL
*result
)
290 if (!http_auth
.username
)
293 credential_fill(&http_auth
);
295 #if LIBCURL_VERSION_NUM >= 0x071301
296 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
297 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
300 static struct strbuf up
= STRBUF_INIT
;
302 * Note that we assume we only ever have a single set of
303 * credentials in a given program run, so we do not have
304 * to worry about updating this buffer, only setting its
308 strbuf_addf(&up
, "%s:%s",
309 http_auth
.username
, http_auth
.password
);
310 curl_easy_setopt(result
, CURLOPT_USERPWD
, up
.buf
);
315 static int has_cert_password(void)
317 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
319 if (!cert_auth
.password
) {
320 cert_auth
.protocol
= xstrdup("cert");
321 cert_auth
.username
= xstrdup("");
322 cert_auth
.path
= xstrdup(ssl_cert
);
323 credential_fill(&cert_auth
);
328 #if LIBCURL_VERSION_NUM >= 0x071900
329 static void set_curl_keepalive(CURL
*c
)
331 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
334 #elif LIBCURL_VERSION_NUM >= 0x071000
335 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
339 socklen_t len
= (socklen_t
)sizeof(ka
);
341 if (type
!= CURLSOCKTYPE_IPCXN
)
344 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
346 warning("unable to set SO_KEEPALIVE on socket %s",
349 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
352 static void set_curl_keepalive(CURL
*c
)
354 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
358 static void set_curl_keepalive(CURL
*c
)
360 /* not supported on older curl versions */
364 static CURL
*get_curl_handle(void)
366 CURL
*result
= curl_easy_init();
367 long allowed_protocols
= 0;
370 die("curl_easy_init failed");
372 if (!curl_ssl_verify
) {
373 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
374 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
376 /* Verify authenticity of the peer's certificate */
377 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
378 /* The name in the cert must match whom we tried to connect */
379 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
382 #if LIBCURL_VERSION_NUM >= 0x070907
383 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
385 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
386 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
389 if (http_proactive_auth
)
390 init_curl_http_auth(result
);
392 if (getenv("GIT_SSL_VERSION"))
393 ssl_version
= getenv("GIT_SSL_VERSION");
394 if (ssl_version
&& *ssl_version
) {
396 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
397 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
398 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
399 sslversions
[i
].ssl_version
);
403 if (i
== ARRAY_SIZE(sslversions
))
404 warning("unsupported ssl version %s: using default",
408 if (getenv("GIT_SSL_CIPHER_LIST"))
409 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
410 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
411 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
414 if (ssl_cert
!= NULL
)
415 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
416 if (has_cert_password())
417 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
418 #if LIBCURL_VERSION_NUM >= 0x070903
420 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
422 #if LIBCURL_VERSION_NUM >= 0x070908
423 if (ssl_capath
!= NULL
)
424 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
426 if (ssl_cainfo
!= NULL
)
427 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
429 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
430 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
431 curl_low_speed_limit
);
432 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
433 curl_low_speed_time
);
436 curl_easy_setopt(result
, CURLOPT_FOLLOWLOCATION
, 1);
437 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
438 #if LIBCURL_VERSION_NUM >= 0x071301
439 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
440 #elif LIBCURL_VERSION_NUM >= 0x071101
441 curl_easy_setopt(result
, CURLOPT_POST301
, 1);
443 #if LIBCURL_VERSION_NUM >= 0x071304
444 if (is_transport_allowed("http"))
445 allowed_protocols
|= CURLPROTO_HTTP
;
446 if (is_transport_allowed("https"))
447 allowed_protocols
|= CURLPROTO_HTTPS
;
448 if (is_transport_allowed("ftp"))
449 allowed_protocols
|= CURLPROTO_FTP
;
450 if (is_transport_allowed("ftps"))
451 allowed_protocols
|= CURLPROTO_FTPS
;
452 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
, allowed_protocols
);
454 if (transport_restrict_protocols())
455 warning("protocol restrictions not applied to curl redirects because\n"
456 "your curl version is too old (>= 7.19.4)");
459 if (getenv("GIT_CURL_VERBOSE"))
460 curl_easy_setopt(result
, CURLOPT_VERBOSE
, 1);
462 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
463 user_agent
? user_agent
: git_user_agent());
465 if (curl_ftp_no_epsv
)
466 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
468 #ifdef CURLOPT_USE_SSL
470 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
473 if (curl_http_proxy
) {
474 curl_easy_setopt(result
, CURLOPT_PROXY
, curl_http_proxy
);
475 #if LIBCURL_VERSION_NUM >= 0x071800
476 if (starts_with(curl_http_proxy
, "socks5"))
477 curl_easy_setopt(result
,
478 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
479 else if (starts_with(curl_http_proxy
, "socks4a"))
480 curl_easy_setopt(result
,
481 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
482 else if (starts_with(curl_http_proxy
, "socks"))
483 curl_easy_setopt(result
,
484 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
487 #if LIBCURL_VERSION_NUM >= 0x070a07
488 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
491 set_curl_keepalive(result
);
496 static void set_from_env(const char **var
, const char *envname
)
498 const char *val
= getenv(envname
);
503 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
505 char *low_speed_limit
;
506 char *low_speed_time
;
507 char *normalized_url
;
508 struct urlmatch_config config
= { STRING_LIST_INIT_DUP
};
510 config
.section
= "http";
512 config
.collect_fn
= http_options
;
513 config
.cascade_fn
= git_default_config
;
517 normalized_url
= url_normalize(url
, &config
.url
);
519 git_config(urlmatch_config_entry
, &config
);
520 free(normalized_url
);
522 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
523 die("curl_global_init failed");
525 http_proactive_auth
= proactive_auth
;
527 if (remote
&& remote
->http_proxy
)
528 curl_http_proxy
= xstrdup(remote
->http_proxy
);
530 pragma_header
= curl_slist_append(pragma_header
, "Pragma: no-cache");
531 no_pragma_header
= curl_slist_append(no_pragma_header
, "Pragma:");
533 #ifdef USE_CURL_MULTI
535 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
536 if (http_max_requests
!= NULL
)
537 max_requests
= atoi(http_max_requests
);
540 curlm
= curl_multi_init();
542 die("curl_multi_init failed");
545 if (getenv("GIT_SSL_NO_VERIFY"))
548 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
549 #if LIBCURL_VERSION_NUM >= 0x070903
550 set_from_env(&ssl_key
, "GIT_SSL_KEY");
552 #if LIBCURL_VERSION_NUM >= 0x070908
553 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
555 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
557 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
559 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
560 if (low_speed_limit
!= NULL
)
561 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
562 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
563 if (low_speed_time
!= NULL
)
564 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
566 if (curl_ssl_verify
== -1)
569 curl_session_count
= 0;
570 #ifdef USE_CURL_MULTI
571 if (max_requests
< 1)
572 max_requests
= DEFAULT_MAX_REQUESTS
;
575 if (getenv("GIT_CURL_FTP_NO_EPSV"))
576 curl_ftp_no_epsv
= 1;
579 credential_from_url(&http_auth
, url
);
580 if (!ssl_cert_password_required
&&
581 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
582 starts_with(url
, "https://"))
583 ssl_cert_password_required
= 1;
586 #ifndef NO_CURL_EASY_DUPHANDLE
587 curl_default
= get_curl_handle();
591 void http_cleanup(void)
593 struct active_request_slot
*slot
= active_queue_head
;
595 while (slot
!= NULL
) {
596 struct active_request_slot
*next
= slot
->next
;
597 if (slot
->curl
!= NULL
) {
598 xmulti_remove_handle(slot
);
599 curl_easy_cleanup(slot
->curl
);
604 active_queue_head
= NULL
;
606 #ifndef NO_CURL_EASY_DUPHANDLE
607 curl_easy_cleanup(curl_default
);
610 #ifdef USE_CURL_MULTI
611 curl_multi_cleanup(curlm
);
613 curl_global_cleanup();
615 curl_slist_free_all(pragma_header
);
616 pragma_header
= NULL
;
618 curl_slist_free_all(no_pragma_header
);
619 no_pragma_header
= NULL
;
621 if (curl_http_proxy
) {
622 free((void *)curl_http_proxy
);
623 curl_http_proxy
= NULL
;
626 if (cert_auth
.password
!= NULL
) {
627 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
628 free(cert_auth
.password
);
629 cert_auth
.password
= NULL
;
631 ssl_cert_password_required
= 0;
633 free(cached_accept_language
);
634 cached_accept_language
= NULL
;
637 struct active_request_slot
*get_active_slot(void)
639 struct active_request_slot
*slot
= active_queue_head
;
640 struct active_request_slot
*newslot
;
642 #ifdef USE_CURL_MULTI
645 /* Wait for a slot to open up if the queue is full */
646 while (active_requests
>= max_requests
) {
647 curl_multi_perform(curlm
, &num_transfers
);
648 if (num_transfers
< active_requests
)
649 process_curl_messages();
653 while (slot
!= NULL
&& slot
->in_use
)
657 newslot
= xmalloc(sizeof(*newslot
));
658 newslot
->curl
= NULL
;
660 newslot
->next
= NULL
;
662 slot
= active_queue_head
;
664 active_queue_head
= newslot
;
666 while (slot
->next
!= NULL
)
668 slot
->next
= newslot
;
673 if (slot
->curl
== NULL
) {
674 #ifdef NO_CURL_EASY_DUPHANDLE
675 slot
->curl
= get_curl_handle();
677 slot
->curl
= curl_easy_duphandle(curl_default
);
679 curl_session_count
++;
684 slot
->results
= NULL
;
685 slot
->finished
= NULL
;
686 slot
->callback_data
= NULL
;
687 slot
->callback_func
= NULL
;
688 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
689 if (curl_save_cookies
)
690 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
691 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
692 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
693 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
694 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
695 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
696 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
697 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
698 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
699 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
700 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
701 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
703 if (http_auth
.password
)
704 init_curl_http_auth(slot
->curl
);
709 int start_active_slot(struct active_request_slot
*slot
)
711 #ifdef USE_CURL_MULTI
712 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
715 if (curlm_result
!= CURLM_OK
&&
716 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
717 warning("curl_multi_add_handle failed: %s",
718 curl_multi_strerror(curlm_result
));
725 * We know there must be something to do, since we just added
728 curl_multi_perform(curlm
, &num_transfers
);
733 #ifdef USE_CURL_MULTI
737 struct fill_chain
*next
;
740 static struct fill_chain
*fill_cfg
;
742 void add_fill_function(void *data
, int (*fill
)(void *))
744 struct fill_chain
*new = xmalloc(sizeof(*new));
745 struct fill_chain
**linkp
= &fill_cfg
;
750 linkp
= &(*linkp
)->next
;
754 void fill_active_slots(void)
756 struct active_request_slot
*slot
= active_queue_head
;
758 while (active_requests
< max_requests
) {
759 struct fill_chain
*fill
;
760 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
761 if (fill
->fill(fill
->data
))
768 while (slot
!= NULL
) {
769 if (!slot
->in_use
&& slot
->curl
!= NULL
770 && curl_session_count
> min_curl_sessions
) {
771 curl_easy_cleanup(slot
->curl
);
773 curl_session_count
--;
779 void step_active_slots(void)
782 CURLMcode curlm_result
;
785 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
786 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
787 if (num_transfers
< active_requests
) {
788 process_curl_messages();
794 void run_active_slot(struct active_request_slot
*slot
)
796 #ifdef USE_CURL_MULTI
801 struct timeval select_timeout
;
804 slot
->finished
= &finished
;
809 #if LIBCURL_VERSION_NUM >= 0x070f04
811 curl_multi_timeout(curlm
, &curl_timeout
);
812 if (curl_timeout
== 0) {
814 } else if (curl_timeout
== -1) {
815 select_timeout
.tv_sec
= 0;
816 select_timeout
.tv_usec
= 50000;
818 select_timeout
.tv_sec
= curl_timeout
/ 1000;
819 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
822 select_timeout
.tv_sec
= 0;
823 select_timeout
.tv_usec
= 50000;
830 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
833 * It can happen that curl_multi_timeout returns a pathologically
834 * long timeout when curl_multi_fdset returns no file descriptors
835 * to read. See commit message for more details.
838 (select_timeout
.tv_sec
> 0 ||
839 select_timeout
.tv_usec
> 50000)) {
840 select_timeout
.tv_sec
= 0;
841 select_timeout
.tv_usec
= 50000;
844 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
848 while (slot
->in_use
) {
849 slot
->curl_result
= curl_easy_perform(slot
->curl
);
850 finish_active_slot(slot
);
855 static void release_active_slot(struct active_request_slot
*slot
)
857 closedown_active_slot(slot
);
859 xmulti_remove_handle(slot
);
860 if (curl_session_count
> min_curl_sessions
) {
861 curl_easy_cleanup(slot
->curl
);
863 curl_session_count
--;
866 #ifdef USE_CURL_MULTI
871 void finish_all_active_slots(void)
873 struct active_request_slot
*slot
= active_queue_head
;
877 run_active_slot(slot
);
878 slot
= active_queue_head
;
884 /* Helpers for modifying and creating URLs */
885 static inline int needs_quote(int ch
)
887 if (((ch
>= 'A') && (ch
<= 'Z'))
888 || ((ch
>= 'a') && (ch
<= 'z'))
889 || ((ch
>= '0') && (ch
<= '9'))
897 static char *quote_ref_url(const char *base
, const char *ref
)
899 struct strbuf buf
= STRBUF_INIT
;
903 end_url_with_slash(&buf
, base
);
905 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
907 strbuf_addf(&buf
, "%%%02x", ch
);
909 strbuf_addch(&buf
, *cp
);
911 return strbuf_detach(&buf
, NULL
);
914 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
916 int only_two_digit_prefix
)
918 end_url_with_slash(buf
, url
);
920 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
921 if (!only_two_digit_prefix
)
922 strbuf_addf(buf
, "%s", hex
+2);
925 char *get_remote_object_url(const char *url
, const char *hex
,
926 int only_two_digit_prefix
)
928 struct strbuf buf
= STRBUF_INIT
;
929 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
930 return strbuf_detach(&buf
, NULL
);
933 static int handle_curl_result(struct slot_results
*results
)
936 * If we see a failing http code with CURLE_OK, we have turned off
937 * FAILONERROR (to keep the server's custom error response), and should
938 * translate the code into failure here.
940 if (results
->curl_result
== CURLE_OK
&&
941 results
->http_code
>= 400) {
942 results
->curl_result
= CURLE_HTTP_RETURNED_ERROR
;
944 * Normally curl will already have put the "reason phrase"
945 * from the server into curl_errorstr; unfortunately without
946 * FAILONERROR it is lost, so we can give only the numeric
949 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
950 "The requested URL returned error: %ld",
954 if (results
->curl_result
== CURLE_OK
) {
955 credential_approve(&http_auth
);
957 } else if (missing_target(results
))
958 return HTTP_MISSING_TARGET
;
959 else if (results
->http_code
== 401) {
960 if (http_auth
.username
&& http_auth
.password
) {
961 credential_reject(&http_auth
);
964 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
965 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
970 #if LIBCURL_VERSION_NUM >= 0x070c00
971 if (!curl_errorstr
[0])
972 strlcpy(curl_errorstr
,
973 curl_easy_strerror(results
->curl_result
),
974 sizeof(curl_errorstr
));
980 int run_one_slot(struct active_request_slot
*slot
,
981 struct slot_results
*results
)
983 slot
->results
= results
;
984 if (!start_active_slot(slot
)) {
985 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
986 "failed to start HTTP request");
987 return HTTP_START_FAILED
;
990 run_active_slot(slot
);
991 return handle_curl_result(results
);
994 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
1000 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1002 strbuf_addstr(buf
, ptr
);
1007 * Check for and extract a content-type parameter. "raw"
1008 * should be positioned at the start of the potential
1009 * parameter, with any whitespace already removed.
1011 * "name" is the name of the parameter. The value is appended
1014 static int extract_param(const char *raw
, const char *name
,
1017 size_t len
= strlen(name
);
1019 if (strncasecmp(raw
, name
, len
))
1027 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1028 strbuf_addch(out
, *raw
++);
1033 * Extract a normalized version of the content type, with any
1034 * spaces suppressed, all letters lowercased, and no trailing ";"
1037 * Note that we will silently remove even invalid whitespace. For
1038 * example, "text / plain" is specifically forbidden by RFC 2616,
1039 * but "text/plain" is the only reasonable output, and this keeps
1042 * If the "charset" argument is not NULL, store the value of any
1043 * charset parameter there.
1046 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1047 * "text / plain" -> "text/plain"
1049 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1050 struct strbuf
*charset
)
1055 strbuf_grow(type
, raw
->len
);
1056 for (p
= raw
->buf
; *p
; p
++) {
1063 strbuf_addch(type
, tolower(*p
));
1069 strbuf_reset(charset
);
1071 while (isspace(*p
) || *p
== ';')
1073 if (!extract_param(p
, "charset", charset
))
1075 while (*p
&& !isspace(*p
))
1079 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1080 strbuf_addstr(charset
, "ISO-8859-1");
1083 static void write_accept_language(struct strbuf
*buf
)
1086 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1087 * that, q-value will be smaller than 0.001, the minimum q-value the
1088 * HTTP specification allows. See
1089 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1091 const int MAX_DECIMAL_PLACES
= 3;
1092 const int MAX_LANGUAGE_TAGS
= 1000;
1093 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1094 char **language_tags
= NULL
;
1096 const char *s
= get_preferred_languages();
1098 struct strbuf tag
= STRBUF_INIT
;
1100 /* Don't add Accept-Language header if no language is preferred. */
1105 * Split the colon-separated string of preferred languages into
1106 * language_tags array.
1109 /* collect language tag */
1110 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1111 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1113 /* skip .codeset, @modifier and any other unnecessary parts */
1114 while (*s
&& *s
!= ':')
1119 REALLOC_ARRAY(language_tags
, num_langs
);
1120 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1121 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1126 /* write Accept-Language header into buf */
1128 int last_buf_len
= 0;
1134 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1135 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1137 /* compute decimal_places */
1138 for (max_q
= 1, decimal_places
= 0;
1139 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1140 decimal_places
++, max_q
*= 10)
1143 sprintf(q_format
, ";q=0.%%0%dd", decimal_places
);
1145 strbuf_addstr(buf
, "Accept-Language: ");
1147 for (i
= 0; i
< num_langs
; i
++) {
1149 strbuf_addstr(buf
, ", ");
1151 strbuf_addstr(buf
, language_tags
[i
]);
1154 strbuf_addf(buf
, q_format
, max_q
- i
);
1156 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1157 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1161 last_buf_len
= buf
->len
;
1165 /* free language tags -- last one is a static '*' */
1166 for (i
= 0; i
< num_langs
- 1; i
++)
1167 free(language_tags
[i
]);
1168 free(language_tags
);
1172 * Get an Accept-Language header which indicates user's preferred languages.
1176 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1177 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1178 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1179 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1180 * LANGUAGE= LANG=C -> ""
1182 static const char *get_accept_language(void)
1184 if (!cached_accept_language
) {
1185 struct strbuf buf
= STRBUF_INIT
;
1186 write_accept_language(&buf
);
1188 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1191 return cached_accept_language
;
1194 /* http_request() targets */
1195 #define HTTP_REQUEST_STRBUF 0
1196 #define HTTP_REQUEST_FILE 1
1198 static int http_request(const char *url
,
1199 void *result
, int target
,
1200 const struct http_get_options
*options
)
1202 struct active_request_slot
*slot
;
1203 struct slot_results results
;
1204 struct curl_slist
*headers
= NULL
;
1205 struct strbuf buf
= STRBUF_INIT
;
1206 const char *accept_language
;
1209 slot
= get_active_slot();
1210 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1212 if (result
== NULL
) {
1213 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
1215 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
1216 curl_easy_setopt(slot
->curl
, CURLOPT_FILE
, result
);
1218 if (target
== HTTP_REQUEST_FILE
) {
1219 long posn
= ftell(result
);
1220 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1223 strbuf_addf(&buf
, "Range: bytes=%ld-", posn
);
1224 headers
= curl_slist_append(headers
, buf
.buf
);
1228 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1232 accept_language
= get_accept_language();
1234 if (accept_language
)
1235 headers
= curl_slist_append(headers
, accept_language
);
1237 strbuf_addstr(&buf
, "Pragma:");
1238 if (options
&& options
->no_cache
)
1239 strbuf_addstr(&buf
, " no-cache");
1240 if (options
&& options
->keep_error
)
1241 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
1243 headers
= curl_slist_append(headers
, buf
.buf
);
1245 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
1246 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
1247 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "gzip");
1249 ret
= run_one_slot(slot
, &results
);
1251 if (options
&& options
->content_type
) {
1252 struct strbuf raw
= STRBUF_INIT
;
1253 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
1254 extract_content_type(&raw
, options
->content_type
,
1256 strbuf_release(&raw
);
1259 if (options
&& options
->effective_url
)
1260 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
1261 options
->effective_url
);
1263 curl_slist_free_all(headers
);
1264 strbuf_release(&buf
);
1270 * Update the "base" url to a more appropriate value, as deduced by
1271 * redirects seen when requesting a URL starting with "url".
1273 * The "asked" parameter is a URL that we asked curl to access, and must begin
1276 * The "got" parameter is the URL that curl reported to us as where we ended
1279 * Returns 1 if we updated the base url, 0 otherwise.
1281 * Our basic strategy is to compare "base" and "asked" to find the bits
1282 * specific to our request. We then strip those bits off of "got" to yield the
1283 * new base. So for example, if our base is "http://example.com/foo.git",
1284 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1285 * with "https://other.example.com/foo.git/info/refs". We would want the
1286 * new URL to become "https://other.example.com/foo.git".
1288 * Note that this assumes a sane redirect scheme. It's entirely possible
1289 * in the example above to end up at a URL that does not even end in
1290 * "info/refs". In such a case we simply punt, as there is not much we can
1291 * do (and such a scheme is unlikely to represent a real git repository,
1292 * which means we are likely about to abort anyway).
1294 static int update_url_from_redirect(struct strbuf
*base
,
1296 const struct strbuf
*got
)
1301 if (!strcmp(asked
, got
->buf
))
1304 if (!skip_prefix(asked
, base
->buf
, &tail
))
1305 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1308 tail_len
= strlen(tail
);
1310 if (got
->len
< tail_len
||
1311 strcmp(tail
, got
->buf
+ got
->len
- tail_len
))
1312 return 0; /* insane redirect scheme */
1315 strbuf_add(base
, got
->buf
, got
->len
- tail_len
);
1319 static int http_request_reauth(const char *url
,
1320 void *result
, int target
,
1321 struct http_get_options
*options
)
1323 int ret
= http_request(url
, result
, target
, options
);
1325 if (options
&& options
->effective_url
&& options
->base_url
) {
1326 if (update_url_from_redirect(options
->base_url
,
1327 url
, options
->effective_url
)) {
1328 credential_from_url(&http_auth
, options
->base_url
->buf
);
1329 url
= options
->effective_url
->buf
;
1333 if (ret
!= HTTP_REAUTH
)
1337 * If we are using KEEP_ERROR, the previous request may have
1338 * put cruft into our output stream; we should clear it out before
1339 * making our next request. We only know how to do this for
1340 * the strbuf case, but that is enough to satisfy current callers.
1342 if (options
&& options
->keep_error
) {
1344 case HTTP_REQUEST_STRBUF
:
1345 strbuf_reset(result
);
1348 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1352 credential_fill(&http_auth
);
1354 return http_request(url
, result
, target
, options
);
1357 int http_get_strbuf(const char *url
,
1358 struct strbuf
*result
,
1359 struct http_get_options
*options
)
1361 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
1365 * Downloads a URL and stores the result in the given file.
1367 * If a previous interrupted download is detected (i.e. a previous temporary
1368 * file is still around) the download is resumed.
1370 static int http_get_file(const char *url
, const char *filename
,
1371 struct http_get_options
*options
)
1374 struct strbuf tmpfile
= STRBUF_INIT
;
1377 strbuf_addf(&tmpfile
, "%s.temp", filename
);
1378 result
= fopen(tmpfile
.buf
, "a");
1380 error("Unable to open local file %s", tmpfile
.buf
);
1385 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
1388 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
1391 strbuf_release(&tmpfile
);
1395 int http_fetch_ref(const char *base
, struct ref
*ref
)
1397 struct http_get_options options
= {0};
1399 struct strbuf buffer
= STRBUF_INIT
;
1402 options
.no_cache
= 1;
1404 url
= quote_ref_url(base
, ref
->name
);
1405 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
1406 strbuf_rtrim(&buffer
);
1407 if (buffer
.len
== 40)
1408 ret
= get_sha1_hex(buffer
.buf
, ref
->old_sha1
);
1409 else if (starts_with(buffer
.buf
, "ref: ")) {
1410 ref
->symref
= xstrdup(buffer
.buf
+ 5);
1415 strbuf_release(&buffer
);
1420 /* Helpers for fetching packs */
1421 static char *fetch_pack_index(unsigned char *sha1
, const char *base_url
)
1424 struct strbuf buf
= STRBUF_INIT
;
1426 if (http_is_verbose
)
1427 fprintf(stderr
, "Getting index for pack %s\n", sha1_to_hex(sha1
));
1429 end_url_with_slash(&buf
, base_url
);
1430 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", sha1_to_hex(sha1
));
1431 url
= strbuf_detach(&buf
, NULL
);
1433 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(sha1
));
1434 tmp
= strbuf_detach(&buf
, NULL
);
1436 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
1437 error("Unable to get pack index %s", url
);
1446 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
1447 unsigned char *sha1
, const char *base_url
)
1449 struct packed_git
*new_pack
;
1450 char *tmp_idx
= NULL
;
1453 if (has_pack_index(sha1
)) {
1454 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
1456 return -1; /* parse_pack_index() already issued error message */
1460 tmp_idx
= fetch_pack_index(sha1
, base_url
);
1464 new_pack
= parse_pack_index(sha1
, tmp_idx
);
1469 return -1; /* parse_pack_index() already issued error message */
1472 ret
= verify_pack_index(new_pack
);
1474 close_pack_index(new_pack
);
1475 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
1482 new_pack
->next
= *packs_head
;
1483 *packs_head
= new_pack
;
1487 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
1489 struct http_get_options options
= {0};
1492 struct strbuf buf
= STRBUF_INIT
;
1493 unsigned char sha1
[20];
1495 end_url_with_slash(&buf
, base_url
);
1496 strbuf_addstr(&buf
, "objects/info/packs");
1497 url
= strbuf_detach(&buf
, NULL
);
1499 options
.no_cache
= 1;
1500 ret
= http_get_strbuf(url
, &buf
, &options
);
1505 while (i
< buf
.len
) {
1509 if (i
+ 52 <= buf
.len
&&
1510 starts_with(data
+ i
, " pack-") &&
1511 starts_with(data
+ i
+ 46, ".pack\n")) {
1512 get_sha1_hex(data
+ i
+ 6, sha1
);
1513 fetch_and_setup_pack_index(packs_head
, sha1
,
1519 while (i
< buf
.len
&& data
[i
] != '\n')
1530 void release_http_pack_request(struct http_pack_request
*preq
)
1532 if (preq
->packfile
!= NULL
) {
1533 fclose(preq
->packfile
);
1534 preq
->packfile
= NULL
;
1536 if (preq
->range_header
!= NULL
) {
1537 curl_slist_free_all(preq
->range_header
);
1538 preq
->range_header
= NULL
;
1545 int finish_http_pack_request(struct http_pack_request
*preq
)
1547 struct packed_git
**lst
;
1548 struct packed_git
*p
= preq
->target
;
1550 struct child_process ip
= CHILD_PROCESS_INIT
;
1551 const char *ip_argv
[8];
1553 close_pack_index(p
);
1555 fclose(preq
->packfile
);
1556 preq
->packfile
= NULL
;
1560 lst
= &((*lst
)->next
);
1561 *lst
= (*lst
)->next
;
1563 tmp_idx
= xstrdup(preq
->tmpfile
);
1564 strcpy(tmp_idx
+ strlen(tmp_idx
) - strlen(".pack.temp"),
1567 ip_argv
[0] = "index-pack";
1569 ip_argv
[2] = tmp_idx
;
1570 ip_argv
[3] = preq
->tmpfile
;
1578 if (run_command(&ip
)) {
1579 unlink(preq
->tmpfile
);
1585 unlink(sha1_pack_index_name(p
->sha1
));
1587 if (finalize_object_file(preq
->tmpfile
, sha1_pack_name(p
->sha1
))
1588 || finalize_object_file(tmp_idx
, sha1_pack_index_name(p
->sha1
))) {
1593 install_packed_git(p
);
1598 struct http_pack_request
*new_http_pack_request(
1599 struct packed_git
*target
, const char *base_url
)
1602 char range
[RANGE_HEADER_SIZE
];
1603 struct strbuf buf
= STRBUF_INIT
;
1604 struct http_pack_request
*preq
;
1606 preq
= xcalloc(1, sizeof(*preq
));
1607 preq
->target
= target
;
1609 end_url_with_slash(&buf
, base_url
);
1610 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
1611 sha1_to_hex(target
->sha1
));
1612 preq
->url
= strbuf_detach(&buf
, NULL
);
1614 snprintf(preq
->tmpfile
, sizeof(preq
->tmpfile
), "%s.temp",
1615 sha1_pack_name(target
->sha1
));
1616 preq
->packfile
= fopen(preq
->tmpfile
, "a");
1617 if (!preq
->packfile
) {
1618 error("Unable to open local file %s for pack",
1623 preq
->slot
= get_active_slot();
1624 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_FILE
, preq
->packfile
);
1625 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
1626 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
1627 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
1631 * If there is data present from a previous transfer attempt,
1632 * resume where it left off
1634 prev_posn
= ftell(preq
->packfile
);
1636 if (http_is_verbose
)
1638 "Resuming fetch of pack %s at byte %ld\n",
1639 sha1_to_hex(target
->sha1
), prev_posn
);
1640 sprintf(range
, "Range: bytes=%ld-", prev_posn
);
1641 preq
->range_header
= curl_slist_append(NULL
, range
);
1642 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
1643 preq
->range_header
);
1654 /* Helpers for fetching objects (loose) */
1655 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
1658 unsigned char expn
[4096];
1659 size_t size
= eltsize
* nmemb
;
1661 struct http_object_request
*freq
=
1662 (struct http_object_request
*)data
;
1664 ssize_t retval
= xwrite(freq
->localfile
,
1665 (char *) ptr
+ posn
, size
- posn
);
1669 } while (posn
< size
);
1671 freq
->stream
.avail_in
= size
;
1672 freq
->stream
.next_in
= (void *)ptr
;
1674 freq
->stream
.next_out
= expn
;
1675 freq
->stream
.avail_out
= sizeof(expn
);
1676 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
1677 git_SHA1_Update(&freq
->c
, expn
,
1678 sizeof(expn
) - freq
->stream
.avail_out
);
1679 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
1683 struct http_object_request
*new_http_object_request(const char *base_url
,
1684 unsigned char *sha1
)
1686 char *hex
= sha1_to_hex(sha1
);
1687 const char *filename
;
1688 char prevfile
[PATH_MAX
];
1690 char prev_buf
[PREV_BUF_SIZE
];
1691 ssize_t prev_read
= 0;
1693 char range
[RANGE_HEADER_SIZE
];
1694 struct curl_slist
*range_header
= NULL
;
1695 struct http_object_request
*freq
;
1697 freq
= xcalloc(1, sizeof(*freq
));
1698 hashcpy(freq
->sha1
, sha1
);
1699 freq
->localfile
= -1;
1701 filename
= sha1_file_name(sha1
);
1702 snprintf(freq
->tmpfile
, sizeof(freq
->tmpfile
),
1703 "%s.temp", filename
);
1705 snprintf(prevfile
, sizeof(prevfile
), "%s.prev", filename
);
1706 unlink_or_warn(prevfile
);
1707 rename(freq
->tmpfile
, prevfile
);
1708 unlink_or_warn(freq
->tmpfile
);
1710 if (freq
->localfile
!= -1)
1711 error("fd leakage in start: %d", freq
->localfile
);
1712 freq
->localfile
= open(freq
->tmpfile
,
1713 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1715 * This could have failed due to the "lazy directory creation";
1716 * try to mkdir the last path component.
1718 if (freq
->localfile
< 0 && errno
== ENOENT
) {
1719 char *dir
= strrchr(freq
->tmpfile
, '/');
1722 mkdir(freq
->tmpfile
, 0777);
1725 freq
->localfile
= open(freq
->tmpfile
,
1726 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1729 if (freq
->localfile
< 0) {
1730 error("Couldn't create temporary file %s: %s",
1731 freq
->tmpfile
, strerror(errno
));
1735 git_inflate_init(&freq
->stream
);
1737 git_SHA1_Init(&freq
->c
);
1739 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
1742 * If a previous temp file is present, process what was already
1745 prevlocal
= open(prevfile
, O_RDONLY
);
1746 if (prevlocal
!= -1) {
1748 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
1750 if (fwrite_sha1_file(prev_buf
,
1753 freq
) == prev_read
) {
1754 prev_posn
+= prev_read
;
1759 } while (prev_read
> 0);
1762 unlink_or_warn(prevfile
);
1765 * Reset inflate/SHA1 if there was an error reading the previous temp
1766 * file; also rewind to the beginning of the local file.
1768 if (prev_read
== -1) {
1769 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
1770 git_inflate_init(&freq
->stream
);
1771 git_SHA1_Init(&freq
->c
);
1774 lseek(freq
->localfile
, 0, SEEK_SET
);
1775 if (ftruncate(freq
->localfile
, 0) < 0) {
1776 error("Couldn't truncate temporary file %s: %s",
1777 freq
->tmpfile
, strerror(errno
));
1783 freq
->slot
= get_active_slot();
1785 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FILE
, freq
);
1786 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
1787 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
1788 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
1789 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
1792 * If we have successfully processed data from a previous fetch
1793 * attempt, only fetch the data we don't already have.
1796 if (http_is_verbose
)
1798 "Resuming fetch of object %s at byte %ld\n",
1800 sprintf(range
, "Range: bytes=%ld-", prev_posn
);
1801 range_header
= curl_slist_append(range_header
, range
);
1802 curl_easy_setopt(freq
->slot
->curl
,
1803 CURLOPT_HTTPHEADER
, range_header
);
1814 void process_http_object_request(struct http_object_request
*freq
)
1816 if (freq
->slot
== NULL
)
1818 freq
->curl_result
= freq
->slot
->curl_result
;
1819 freq
->http_code
= freq
->slot
->http_code
;
1823 int finish_http_object_request(struct http_object_request
*freq
)
1827 close(freq
->localfile
);
1828 freq
->localfile
= -1;
1830 process_http_object_request(freq
);
1832 if (freq
->http_code
== 416) {
1833 warning("requested range invalid; we may already have all the data.");
1834 } else if (freq
->curl_result
!= CURLE_OK
) {
1835 if (stat(freq
->tmpfile
, &st
) == 0)
1836 if (st
.st_size
== 0)
1837 unlink_or_warn(freq
->tmpfile
);
1841 git_inflate_end(&freq
->stream
);
1842 git_SHA1_Final(freq
->real_sha1
, &freq
->c
);
1843 if (freq
->zret
!= Z_STREAM_END
) {
1844 unlink_or_warn(freq
->tmpfile
);
1847 if (hashcmp(freq
->sha1
, freq
->real_sha1
)) {
1848 unlink_or_warn(freq
->tmpfile
);
1852 finalize_object_file(freq
->tmpfile
, sha1_file_name(freq
->sha1
));
1854 return freq
->rename
;
1857 void abort_http_object_request(struct http_object_request
*freq
)
1859 unlink_or_warn(freq
->tmpfile
);
1861 release_http_object_request(freq
);
1864 void release_http_object_request(struct http_object_request
*freq
)
1866 if (freq
->localfile
!= -1) {
1867 close(freq
->localfile
);
1868 freq
->localfile
= -1;
1870 if (freq
->url
!= NULL
) {
1874 if (freq
->slot
!= NULL
) {
1875 freq
->slot
->callback_func
= NULL
;
1876 freq
->slot
->callback_data
= NULL
;
1877 release_active_slot(freq
->slot
);