1 #include "git-compat-util.h"
5 #include "run-command.h"
8 #include "credential.h"
14 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
16 #if LIBCURL_VERSION_NUM >= 0x070a06
17 #define LIBCURL_CAN_HANDLE_AUTH_ANY
20 static int min_curl_sessions = 1;
21 static int curl_session_count;
23 static int max_requests = -1;
26 #ifndef NO_CURL_EASY_DUPHANDLE
27 static CURL *curl_default;
30 #define PREV_BUF_SIZE 4096
31 #define RANGE_HEADER_SIZE 30
33 char curl_errorstr[CURL_ERROR_SIZE];
35 static int curl_ssl_verify = -1;
36 static int curl_ssl_try;
37 static const char *ssl_cert;
38 #if LIBCURL_VERSION_NUM >= 0x070903
39 static const char *ssl_key;
41 #if LIBCURL_VERSION_NUM >= 0x070908
42 static const char *ssl_capath;
44 static const char *ssl_cainfo;
45 static long curl_low_speed_limit = -1;
46 static long curl_low_speed_time = -1;
47 static int curl_ftp_no_epsv;
48 static const char *curl_http_proxy;
49 static const char *curl_cookie_file;
50 static int curl_save_cookies;
51 struct credential http_auth = CREDENTIAL_INIT;
52 static int http_proactive_auth;
53 static const char *user_agent;
55 #if LIBCURL_VERSION_NUM >= 0x071700
56 /* Use CURLOPT_KEYPASSWD as is */
57 #elif LIBCURL_VERSION_NUM >= 0x070903
58 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
60 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
63 static struct credential cert_auth = CREDENTIAL_INIT;
64 static int ssl_cert_password_required;
66 static struct curl_slist *pragma_header;
67 static struct curl_slist *no_pragma_header;
69 static struct active_request_slot *active_queue_head;
71 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
73 size_t size = eltsize * nmemb;
74 struct buffer *buffer = buffer_;
76 if (size > buffer->buf.len - buffer->posn)
77 size = buffer->buf.len - buffer->posn;
78 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
85 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
87 struct buffer *buffer = clientp;
93 case CURLIOCMD_RESTARTREAD:
98 return CURLIOE_UNKNOWNCMD;
103 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
105 size_t size = eltsize * nmemb;
106 struct strbuf *buffer = buffer_;
108 strbuf_add(buffer, ptr, size);
112 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
114 return eltsize * nmemb;
117 #ifdef USE_CURL_MULTI
118 static void process_curl_messages(void)
121 struct active_request_slot *slot;
122 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
124 while (curl_message != NULL) {
125 if (curl_message->msg == CURLMSG_DONE) {
126 int curl_result = curl_message->data.result;
127 slot = active_queue_head;
128 while (slot != NULL &&
129 slot->curl != curl_message->easy_handle)
132 curl_multi_remove_handle(curlm, slot->curl);
133 slot->curl_result = curl_result;
134 finish_active_slot(slot);
136 fprintf(stderr, "Received DONE message for unknown request!\n");
139 fprintf(stderr, "Unknown CURL message received: %d\n",
140 (int)curl_message->msg);
142 curl_message = curl_multi_info_read(curlm, &num_messages);
147 static int http_options(const char *var, const char *value, void *cb)
149 if (!strcmp("http.sslverify", var)) {
150 curl_ssl_verify = git_config_bool(var, value);
153 if (!strcmp("http.sslcert", var))
154 return git_config_string(&ssl_cert, var, value);
155 #if LIBCURL_VERSION_NUM >= 0x070903
156 if (!strcmp("http.sslkey", var))
157 return git_config_string(&ssl_key, var, value);
159 #if LIBCURL_VERSION_NUM >= 0x070908
160 if (!strcmp("http.sslcapath", var))
161 return git_config_string(&ssl_capath, var, value);
163 if (!strcmp("http.sslcainfo", var))
164 return git_config_string(&ssl_cainfo, var, value);
165 if (!strcmp("http.sslcertpasswordprotected", var)) {
166 ssl_cert_password_required = git_config_bool(var, value);
169 if (!strcmp("http.ssltry", var)) {
170 curl_ssl_try = git_config_bool(var, value);
173 if (!strcmp("http.minsessions", var)) {
174 min_curl_sessions = git_config_int(var, value);
175 #ifndef USE_CURL_MULTI
176 if (min_curl_sessions > 1)
177 min_curl_sessions = 1;
181 #ifdef USE_CURL_MULTI
182 if (!strcmp("http.maxrequests", var)) {
183 max_requests = git_config_int(var, value);
187 if (!strcmp("http.lowspeedlimit", var)) {
188 curl_low_speed_limit = (long)git_config_int(var, value);
191 if (!strcmp("http.lowspeedtime", var)) {
192 curl_low_speed_time = (long)git_config_int(var, value);
196 if (!strcmp("http.noepsv", var)) {
197 curl_ftp_no_epsv = git_config_bool(var, value);
200 if (!strcmp("http.proxy", var))
201 return git_config_string(&curl_http_proxy, var, value);
203 if (!strcmp("http.cookiefile", var))
204 return git_config_string(&curl_cookie_file, var, value);
205 if (!strcmp("http.savecookies", var)) {
206 curl_save_cookies = git_config_bool(var, value);
210 if (!strcmp("http.postbuffer", var)) {
211 http_post_buffer = git_config_int(var, value);
212 if (http_post_buffer < LARGE_PACKET_MAX)
213 http_post_buffer = LARGE_PACKET_MAX;
217 if (!strcmp("http.useragent", var))
218 return git_config_string(&user_agent, var, value);
220 /* Fall back on the default ones */
221 return git_default_config(var, value, cb);
224 static void init_curl_http_auth(CURL *result)
226 if (!http_auth.username)
229 credential_fill(&http_auth);
231 #if LIBCURL_VERSION_NUM >= 0x071301
232 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
233 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
236 static struct strbuf up = STRBUF_INIT;
238 * Note that we assume we only ever have a single set of
239 * credentials in a given program run, so we do not have
240 * to worry about updating this buffer, only setting its
244 strbuf_addf(&up, "%s:%s",
245 http_auth.username, http_auth.password);
246 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
251 static int has_cert_password(void)
253 if (ssl_cert == NULL || ssl_cert_password_required != 1)
255 if (!cert_auth.password) {
256 cert_auth.protocol = xstrdup("cert");
257 cert_auth.username = xstrdup("");
258 cert_auth.path = xstrdup(ssl_cert);
259 credential_fill(&cert_auth);
264 #if LIBCURL_VERSION_NUM >= 0x071900
265 static void set_curl_keepalive(CURL *c)
267 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
270 #elif LIBCURL_VERSION_NUM >= 0x071000
271 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
275 socklen_t len = (socklen_t)sizeof(ka);
277 if (type != CURLSOCKTYPE_IPCXN)
280 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
282 warning("unable to set SO_KEEPALIVE on socket %s",
285 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
288 static void set_curl_keepalive(CURL *c)
290 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
294 static void set_curl_keepalive(CURL *c)
296 /* not supported on older curl versions */
300 static CURL *get_curl_handle(void)
302 CURL *result = curl_easy_init();
305 die("curl_easy_init failed");
307 if (!curl_ssl_verify) {
308 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
309 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
311 /* Verify authenticity of the peer's certificate */
312 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
313 /* The name in the cert must match whom we tried to connect */
314 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
317 #if LIBCURL_VERSION_NUM >= 0x070907
318 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
320 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
321 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
324 if (http_proactive_auth)
325 init_curl_http_auth(result);
327 if (ssl_cert != NULL)
328 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
329 if (has_cert_password())
330 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
331 #if LIBCURL_VERSION_NUM >= 0x070903
333 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
335 #if LIBCURL_VERSION_NUM >= 0x070908
336 if (ssl_capath != NULL)
337 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
339 if (ssl_cainfo != NULL)
340 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
342 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
343 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
344 curl_low_speed_limit);
345 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
346 curl_low_speed_time);
349 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
350 #if LIBCURL_VERSION_NUM >= 0x071301
351 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
352 #elif LIBCURL_VERSION_NUM >= 0x071101
353 curl_easy_setopt(result, CURLOPT_POST301, 1);
356 if (getenv("GIT_CURL_VERBOSE"))
357 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
359 curl_easy_setopt(result, CURLOPT_USERAGENT,
360 user_agent ? user_agent : git_user_agent());
362 if (curl_ftp_no_epsv)
363 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
365 #ifdef CURLOPT_USE_SSL
367 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
370 if (curl_http_proxy) {
371 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
372 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
375 set_curl_keepalive(result);
380 static void set_from_env(const char **var, const char *envname)
382 const char *val = getenv(envname);
387 void http_init(struct remote *remote, const char *url, int proactive_auth)
389 char *low_speed_limit;
390 char *low_speed_time;
391 char *normalized_url;
392 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
394 config.section = "http";
396 config.collect_fn = http_options;
397 config.cascade_fn = git_default_config;
401 normalized_url = url_normalize(url, &config.url);
403 git_config(urlmatch_config_entry, &config);
404 free(normalized_url);
406 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
407 die("curl_global_init failed");
409 http_proactive_auth = proactive_auth;
411 if (remote && remote->http_proxy)
412 curl_http_proxy = xstrdup(remote->http_proxy);
414 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
415 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
417 #ifdef USE_CURL_MULTI
419 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
420 if (http_max_requests != NULL)
421 max_requests = atoi(http_max_requests);
424 curlm = curl_multi_init();
426 die("curl_multi_init failed");
429 if (getenv("GIT_SSL_NO_VERIFY"))
432 set_from_env(&ssl_cert, "GIT_SSL_CERT");
433 #if LIBCURL_VERSION_NUM >= 0x070903
434 set_from_env(&ssl_key, "GIT_SSL_KEY");
436 #if LIBCURL_VERSION_NUM >= 0x070908
437 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
439 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
441 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
443 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
444 if (low_speed_limit != NULL)
445 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
446 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
447 if (low_speed_time != NULL)
448 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
450 if (curl_ssl_verify == -1)
453 curl_session_count = 0;
454 #ifdef USE_CURL_MULTI
455 if (max_requests < 1)
456 max_requests = DEFAULT_MAX_REQUESTS;
459 if (getenv("GIT_CURL_FTP_NO_EPSV"))
460 curl_ftp_no_epsv = 1;
463 credential_from_url(&http_auth, url);
464 if (!ssl_cert_password_required &&
465 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
466 starts_with(url, "https://"))
467 ssl_cert_password_required = 1;
470 #ifndef NO_CURL_EASY_DUPHANDLE
471 curl_default = get_curl_handle();
475 void http_cleanup(void)
477 struct active_request_slot *slot = active_queue_head;
479 while (slot != NULL) {
480 struct active_request_slot *next = slot->next;
481 if (slot->curl != NULL) {
482 #ifdef USE_CURL_MULTI
483 curl_multi_remove_handle(curlm, slot->curl);
485 curl_easy_cleanup(slot->curl);
490 active_queue_head = NULL;
492 #ifndef NO_CURL_EASY_DUPHANDLE
493 curl_easy_cleanup(curl_default);
496 #ifdef USE_CURL_MULTI
497 curl_multi_cleanup(curlm);
499 curl_global_cleanup();
501 curl_slist_free_all(pragma_header);
502 pragma_header = NULL;
504 curl_slist_free_all(no_pragma_header);
505 no_pragma_header = NULL;
507 if (curl_http_proxy) {
508 free((void *)curl_http_proxy);
509 curl_http_proxy = NULL;
512 if (cert_auth.password != NULL) {
513 memset(cert_auth.password, 0, strlen(cert_auth.password));
514 free(cert_auth.password);
515 cert_auth.password = NULL;
517 ssl_cert_password_required = 0;
520 struct active_request_slot *get_active_slot(void)
522 struct active_request_slot *slot = active_queue_head;
523 struct active_request_slot *newslot;
525 #ifdef USE_CURL_MULTI
528 /* Wait for a slot to open up if the queue is full */
529 while (active_requests >= max_requests) {
530 curl_multi_perform(curlm, &num_transfers);
531 if (num_transfers < active_requests)
532 process_curl_messages();
536 while (slot != NULL && slot->in_use)
540 newslot = xmalloc(sizeof(*newslot));
541 newslot->curl = NULL;
543 newslot->next = NULL;
545 slot = active_queue_head;
547 active_queue_head = newslot;
549 while (slot->next != NULL)
551 slot->next = newslot;
556 if (slot->curl == NULL) {
557 #ifdef NO_CURL_EASY_DUPHANDLE
558 slot->curl = get_curl_handle();
560 slot->curl = curl_easy_duphandle(curl_default);
562 curl_session_count++;
567 slot->results = NULL;
568 slot->finished = NULL;
569 slot->callback_data = NULL;
570 slot->callback_func = NULL;
571 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
572 if (curl_save_cookies)
573 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
574 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
575 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
576 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
577 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
578 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
579 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
580 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
581 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
582 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
583 if (http_auth.password)
584 init_curl_http_auth(slot->curl);
589 int start_active_slot(struct active_request_slot *slot)
591 #ifdef USE_CURL_MULTI
592 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
595 if (curlm_result != CURLM_OK &&
596 curlm_result != CURLM_CALL_MULTI_PERFORM) {
603 * We know there must be something to do, since we just added
606 curl_multi_perform(curlm, &num_transfers);
611 #ifdef USE_CURL_MULTI
615 struct fill_chain *next;
618 static struct fill_chain *fill_cfg;
620 void add_fill_function(void *data, int (*fill)(void *))
622 struct fill_chain *new = xmalloc(sizeof(*new));
623 struct fill_chain **linkp = &fill_cfg;
628 linkp = &(*linkp)->next;
632 void fill_active_slots(void)
634 struct active_request_slot *slot = active_queue_head;
636 while (active_requests < max_requests) {
637 struct fill_chain *fill;
638 for (fill = fill_cfg; fill; fill = fill->next)
639 if (fill->fill(fill->data))
646 while (slot != NULL) {
647 if (!slot->in_use && slot->curl != NULL
648 && curl_session_count > min_curl_sessions) {
649 curl_easy_cleanup(slot->curl);
651 curl_session_count--;
657 void step_active_slots(void)
660 CURLMcode curlm_result;
663 curlm_result = curl_multi_perform(curlm, &num_transfers);
664 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
665 if (num_transfers < active_requests) {
666 process_curl_messages();
672 void run_active_slot(struct active_request_slot *slot)
674 #ifdef USE_CURL_MULTI
679 struct timeval select_timeout;
682 slot->finished = &finished;
687 #if LIBCURL_VERSION_NUM >= 0x070f04
689 curl_multi_timeout(curlm, &curl_timeout);
690 if (curl_timeout == 0) {
692 } else if (curl_timeout == -1) {
693 select_timeout.tv_sec = 0;
694 select_timeout.tv_usec = 50000;
696 select_timeout.tv_sec = curl_timeout / 1000;
697 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
700 select_timeout.tv_sec = 0;
701 select_timeout.tv_usec = 50000;
708 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
711 * It can happen that curl_multi_timeout returns a pathologically
712 * long timeout when curl_multi_fdset returns no file descriptors
713 * to read. See commit message for more details.
716 (select_timeout.tv_sec > 0 ||
717 select_timeout.tv_usec > 50000)) {
718 select_timeout.tv_sec = 0;
719 select_timeout.tv_usec = 50000;
722 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
726 while (slot->in_use) {
727 slot->curl_result = curl_easy_perform(slot->curl);
728 finish_active_slot(slot);
733 static void closedown_active_slot(struct active_request_slot *slot)
739 static void release_active_slot(struct active_request_slot *slot)
741 closedown_active_slot(slot);
742 if (slot->curl && curl_session_count > min_curl_sessions) {
743 #ifdef USE_CURL_MULTI
744 curl_multi_remove_handle(curlm, slot->curl);
746 curl_easy_cleanup(slot->curl);
748 curl_session_count--;
750 #ifdef USE_CURL_MULTI
755 void finish_active_slot(struct active_request_slot *slot)
757 closedown_active_slot(slot);
758 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
760 if (slot->finished != NULL)
761 (*slot->finished) = 1;
763 /* Store slot results so they can be read after the slot is reused */
764 if (slot->results != NULL) {
765 slot->results->curl_result = slot->curl_result;
766 slot->results->http_code = slot->http_code;
767 #if LIBCURL_VERSION_NUM >= 0x070a08
768 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
769 &slot->results->auth_avail);
771 slot->results->auth_avail = 0;
775 /* Run callback if appropriate */
776 if (slot->callback_func != NULL)
777 slot->callback_func(slot->callback_data);
780 void finish_all_active_slots(void)
782 struct active_request_slot *slot = active_queue_head;
786 run_active_slot(slot);
787 slot = active_queue_head;
793 /* Helpers for modifying and creating URLs */
794 static inline int needs_quote(int ch)
796 if (((ch >= 'A') && (ch <= 'Z'))
797 || ((ch >= 'a') && (ch <= 'z'))
798 || ((ch >= '0') && (ch <= '9'))
806 static char *quote_ref_url(const char *base, const char *ref)
808 struct strbuf buf = STRBUF_INIT;
812 end_url_with_slash(&buf, base);
814 for (cp = ref; (ch = *cp) != 0; cp++)
816 strbuf_addf(&buf, "%%%02x", ch);
818 strbuf_addch(&buf, *cp);
820 return strbuf_detach(&buf, NULL);
823 void append_remote_object_url(struct strbuf *buf, const char *url,
825 int only_two_digit_prefix)
827 end_url_with_slash(buf, url);
829 strbuf_addf(buf, "objects/%.*s/", 2, hex);
830 if (!only_two_digit_prefix)
831 strbuf_addf(buf, "%s", hex+2);
834 char *get_remote_object_url(const char *url, const char *hex,
835 int only_two_digit_prefix)
837 struct strbuf buf = STRBUF_INIT;
838 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
839 return strbuf_detach(&buf, NULL);
842 int handle_curl_result(struct slot_results *results)
845 * If we see a failing http code with CURLE_OK, we have turned off
846 * FAILONERROR (to keep the server's custom error response), and should
847 * translate the code into failure here.
849 if (results->curl_result == CURLE_OK &&
850 results->http_code >= 400) {
851 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
853 * Normally curl will already have put the "reason phrase"
854 * from the server into curl_errorstr; unfortunately without
855 * FAILONERROR it is lost, so we can give only the numeric
858 snprintf(curl_errorstr, sizeof(curl_errorstr),
859 "The requested URL returned error: %ld",
863 if (results->curl_result == CURLE_OK) {
864 credential_approve(&http_auth);
866 } else if (missing_target(results))
867 return HTTP_MISSING_TARGET;
868 else if (results->http_code == 401) {
869 if (http_auth.username && http_auth.password) {
870 credential_reject(&http_auth);
876 #if LIBCURL_VERSION_NUM >= 0x070c00
877 if (!curl_errorstr[0])
878 strlcpy(curl_errorstr,
879 curl_easy_strerror(results->curl_result),
880 sizeof(curl_errorstr));
886 int run_one_slot(struct active_request_slot *slot,
887 struct slot_results *results)
889 slot->results = results;
890 if (!start_active_slot(slot)) {
891 snprintf(curl_errorstr, sizeof(curl_errorstr),
892 "failed to start HTTP request");
893 return HTTP_START_FAILED;
896 run_active_slot(slot);
897 return handle_curl_result(results);
900 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
906 ret = curl_easy_getinfo(curl, info, &ptr);
908 strbuf_addstr(buf, ptr);
913 * Check for and extract a content-type parameter. "raw"
914 * should be positioned at the start of the potential
915 * parameter, with any whitespace already removed.
917 * "name" is the name of the parameter. The value is appended
920 static int extract_param(const char *raw, const char *name,
923 size_t len = strlen(name);
925 if (strncasecmp(raw, name, len))
933 while (*raw && !isspace(*raw) && *raw != ';')
934 strbuf_addch(out, *raw++);
939 * Extract a normalized version of the content type, with any
940 * spaces suppressed, all letters lowercased, and no trailing ";"
943 * Note that we will silently remove even invalid whitespace. For
944 * example, "text / plain" is specifically forbidden by RFC 2616,
945 * but "text/plain" is the only reasonable output, and this keeps
948 * If the "charset" argument is not NULL, store the value of any
949 * charset parameter there.
952 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
953 * "text / plain" -> "text/plain"
955 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
956 struct strbuf *charset)
961 strbuf_grow(type, raw->len);
962 for (p = raw->buf; *p; p++) {
969 strbuf_addch(type, tolower(*p));
975 strbuf_reset(charset);
977 while (isspace(*p) || *p == ';')
979 if (!extract_param(p, "charset", charset))
981 while (*p && !isspace(*p))
985 if (!charset->len && starts_with(type->buf, "text/"))
986 strbuf_addstr(charset, "ISO-8859-1");
989 /* http_request() targets */
990 #define HTTP_REQUEST_STRBUF 0
991 #define HTTP_REQUEST_FILE 1
993 static int http_request(const char *url,
994 void *result, int target,
995 const struct http_get_options *options)
997 struct active_request_slot *slot;
998 struct slot_results results;
999 struct curl_slist *headers = NULL;
1000 struct strbuf buf = STRBUF_INIT;
1003 slot = get_active_slot();
1004 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1006 if (result == NULL) {
1007 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1009 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1010 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1012 if (target == HTTP_REQUEST_FILE) {
1013 long posn = ftell(result);
1014 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1017 strbuf_addf(&buf, "Range: bytes=%ld-", posn);
1018 headers = curl_slist_append(headers, buf.buf);
1022 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1026 strbuf_addstr(&buf, "Pragma:");
1027 if (options && options->no_cache)
1028 strbuf_addstr(&buf, " no-cache");
1029 if (options && options->keep_error)
1030 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1032 headers = curl_slist_append(headers, buf.buf);
1034 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1035 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1036 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1038 ret = run_one_slot(slot, &results);
1040 if (options && options->content_type) {
1041 struct strbuf raw = STRBUF_INIT;
1042 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1043 extract_content_type(&raw, options->content_type,
1045 strbuf_release(&raw);
1048 if (options && options->effective_url)
1049 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1050 options->effective_url);
1052 curl_slist_free_all(headers);
1053 strbuf_release(&buf);
1059 * Update the "base" url to a more appropriate value, as deduced by
1060 * redirects seen when requesting a URL starting with "url".
1062 * The "asked" parameter is a URL that we asked curl to access, and must begin
1065 * The "got" parameter is the URL that curl reported to us as where we ended
1068 * Returns 1 if we updated the base url, 0 otherwise.
1070 * Our basic strategy is to compare "base" and "asked" to find the bits
1071 * specific to our request. We then strip those bits off of "got" to yield the
1072 * new base. So for example, if our base is "http://example.com/foo.git",
1073 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1074 * with "https://other.example.com/foo.git/info/refs". We would want the
1075 * new URL to become "https://other.example.com/foo.git".
1077 * Note that this assumes a sane redirect scheme. It's entirely possible
1078 * in the example above to end up at a URL that does not even end in
1079 * "info/refs". In such a case we simply punt, as there is not much we can
1080 * do (and such a scheme is unlikely to represent a real git repository,
1081 * which means we are likely about to abort anyway).
1083 static int update_url_from_redirect(struct strbuf *base,
1085 const struct strbuf *got)
1090 if (!strcmp(asked, got->buf))
1093 if (!skip_prefix(asked, base->buf, &tail))
1094 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1097 tail_len = strlen(tail);
1099 if (got->len < tail_len ||
1100 strcmp(tail, got->buf + got->len - tail_len))
1101 return 0; /* insane redirect scheme */
1104 strbuf_add(base, got->buf, got->len - tail_len);
1108 static int http_request_reauth(const char *url,
1109 void *result, int target,
1110 struct http_get_options *options)
1112 int ret = http_request(url, result, target, options);
1114 if (options && options->effective_url && options->base_url) {
1115 if (update_url_from_redirect(options->base_url,
1116 url, options->effective_url)) {
1117 credential_from_url(&http_auth, options->base_url->buf);
1118 url = options->effective_url->buf;
1122 if (ret != HTTP_REAUTH)
1126 * If we are using KEEP_ERROR, the previous request may have
1127 * put cruft into our output stream; we should clear it out before
1128 * making our next request. We only know how to do this for
1129 * the strbuf case, but that is enough to satisfy current callers.
1131 if (options && options->keep_error) {
1133 case HTTP_REQUEST_STRBUF:
1134 strbuf_reset(result);
1137 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1141 credential_fill(&http_auth);
1143 return http_request(url, result, target, options);
1146 int http_get_strbuf(const char *url,
1147 struct strbuf *result,
1148 struct http_get_options *options)
1150 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1154 * Downloads a URL and stores the result in the given file.
1156 * If a previous interrupted download is detected (i.e. a previous temporary
1157 * file is still around) the download is resumed.
1159 static int http_get_file(const char *url, const char *filename,
1160 struct http_get_options *options)
1163 struct strbuf tmpfile = STRBUF_INIT;
1166 strbuf_addf(&tmpfile, "%s.temp", filename);
1167 result = fopen(tmpfile.buf, "a");
1169 error("Unable to open local file %s", tmpfile.buf);
1174 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1177 if (ret == HTTP_OK && move_temp_to_file(tmpfile.buf, filename))
1180 strbuf_release(&tmpfile);
1184 int http_fetch_ref(const char *base, struct ref *ref)
1186 struct http_get_options options = {0};
1188 struct strbuf buffer = STRBUF_INIT;
1191 options.no_cache = 1;
1193 url = quote_ref_url(base, ref->name);
1194 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1195 strbuf_rtrim(&buffer);
1196 if (buffer.len == 40)
1197 ret = get_sha1_hex(buffer.buf, ref->old_sha1);
1198 else if (starts_with(buffer.buf, "ref: ")) {
1199 ref->symref = xstrdup(buffer.buf + 5);
1204 strbuf_release(&buffer);
1209 /* Helpers for fetching packs */
1210 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1213 struct strbuf buf = STRBUF_INIT;
1215 if (http_is_verbose)
1216 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1218 end_url_with_slash(&buf, base_url);
1219 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1220 url = strbuf_detach(&buf, NULL);
1222 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1223 tmp = strbuf_detach(&buf, NULL);
1225 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1226 error("Unable to get pack index %s", url);
1235 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1236 unsigned char *sha1, const char *base_url)
1238 struct packed_git *new_pack;
1239 char *tmp_idx = NULL;
1242 if (has_pack_index(sha1)) {
1243 new_pack = parse_pack_index(sha1, NULL);
1245 return -1; /* parse_pack_index() already issued error message */
1249 tmp_idx = fetch_pack_index(sha1, base_url);
1253 new_pack = parse_pack_index(sha1, tmp_idx);
1258 return -1; /* parse_pack_index() already issued error message */
1261 ret = verify_pack_index(new_pack);
1263 close_pack_index(new_pack);
1264 ret = move_temp_to_file(tmp_idx, sha1_pack_index_name(sha1));
1271 new_pack->next = *packs_head;
1272 *packs_head = new_pack;
1276 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1278 struct http_get_options options = {0};
1281 struct strbuf buf = STRBUF_INIT;
1282 unsigned char sha1[20];
1284 end_url_with_slash(&buf, base_url);
1285 strbuf_addstr(&buf, "objects/info/packs");
1286 url = strbuf_detach(&buf, NULL);
1288 options.no_cache = 1;
1289 ret = http_get_strbuf(url, &buf, &options);
1294 while (i < buf.len) {
1298 if (i + 52 <= buf.len &&
1299 starts_with(data + i, " pack-") &&
1300 starts_with(data + i + 46, ".pack\n")) {
1301 get_sha1_hex(data + i + 6, sha1);
1302 fetch_and_setup_pack_index(packs_head, sha1,
1308 while (i < buf.len && data[i] != '\n')
1319 void release_http_pack_request(struct http_pack_request *preq)
1321 if (preq->packfile != NULL) {
1322 fclose(preq->packfile);
1323 preq->packfile = NULL;
1325 if (preq->range_header != NULL) {
1326 curl_slist_free_all(preq->range_header);
1327 preq->range_header = NULL;
1333 int finish_http_pack_request(struct http_pack_request *preq)
1335 struct packed_git **lst;
1336 struct packed_git *p = preq->target;
1338 struct child_process ip = CHILD_PROCESS_INIT;
1339 const char *ip_argv[8];
1341 close_pack_index(p);
1343 fclose(preq->packfile);
1344 preq->packfile = NULL;
1348 lst = &((*lst)->next);
1349 *lst = (*lst)->next;
1351 tmp_idx = xstrdup(preq->tmpfile);
1352 strcpy(tmp_idx + strlen(tmp_idx) - strlen(".pack.temp"),
1355 ip_argv[0] = "index-pack";
1357 ip_argv[2] = tmp_idx;
1358 ip_argv[3] = preq->tmpfile;
1366 if (run_command(&ip)) {
1367 unlink(preq->tmpfile);
1373 unlink(sha1_pack_index_name(p->sha1));
1375 if (move_temp_to_file(preq->tmpfile, sha1_pack_name(p->sha1))
1376 || move_temp_to_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1381 install_packed_git(p);
1386 struct http_pack_request *new_http_pack_request(
1387 struct packed_git *target, const char *base_url)
1390 char range[RANGE_HEADER_SIZE];
1391 struct strbuf buf = STRBUF_INIT;
1392 struct http_pack_request *preq;
1394 preq = xcalloc(1, sizeof(*preq));
1395 preq->target = target;
1397 end_url_with_slash(&buf, base_url);
1398 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1399 sha1_to_hex(target->sha1));
1400 preq->url = strbuf_detach(&buf, NULL);
1402 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1403 sha1_pack_name(target->sha1));
1404 preq->packfile = fopen(preq->tmpfile, "a");
1405 if (!preq->packfile) {
1406 error("Unable to open local file %s for pack",
1411 preq->slot = get_active_slot();
1412 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1413 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1414 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1415 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1419 * If there is data present from a previous transfer attempt,
1420 * resume where it left off
1422 prev_posn = ftell(preq->packfile);
1424 if (http_is_verbose)
1426 "Resuming fetch of pack %s at byte %ld\n",
1427 sha1_to_hex(target->sha1), prev_posn);
1428 sprintf(range, "Range: bytes=%ld-", prev_posn);
1429 preq->range_header = curl_slist_append(NULL, range);
1430 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1431 preq->range_header);
1442 /* Helpers for fetching objects (loose) */
1443 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1446 unsigned char expn[4096];
1447 size_t size = eltsize * nmemb;
1449 struct http_object_request *freq =
1450 (struct http_object_request *)data;
1452 ssize_t retval = xwrite(freq->localfile,
1453 (char *) ptr + posn, size - posn);
1457 } while (posn < size);
1459 freq->stream.avail_in = size;
1460 freq->stream.next_in = (void *)ptr;
1462 freq->stream.next_out = expn;
1463 freq->stream.avail_out = sizeof(expn);
1464 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1465 git_SHA1_Update(&freq->c, expn,
1466 sizeof(expn) - freq->stream.avail_out);
1467 } while (freq->stream.avail_in && freq->zret == Z_OK);
1471 struct http_object_request *new_http_object_request(const char *base_url,
1472 unsigned char *sha1)
1474 char *hex = sha1_to_hex(sha1);
1475 const char *filename;
1476 char prevfile[PATH_MAX];
1478 char prev_buf[PREV_BUF_SIZE];
1479 ssize_t prev_read = 0;
1481 char range[RANGE_HEADER_SIZE];
1482 struct curl_slist *range_header = NULL;
1483 struct http_object_request *freq;
1485 freq = xcalloc(1, sizeof(*freq));
1486 hashcpy(freq->sha1, sha1);
1487 freq->localfile = -1;
1489 filename = sha1_file_name(sha1);
1490 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1491 "%s.temp", filename);
1493 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1494 unlink_or_warn(prevfile);
1495 rename(freq->tmpfile, prevfile);
1496 unlink_or_warn(freq->tmpfile);
1498 if (freq->localfile != -1)
1499 error("fd leakage in start: %d", freq->localfile);
1500 freq->localfile = open(freq->tmpfile,
1501 O_WRONLY | O_CREAT | O_EXCL, 0666);
1503 * This could have failed due to the "lazy directory creation";
1504 * try to mkdir the last path component.
1506 if (freq->localfile < 0 && errno == ENOENT) {
1507 char *dir = strrchr(freq->tmpfile, '/');
1510 mkdir(freq->tmpfile, 0777);
1513 freq->localfile = open(freq->tmpfile,
1514 O_WRONLY | O_CREAT | O_EXCL, 0666);
1517 if (freq->localfile < 0) {
1518 error("Couldn't create temporary file %s: %s",
1519 freq->tmpfile, strerror(errno));
1523 git_inflate_init(&freq->stream);
1525 git_SHA1_Init(&freq->c);
1527 freq->url = get_remote_object_url(base_url, hex, 0);
1530 * If a previous temp file is present, process what was already
1533 prevlocal = open(prevfile, O_RDONLY);
1534 if (prevlocal != -1) {
1536 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1538 if (fwrite_sha1_file(prev_buf,
1541 freq) == prev_read) {
1542 prev_posn += prev_read;
1547 } while (prev_read > 0);
1550 unlink_or_warn(prevfile);
1553 * Reset inflate/SHA1 if there was an error reading the previous temp
1554 * file; also rewind to the beginning of the local file.
1556 if (prev_read == -1) {
1557 memset(&freq->stream, 0, sizeof(freq->stream));
1558 git_inflate_init(&freq->stream);
1559 git_SHA1_Init(&freq->c);
1562 lseek(freq->localfile, 0, SEEK_SET);
1563 if (ftruncate(freq->localfile, 0) < 0) {
1564 error("Couldn't truncate temporary file %s: %s",
1565 freq->tmpfile, strerror(errno));
1571 freq->slot = get_active_slot();
1573 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1574 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1575 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1576 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1577 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1580 * If we have successfully processed data from a previous fetch
1581 * attempt, only fetch the data we don't already have.
1584 if (http_is_verbose)
1586 "Resuming fetch of object %s at byte %ld\n",
1588 sprintf(range, "Range: bytes=%ld-", prev_posn);
1589 range_header = curl_slist_append(range_header, range);
1590 curl_easy_setopt(freq->slot->curl,
1591 CURLOPT_HTTPHEADER, range_header);
1602 void process_http_object_request(struct http_object_request *freq)
1604 if (freq->slot == NULL)
1606 freq->curl_result = freq->slot->curl_result;
1607 freq->http_code = freq->slot->http_code;
1611 int finish_http_object_request(struct http_object_request *freq)
1615 close(freq->localfile);
1616 freq->localfile = -1;
1618 process_http_object_request(freq);
1620 if (freq->http_code == 416) {
1621 warning("requested range invalid; we may already have all the data.");
1622 } else if (freq->curl_result != CURLE_OK) {
1623 if (stat(freq->tmpfile, &st) == 0)
1624 if (st.st_size == 0)
1625 unlink_or_warn(freq->tmpfile);
1629 git_inflate_end(&freq->stream);
1630 git_SHA1_Final(freq->real_sha1, &freq->c);
1631 if (freq->zret != Z_STREAM_END) {
1632 unlink_or_warn(freq->tmpfile);
1635 if (hashcmp(freq->sha1, freq->real_sha1)) {
1636 unlink_or_warn(freq->tmpfile);
1640 move_temp_to_file(freq->tmpfile, sha1_file_name(freq->sha1));
1642 return freq->rename;
1645 void abort_http_object_request(struct http_object_request *freq)
1647 unlink_or_warn(freq->tmpfile);
1649 release_http_object_request(freq);
1652 void release_http_object_request(struct http_object_request *freq)
1654 if (freq->localfile != -1) {
1655 close(freq->localfile);
1656 freq->localfile = -1;
1658 if (freq->url != NULL) {
1662 if (freq->slot != NULL) {
1663 freq->slot->callback_func = NULL;
1664 freq->slot->callback_data = NULL;
1665 release_active_slot(freq->slot);